app("Mod for deserial_rce_DENY"):
	requires(version: ARMR/2.2)
	marshal("deserial_rce_DENY"):
		deserialize(dotnet, java)
		rce()
		protect(message: "", severity: Medium)
	endmarshal
endapp
app("Mod for process_all_DENY"):
	requires(version: ARMR/2.2)
	process("process_all_DENY"):
		execute("C:\Windows\System32\NETSTAT.EXE")
		protect(message: "", severity: Medium)
	endprocess
endapp
app("Mod for process_list_WHITELIST"):
	requires(version: ARMR/2.2)
	process("process_list_WHITELIST"):
		execute("*")
		allow(severity: Medium)
	endprocess
endapp
app("Mod for deserial_dos_PROTECT"):
	requires(version: ARMR/2.2)
	marshal("deserial_dos_PROTECT"):
		deserialize(dotnet, java)
		dos()
		protect(message: "", severity: Medium)
	endmarshal
endapp
app("Mod for sqli_oracle_PROTECT"):
	requires(version: ARMR/2.2)
	sql("sqli_oracle_PROTECT"):
		vendor(oracle)
		input(http, database, deserialization)
		injection(successful-attempt)
		protect(message: "", severity: Medium)
	endsql
endapp
app("Mod for xss_all_DENY"):
	requires(version: ARMR/2.2)
	http("xss_all_DENY"):
		response(paths: ["*"])
		input(http, database, deserialization)
		xss(html, options: {policy: loose})
		protect(message: "", severity: Medium)
	endhttp
endapp
app("Mod for bind_all_ALLOW"):
	requires(version: ARMR/2.2)
	socket("bind_all_ALLOW"):
		bind(client: "0.0.0.0:0", server: "0.0.0.0:0")
		allow(message: "", severity: Medium)
	endsocket
endapp
app("Mod for redirect_all_PROTECT"):
	requires(version: ARMR/2.2)
	http("redirect_all_PROTECT"):
		response(paths: ["*"])
		input(http, database, deserialization)
		open-redirect()
		protect(message: "", severity: Medium)
	endhttp
endapp
app("Mod for traversal_both_PROTECT"):
	requires(version: ARMR/2.2)
	filesystem("traversal_both_PROTECT"):
		input(http, database, deserialization)
		traversal()
		protect(message: "", severity: Medium)
	endfilesystem
endapp

app("WEBLOGIC"):
    requires(version: "ARMR/2.2")

    /***************************************************************************
        CVE-2020-14882 (WEBLOGIC)
        CVE-2020-14883
        CVE-2020-14750

        CVSS 3.0 Summary:
            Base Score              | 9.8 CRITICAL
            Attack Vector           | Network
            Attack Complexity       | Low
            Privileges Required     | None
            User Interaction        | None
            Scope                   | Unchanged
            Confidentiality Impact  | High
            Integrity Impact        | High
            Availability Impact     | High

        Description:
            Vulnerability in the Oracle WebLogic Server product of Oracle Fusion
            Middleware (component: Console). Easily exploitable vulnerability
            allows unauthenticated attacker with network access via HTTP to
            compromise Oracle WebLogic Server. Successful attacks of this
            vulnerability can result in takeover of Oracle WebLogic Server.

        Resources:
            https://www.oracle.com/security-alerts/cpuoct2020traditional.html#AppendixFMW
            https://www.oracle.com/security-alerts/alert-cve-2020-14750.html
            https://nvd.nist.gov/vuln/detail/CVE-2020-14882
            https://testbnull.medium.com/weblogic-rce-by-only-one-get-request-cve-2020-14882-analysis-6e4b09981dbf
            https://isc.sans.edu/forums/diary/PATCH+NOW+CVE202014882+Weblogic+Actively+Exploited+Against+Honeypots/26734
            https://twitter.com/chybeta/status/1322131143034957826
            https://www.buaq.net/go-43706.html
            https://github.com/jas502n/CVE-2020-14882
            https://attackerkb.com/topics/mzyS1rMcZc/cve-2020-14750-oracle-weblogic-remote-unauthenticated-remote-code-execution-rce-vulnerability?referrer=activityFeed

        Affected Operating System:
            Any

        Affected Versions:
            10.3.6.0.0, 12.1.3.0.0, 12.2.1.3.0, 12.2.1.4.0, 14.1.1.0.0

        Fixed Version:
            2020 OCTOBER CPU Releases

        Tested Versions:
            12.2.1.4

        Protection Provided:
            Functional (based on available information)

        Patch Version:
            1.2
    ***************************************************************************/

    patch("CVE-2020-14882 :01"):
        function("com/bea/console/utils/MBeanUtilsInitSingleFileServlet.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V")
        entry()

        code(language: java,   import: ["java.util.*",
                                        "javax.servlet.ServletRequest",
                                        "javax.servlet.http.HttpServletRequest",
                                        "javax.servlet.ServletResponse",
                                        "javax.servlet.http.HttpServletResponse",
                                        "javax.servlet.ServletException",
                                        "java.io.IOException",
                                        "com.bea.console.utils.MBeanUtils",
                                        "weblogic.management.configuration.DomainMBean",
                                        "weblogic.utils.http.HttpParsing"]):
            private static final String DEFAULT_CONSOLE_CONTEXT_PATH = "console";
            private static final String VALID_PORTAL_NAMES_PROPERTY = "weblogic.console.validPortalNames";
            private static final Set<String> ALLOWED_URI_SET = getAllowedURIs();

            public void patch(JavaFrame frame) {
                try {
                    Object reqRef = frame.loadObjectVariable(1);
                    if(!(reqRef instanceof HttpServletRequest)) {
                        return;
                    }
                    HttpServletRequest req = (HttpServletRequest) reqRef;
                    String requestURI = req.getRequestURI();
                    // 01: Block non authenticated users
                    if (req.getUserPrincipal() == null) {
                        cefAlert("A non authenticated user attempted to access a console URI related to CVE-2020-14882", requestURI);
                        frame.raiseException(new ServletException("User not authenticated."));
                        return;
                    }
                    // 02: Block URIs that are not allowed
                    if (!isURIAllowed(requestURI)) {
                        cefAlert("An attempt was made to access a malformed console URI related to CVE-2020-14882", requestURI);
                        send404Response(frame);
                        return;
                    }
                    // 03: Block URIs that contain '..'
                    String uri = requestURI;
                    while(uri.contains("%")) {
                        String unescaped = HttpParsing.unescape(uri, "UTF-8");
                        if (uri.equals(unescaped)) {
                            break;
                        }
                        uri = unescaped;
                    }
                    if (uri.contains("..")) {
                        cefAlert("An attempt was made to access a malformed console URI related to CVE-2020-14882", requestURI);
                        send404Response(frame);
                        return;
                    }
                } catch (IOException ex) {
                    frame.raiseException(ex);
                }
            }

            private boolean isURIAllowed(String uri) {
                for (String allowedURI : ALLOWED_URI_SET) {
                    if (allowedURI.equals(uri)) {
                        return true;
                    }
                }
                return false;
            }

            private void send404Response(JavaFrame frame)
                    throws IOException {
                ServletResponse res = (ServletResponse) frame.loadObjectVariable(2);
                if (res instanceof HttpServletResponse) {
                    ((HttpServletResponse) res).sendError(404);
                }
                frame.returnVoid();
            }

            private void cefAlert(String msg, String uri) {
                ArmrEvent event = ArmrEvent.load("Vulnerability Alert", "high");
                event.addExtension("msg", msg);
                event.addExtension("uri", uri);
                event.addExtension("act", "Denied");
                event.commit();
            }

            private static Set<String> getAllowedURIs() {
                String consoleContextPath;
                try {
                    DomainMBean domain = MBeanUtils.getDomainMBean();
                    consoleContextPath = domain.getConsoleContextPath();
                } catch (Exception ex) {
                    consoleContextPath = DEFAULT_CONSOLE_CONTEXT_PATH;
                }
                Set<String> trustedConsoleURIs = getTrustedConsoleURIs();
                Set<String> allowedURIs = new HashSet<String>();
                for (String uri : trustedConsoleURIs) {
                    String allowedURI = "/" + consoleContextPath + uri;
                    allowedURIs.add(allowedURI);
                }
                return allowedURIs;
            }

            private static Set<String> getTrustedConsoleURIs() {
                Set<String> trustedConsoleURIs = new HashSet<String>();
                String validPortalNames = System.getProperty(VALID_PORTAL_NAMES_PROPERTY);
                if (validPortalNames != null && !validPortalNames.trim().isEmpty()) {
                    String[] names = validPortalNames.split(",");
                    for (String name : names) {
                        trustedConsoleURIs.add(name.trim());
                    }
                }
                trustedConsoleURIs.add("/console.portal");
                trustedConsoleURIs.add("/consolejndi.portal");
                return trustedConsoleURIs;
            }
        endcode
    endpatch

    patch("CVE-2020-14882 :02"):
        function("com/bea/console/handles/HandleFactory.getHandle(Ljava/lang/String;)Lcom/bea/console/handles/Handle;")
        callreturn("weblogic/utils/http/HttpParsing.unescape(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;")

        code(language: java):
            // This is a collection of partial namespaces that are known to
            // be used in a malicious way. HandleFactory should only be used
            // with namespaces/classes that implement
            // 'com.bea.console.handles.Handle'.
            private static final String[] ILLEGAL_SERIALIZED = new String[] {
                "lang.Runtime", "lang.ProcessBuilder", "lang.reflect",
                "tangosol", "springframework"
            };

            public void patch(JavaFrame frame) {
                String serialized = frame.loadStringOperand(0);
                for (String illegal : ILLEGAL_SERIALIZED) {
                    if (serialized.contains(illegal)) {
                        ArmrEvent event = ArmrEvent.load("Vulnerability Alert", "high");
                        event.addExtension("msg", "An attempt was made to use an illegal 'handle' value related to CVE-2020-14882");
                        event.addExtension("value", serialized);
                        event.addExtension("act", "Denied");
                        event.commit();
                        frame.raiseException(new Exception("Invalid Handle Class detected."));
                    }
                }
            }
        endcode
    endpatch

    patch("CVE-2020-14882 :03"):
        function("com/bea/console/handles/HandleFactory.getHandle(Ljava/lang/String;)Lcom/bea/console/handles/Handle;")
        callreturn("java/lang/Class.forName(Ljava/lang/String;)Ljava/lang/Class;")

        code(language: java,   import: ["com.bea.console.handles.Handle"]):
            public void patch(JavaFrame frame) {
                Class<?> handleClass = (Class<?>) frame.loadObjectOperand(0);
                if (!Handle.class.isAssignableFrom(handleClass)) {
                    ArmrEvent event = ArmrEvent.load("Vulnerability Alert", "high");
                    event.addExtension("msg", "An attempt was made to use a class that does not implement 'com.bea.console.handles.Handle' related to CVE-2020-14882");
                    event.addExtension("className", handleClass.getName());
                    event.addExtension("act", "Denied");
                    event.commit();
                    frame.raiseException(new Exception("Invalid Handle Class detected."));
                }
            }
        endcode
    endpatch

endapp

app("CSRF Same Origin Mod"):
  requires(version: ARMR/2.2)
  http("CSRF Same Origin"):
    request()
    csrf(same-origin)
    protect(message: "CSRF Same Origin validation failed", severity: High)
  endhttp
endapp