コード例 #1
0
    def bind(self, packet, bind):
        # Standard NDR Representation
        NDRSyntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
        resp = dcerpc.MSRPCBindAck()

        resp['type'] = dcerpc.MSRPC_BINDACK
        resp['flags'] = packet['flags']
        resp['frag_len'] = 0
        resp['auth_len'] = 0
        resp['auth_data'] = ''
        resp['call_id'] = packet['call_id']
        resp['max_tfrag'] = bind['max_tfrag']
        resp['max_rfrag'] = bind['max_rfrag']
        resp['assoc_group'] = 0x1234
        resp['SecondaryAddrLen'] = 13
        resp['SecondaryAddr'] = '\\PIPE\\srvsvc'
        resp['Pad'] = 'A' * ((4 - (
            (resp["SecondaryAddrLen"] + dcerpc.MSRPCBindAck._SIZE) % 4)) % 4)
        resp['ctx_num'] = 0

        data = bind['ctx_items']
        ctx_items = ''
        for i in range(bind['ctx_num']):
            result = dcerpc.MSRPC_CONT_RESULT_USER_REJECT
            item = dcerpc.CtxItem(data)
            data = data[len(item):]

            # First we check the Transfer Syntax is NDR32, what we support
            #print "Trying to bind to: %s %s / %s %s" % (bin_to_uuidtup(item['AbstractSyntax']) + bin_to_uuidtup(item['TransferSyntax'])),

            if item['TransferSyntax'] == uuidtup_to_bin(NDRSyntax):
                # Now Check if the interface is what we listen
                reason = 1  # Default, Abstract Syntax not supported
                for i in self._listenUUIDS:
                    if item['AbstractSyntax'] == i:
                        # Match, we accept the bind request
                        reason = 0
                        self._boundUUID = i
            else:
                # Fail the bind request for this context
                reason = 2  # Transfer Syntax not supported
            if reason == 0:
                result = dcerpc.MSRPC_CONT_RESULT_ACCEPT
                #print "... OK!"
            #else:
            #   print "... ERROR!"

            resp['ctx_num'] += 1
            itemResult = dcerpc.CtxItemResult()
            itemResult['Result'] = result
            itemResult['Reason'] = reason
            itemResult['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
            ctx_items += str(itemResult)

        resp['ctx_items'] = ctx_items
        resp['frag_len'] = len(str(resp))

        self._clientSock.send(str(resp))
        return None
コード例 #2
0
 def test_hept_map(self):
     MSRPC_UUID_SAMR   = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))
     resp = epm.hept_map(self.machine,MSRPC_UUID_SAMR)
     resp = epm.hept_map(self.machine, MSRPC_UUID_SAMR, protocol = 'ncacn_ip_tcp')
     MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))
     resp = epm.hept_map(self.machine,MSRPC_UUID_ATSVC)
     MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))
     resp = epm.hept_map(self.machine,MSRPC_UUID_SCMR, protocol = 'ncacn_ip_tcp')
コード例 #3
0
ファイル: srvsvcserver.py プロジェクト: LucaBongiorni/MITMf
    def bind(self,packet, bind):
        # Standard NDR Representation
        NDRSyntax   = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
        resp = dcerpc.MSRPCBindAck()

        resp['type']             = dcerpc.MSRPC_BINDACK
        resp['flags']            = packet['flags']
        resp['frag_len']         = 0
        resp['auth_len']         = 0
        resp['auth_data']        = ''
        resp['call_id']          = packet['call_id'] 
        resp['max_tfrag']        = bind['max_tfrag']
        resp['max_rfrag']        = bind['max_rfrag']
        resp['assoc_group']      = 0x1234
        resp['SecondaryAddrLen'] = 13
        resp['SecondaryAddr']    = '\\PIPE\\srvsvc'
        resp['Pad']              ='A'*((4-((resp["SecondaryAddrLen"]+dcerpc.MSRPCBindAck._SIZE) % 4))%4)
        resp['ctx_num']          = 0

        data      = bind['ctx_items']
        ctx_items = ''
        for i in range(bind['ctx_num']):
            result = dcerpc.MSRPC_CONT_RESULT_USER_REJECT
            item   = dcerpc.CtxItem(data)
            data   = data[len(item):]

            # First we check the Transfer Syntax is NDR32, what we support
            #print "Trying to bind to: %s %s / %s %s" % (bin_to_uuidtup(item['AbstractSyntax']) + bin_to_uuidtup(item['TransferSyntax'])),

            if item['TransferSyntax'] == uuidtup_to_bin(NDRSyntax):
                # Now Check if the interface is what we listen
                reason = 1 # Default, Abstract Syntax not supported
                for i in self._listenUUIDS:
                    if item['AbstractSyntax'] == i:
                        # Match, we accept the bind request
                        reason           = 0
                        self._boundUUID = i
            else:
                # Fail the bind request for this context
                reason = 2 # Transfer Syntax not supported
            if reason == 0:
               result = dcerpc.MSRPC_CONT_RESULT_ACCEPT
               #print "... OK!"
            #else:
            #   print "... ERROR!"

            resp['ctx_num']             += 1
            itemResult                   = dcerpc.CtxItemResult()
            itemResult['Result']         = result
            itemResult['Reason']         = reason
            itemResult['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
            ctx_items                   += str(itemResult)

        resp['ctx_items'] = ctx_items
        resp['frag_len']  = len(str(resp))

        self._clientSock.send(str(resp)) 
        return None
コード例 #4
0
 def test_hlookup(self):
     resp = epm.hept_lookup(self.machine)
     #for entry in resp:
     #    print epm.PrintStringBinding(entry['tower']['Floors'], self.machine)
     MSRPC_UUID_SAMR   = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))
     resp = epm.hept_lookup(self.machine, inquiry_type = epm.RPC_C_EP_MATCH_BY_IF, ifId = MSRPC_UUID_SAMR)
     MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))
     resp = epm.hept_lookup(self.machine, inquiry_type = epm.RPC_C_EP_MATCH_BY_IF, ifId = MSRPC_UUID_ATSVC)
     MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))
     resp = epm.hept_lookup(self.machine, inquiry_type = epm.RPC_C_EP_MATCH_BY_IF, ifId = MSRPC_UUID_SCMR)
コード例 #5
0
ファイル: test_dcomrt.py プロジェクト: Liljhon241/MITMf
 def test_RemoteGetClassObject(self):
     dce, rpctransport = self.connect()
     IID_IClassFactory = uuidtup_to_bin(
         ('00000001-0000-0000-C000-000000000046', '0.0'))
     scm = dcomrt.IRemoteSCMActivator(dce)
     iInterface = scm.RemoteGetClassObject(comev.CLSID_EventSystem,
                                           IID_IClassFactory)
     iInterface.RemRelease()
コード例 #6
0
ファイル: atsvc.py プロジェクト: LucaBongiorni/MITMf
#   Best way to learn how to use these calls is to grab the protocol standard
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, UCHAR, ULONG, LPDWORD, NULL
from mitmflib.impacket import hresult_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_ATSVC  = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B','1.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'TSCH SessionError: unknown error code: 0x%x' % self.error_code

################################################################################
コード例 #7
0
# Description:
#   [MS-SRVS] interface implementation.
#
# TODO: NetServerEnum2

import array
from struct import *
import exceptions

from mitmflib.impacket import ImpactPacket
from mitmflib.impacket.structure import Structure
from mitmflib.impacket import dcerpc
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SRVSVC = uuidtup_to_bin(
    ('4B324FC8-1670-01D3-1278-5A47BF6EE188', '3.0'))

# Error Codes
ERROR_ACCESS_DENIED = 0x00000005
ERROR_INVALID_LEVEL = 0x0000007C
ERROR_INVALID_PARAMETER = 0x00000057
ERROR_MORE_DATA = 0x000000EA
ERROR_NOT_ENOUGH_MEMORY = 0x00000000
ERROR_FILE_NOT_FOUND = 0x00000002
ERROR_DUP_NAME = 0x00000034
ERROR_INVALID_DOMAINNAME = 0x000004BC
ERROR_NOT_SUPPORTED = 0x00000032
ERROR_SERVICE_DOES_NOT_EXIST = 0x00000424
NERR_BufTooSmall = 0x0000084B
NERR_ClientNameNotFound = 0x00000908
NERR_InvalidComputer = 0x0000092F
コード例 #8
0
ファイル: scmr.py プロジェクト: Liljhon241/MITMf
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from struct import pack

from mitmflib.impacket import system_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDR, NDRSTRUCT, NDRPOINTER, NDRPOINTERNULL, NDRUniConformantArray, NDRUNION
from mitmflib.impacket.dcerpc.v5.dtypes import NULL, DWORD, LPWSTR, ULONG, BOOL, LPBYTE, ULONGLONG, PGUID, USHORT, LPDWORD, WSTR, \
    GUID, PBOOL, WIDESTR
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_SCMR = uuidtup_to_bin(
    ('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if system_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = system_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]
            return 'SCMR SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'SCMR SessionError: unknown error code: 0x%x' % self.error_code
コード例 #9
0
ファイル: mgmt.py プロジェクト: Liljhon241/MITMf
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray, NDRUniConformantVaryingArray
from mitmflib.impacket.dcerpc.v5.epm import PRPC_IF_ID
from mitmflib.impacket.dcerpc.v5.dtypes import ULONG, DWORD_ARRAY, ULONGLONG
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket import nt_errors

MSRPC_UUID_MGMT = uuidtup_to_bin(
    ('afa8bd80-7d8a-11c9-bef4-08002b102989', '1.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if nt_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1]
            return 'MGMT SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'MGMT SessionError: unknown error code: 0x%x' % self.error_code
コード例 #10
0
ファイル: lsarpc.py プロジェクト: LucaBongiorni/MITMf
# Author: Pablo A. Schachner
#         Alberto Solino
#
# Description:
#   LSARPC interface implementation.
#

from mitmflib.impacket.structure import Structure
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket.dcerpc.samr import SAMR_RPC_SID_IDENTIFIER_AUTHORITY, SAMR_RPC_SID
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.nt_errors import ERROR_MESSAGES
import random
from struct import pack, unpack

MSRPC_UUID_LSARPC = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AB','0.0'))

# Constants

# POLICY_INFORMATION_CLASS
POLICY_AUDIT_LOG_INFORMATION            = 1
POLICY_AUDIT_EVENTS_INFORMATION         = 2
POLICY_PRIMARY_DOMAIN_INFORMATION       = 3
POLICY_PD_ACCOUNT_INFORMATION           = 4
POLICY_ACCOUNT_DOMAIN_INFORMATION       = 5
POLICY_LSA_SERVER_ROLE_INFORMATION      = 6
POLICY_REPLICA_SOURCE_INFORMATION       = 7
POLICY_DEFAULT_QUOTA_INFORMATION        = 8
POLICY_MODIFICATION_INFORMATION         = 9
POLICY_AUDIT_FULL_SET_INFORMATION       = 10
POLICY_AUDIT_FULL_QUERY_INFORMATION     = 11
コード例 #11
0
# for more information.
#
# $Id$
#
# Author: Alberto Solino
#
# Description:
#   WKSSVC interface implementation.
#

from mitmflib.impacket.structure import Structure
from mitmflib.impacket import dcerpc
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_WKSSVC = uuidtup_to_bin(
    ('6BFFD098-A112-3610-9833-46C3F87E345A', '1.0'))


class WKSTA_TRANSPORT_INFO_0(Structure):
    structure = (
        ('UnUsed', '<L'),
        ('NumberOfRemoteConnections', '<L'),
        ('RefId1', '<L'),
        ('RefId2', '<L'),
        ('IsRoutableTransport', '<L'),
        #       ('TransportName',':',ndrutils.NDRStringW),
        #       ('TransportAddress',':',ndrutils.NDRStringW),
    )


class WKSSVCNetrWkstaTransportEnum(Structure):
コード例 #12
0
ファイル: samr.py プロジェクト: LucaBongiorni/MITMf
# Author: Alberto Solino
#
# Description:
#   SAMR (Security Account Manager Remote) interface implementation.
#

import array
from time import strftime, gmtime
from struct import *

from mitmflib.impacket import ImpactPacket
from mitmflib.impacket.dcerpc import ndrutils, dcerpc
from mitmflib.impacket.structure import Structure
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SAMR   = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))

KNOWN_SIDS = {
}

OP_NUM_CREATE_USER_IN_DOMAIN    = 0xC
OP_NUM_ENUM_USERS_IN_DOMAIN     = 0xD
OP_NUM_CREATE_ALIAS_IN_DOMAIN   = 0xE

def display_time(filetime_high, filetime_low, minutes_utc=0):
    if filetime_low == 4294967295L:
        r = "Infinity"
        return r 
    d = filetime_high*4.0*1.0*(1<<30)
    d += filetime_low
    d *= 1.0e-7
コード例 #13
0
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id$
#

import array
import struct

from mitmflib.impacket import ImpactPacket
from mitmflib.impacket import uuid
from mitmflib.impacket import dcerpc
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket.dcerpc import transport

MSRPC_UUID_MGMT = uuid.uuidtup_to_bin(("afa8bd80-7d8a-11c9-bef4-08002b102989", "1.0"))

class IfIdsRequestHeader(ImpactPacket.Header):
    OP_NUM = 0

    def get_header_size(self):
        return 0

class IdIdsResponseHeader(ImpactPacket.Header):
    __SIZE = 12

    def __init__(self, aBuffer = None):
        ImpactPacket.Header.__init__(self, IdIdsResponseHeader.__SIZE)
        self.endianness = '<'
        if aBuffer: self.load_header(aBuffer)
コード例 #14
0
ファイル: printer.py プロジェクト: Liljhon241/MITMf
# This library will be deprecated soon. You should use impacket.dcerpc.v5      #
# classes instead                                                              #
################################################################################
# Copyright (c) 2003-2012 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id$
#

from mitmflib.impacket.structure import Structure
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SPOOLSS = uuidtup_to_bin(
    ('12345678-1234-ABCD-EF00-0123456789AB', '1.0'))


def zeroize(s):
    return '\x00'.join(str(s)) + '\x00'


class SpoolSS_DevModeContainer(Structure):
    alignment = 4
    structure = (
        ('cbBuf', '<L-DevMode'),
        ('pDevMode', '<L&DevMode'),
        ('DevMode', ':'),
    )

コード例 #15
0
ファイル: tsch.py プロジェクト: Liljhon241/MITMf
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, ULONG, WSTR, NULL, GUID, PSYSTEMTIME, SYSTEMTIME
from mitmflib.impacket.structure import Structure
from mitmflib.impacket import hresult_errors, system_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_TSCHS = uuidtup_to_bin(
    ('86D35949-83C9-4044-B424-DB363231FD0C', '1.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        elif system_errors.ERROR_MESSAGES.has_key(key & 0xffff):
            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xffff][0]
コード例 #16
0
ファイル: dcerpc.py プロジェクト: LucaBongiorni/MITMf
    def bind(self, uuid, alter = 0, bogus_binds = 0):
        bind = MSRPCBind()
        # Standard NDR Representation
        NDRSyntax   = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
        # NDR 64
        NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0') 
        #item['TransferSyntax']['Version'] = 1
        ctx = self._ctx
        for i in range(bogus_binds):
            item = CtxItem()
            item['ContextID'] = ctx
            item['TransItems'] = 1
            item['ContextID'] = ctx
            # We generate random UUIDs for bogus binds
            item['AbstractSyntax'] = generate() + stringver_to_bin('2.0')
            item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
            bind.addCtxItem(item)
            self._ctx += 1
            ctx += 1

        # The true one :)
        item = CtxItem()
        item['AbstractSyntax'] = uuid
        item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
        item['ContextID'] = ctx
        item['TransItems'] = 1
        bind.addCtxItem(item)

        packet = MSRPCHeader()
        packet['type'] = MSRPC_BIND
        packet['pduData'] = str(bind)
        packet['call_id'] = self.__callid

        if alter:
            packet['type'] = MSRPC_ALTERCTX

        if (self.__auth_level != RPC_C_AUTHN_LEVEL_NONE):
            if (self.__username is None) or (self.__password is None):
                self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__TGT, self.__TGS = self._transport.get_credentials()
            if self.__auth_type == RPC_C_AUTHN_WINNT:
                auth = ntlm.getNTLMSSPType1('', self.__domain, signingRequired = True, use_ntlmv2 = self._transport.doesSupportNTLMv2())
            elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
                from mitmflib.impacket.dcerpc import netlogon
                auth = netlogon.getSSPType1(self.__username[:-1], self.__domain, signingRequired = True)

            sec_trailer = SEC_TRAILER()
            sec_trailer['auth_type']   = self.__auth_type
            sec_trailer['auth_level']  = self.__auth_level
            sec_trailer['auth_ctx_id'] = self._ctx + 79231 

            pad = (4 - (len(packet.get_packet()) % 4)) % 4
            if pad != 0:
               packet['pduData'] = packet['pduData'] + '\xFF'*pad
               sec_trailer['auth_pad_len']=pad

            packet['sec_trailer'] = sec_trailer
            packet['auth_data'] = str(auth)

        self._transport.send(packet.get_packet())

        s = self._transport.recv()

        if s != 0:
            resp = MSRPCHeader(s)
        else:
            return 0 #mmm why not None?

        if resp['type'] == MSRPC_BINDACK or resp['type'] == MSRPC_ALTERCTX_R:
            bindResp = MSRPCBindAck(str(resp))
        elif resp['type'] == MSRPC_BINDNAK:
            resp = MSRPCBindNak(resp['pduData'])
            status_code = resp['RejectedReason']
            if rpc_status_codes.has_key(status_code):
                raise Exception(rpc_status_codes[status_code], resp)
            elif rpc_provider_reason.has_key(status_code):
                raise Exception("Bind context rejected: %s" % rpc_provider_reason[status_code])
            else:
                raise Exception('Unknown DCE RPC fault status code: %.8x' % status_code, resp)
        else:
            raise Exception('Unknown DCE RPC packet type received: %d' % resp['type'])

        # check ack results for each context, except for the bogus ones
        for ctx in range(bogus_binds+1,bindResp['ctx_num']+1):
            result = bindResp.getCtxItem(ctx)['Result']
            if result != 0:
                msg = "Bind context %d rejected: " % ctx
                msg += rpc_cont_def_result.get(result, 'Unknown DCE RPC context result code: %.4x' % result)
                msg += "; "
                reason = bindResp.getCtxItem(ctx)['Reason']
                msg += rpc_provider_reason.get(reason, 'Unknown reason code: %.4x' % reason)
                if (result, reason) == (2, 1): # provider_rejection, abstract syntax not supported
                    msg += " (this usually means the interface isn't listening on the given endpoint)"
                raise Exception(msg, resp)

        self.__max_xmit_size = bindResp['max_tfrag']

        if self.__auth_level != RPC_C_AUTHN_LEVEL_NONE:
            if self.__auth_type == RPC_C_AUTHN_WINNT:
                response, randomSessionKey = ntlm.getNTLMSSPType3(auth, bindResp['auth_data'], self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, use_ntlmv2 = self._transport.doesSupportNTLMv2())
                self.__flags = response['flags']
            elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
                response = None

            self.__sequence = 0

            if self.__auth_level in (RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY):
                if self.__auth_type == RPC_C_AUTHN_WINNT:
                    if self.__flags & ntlm.NTLMSSP_NTLM2_KEY:
                        self.__clientSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey)
                        self.__serverSigningKey = ntlm.SIGNKEY(self.__flags, randomSessionKey,"Server")
                        self.__clientSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey)
                        self.__serverSealingKey = ntlm.SEALKEY(self.__flags, randomSessionKey,"Server")
                        # Preparing the keys handle states
                        cipher3 = ARC4.new(self.__clientSealingKey)
                        self.__clientSealingHandle = cipher3.encrypt
                        cipher4 = ARC4.new(self.__serverSealingKey)
                        self.__serverSealingHandle = cipher4.encrypt
                    else:
                        # Same key for everything
                        self.__clientSigningKey = randomSessionKey
                        self.__serverSigningKey = randomSessionKey
                        self.__clientSealingKey = randomSessionKey
                        self.__serverSealingKey = randomSessionKey
                        cipher = ARC4.new(self.__clientSigningKey)
                        self.__clientSealingHandle = cipher.encrypt
                        self.__serverSealingHandle = cipher.encrypt
                elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
                    pass

            sec_trailer = SEC_TRAILER()
            sec_trailer['auth_type'] = self.__auth_type
            sec_trailer['auth_level'] = self.__auth_level
            sec_trailer['auth_ctx_id'] = self._ctx + 79231 

            if response is not None:
                auth3 = MSRPCHeader()
                auth3['type'] = MSRPC_AUTH3
                # pad (4 bytes): Can be set to any arbitrary value when set and MUST be 
                # ignored on receipt. The pad field MUST be immediately followed by a 
                # sec_trailer structure whose layout, location, and alignment are as 
                # specified in section 2.2.2.11
                auth3['pduData'] = '    '
                auth3['sec_trailer'] = sec_trailer
                auth3['auth_data'] = str(response)

                # Use the same call_id
                self.__callid = resp['call_id']
                auth3['call_id'] = self.__callid
                self._transport.send(auth3.get_packet(), forceWriteAndx = 1)

            self.__callid += 1

        return resp     # means packet is signed, if verifier is wrong it fails
コード例 #17
0
ファイル: tsch.py プロジェクト: LucaBongiorni/MITMf
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, ULONG, WSTR, NULL, GUID, PSYSTEMTIME, SYSTEMTIME
from mitmflib.impacket.structure import Structure
from mitmflib.impacket import hresult_errors, system_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_TSCHS  = uuidtup_to_bin(('86D35949-83C9-4044-B424-DB363231FD0C','1.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        elif system_errors.ERROR_MESSAGES.has_key(key & 0xffff):
            error_msg_short = system_errors.ERROR_MESSAGES[key & 0xffff][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key & 0xffff][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
コード例 #18
0
 def addCallbacks(self, UUID, callbacks):
     # Format is [opnum] =  callback
     self._callbacks[uuidtup_to_bin(UUID)] = callbacks
     self._listenUUIDS.append(uuidtup_to_bin(UUID))
コード例 #19
0
ファイル: rrp.py プロジェクト: LucaBongiorni/MITMf
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from struct import unpack

from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantVaryingArray, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, UUID, ULONG, LPULONG, BOOLEAN, SECURITY_INFORMATION, PFILETIME, \
    RPC_UNICODE_STRING, FILETIME, NULL, MAXIMUM_ALLOWED, OWNER_SECURITY_INFORMATION, PWCHAR, PRPC_UNICODE_STRING
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException
from mitmflib.impacket import system_errors
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_RRP = uuidtup_to_bin(('338CD001-2244-31F1-AAAA-900038001003', '1.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if system_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = system_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] 
            return 'RRP SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'RRP SessionError: unknown error code: 0x%x' % self.error_code

################################################################################
コード例 #20
0
ファイル: srvsvcserver.py プロジェクト: LucaBongiorni/MITMf
 def addCallbacks(self, UUID, callbacks):
     # Format is [opnum] =  callback
     self._callbacks[uuidtup_to_bin(UUID)] = callbacks
     self._listenUUIDS.append(uuidtup_to_bin(UUID))
コード例 #21
0
ファイル: winreg.py プロジェクト: LucaBongiorni/MITMf
# Description:
#   WinReg (Windows Registry) interface implementation.
#
# ToDo:
# [ ] Port all this to structure. Check svcctl.py

import array
import struct

from mitmflib.impacket import dcerpc
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket import ImpactPacket
from mitmflib.impacket.uuid import uuidtup_to_bin


MSRPC_UUID_WINREG = uuidtup_to_bin(("338CD001-2244-31F1-AAAA-900038001003", "1.0"))

# Registry Security Access Mask values
KEY_CREATE_LINK = 0x20
KEY_CREATE_SUB_KEY = 0x04
KEY_ENUMERATE_SUB_KEYS = 0x08
KEY_EXECUTE = 0x20019
KEY_NOTIFY = 0x10
KEY_QUERY_VALUE = 0x01
KEY_SET_VALUE = 0x02
KEY_ALL_ACCESS = 0xF003F
KEY_READ = 0x20019
KEY_WRITE = 0x20006

# Registry Data types
REG_NONE = 0  # No value type
コード例 #22
0
ファイル: scmr.py プロジェクト: LucaBongiorni/MITMf
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from struct import pack

from mitmflib.impacket import system_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDR, NDRSTRUCT, NDRPOINTER, NDRPOINTERNULL, NDRUniConformantArray, NDRUNION
from mitmflib.impacket.dcerpc.v5.dtypes import NULL, DWORD, LPWSTR, ULONG, BOOL, LPBYTE, ULONGLONG, PGUID, USHORT, LPDWORD, WSTR, \
    GUID, PBOOL, WIDESTR
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if system_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = system_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1] 
            return 'SCMR SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'SCMR SessionError: unknown error code: 0x%x' % self.error_code

################################################################################
コード例 #23
0
ファイル: wkssvc.py プロジェクト: LucaBongiorni/MITMf
# for more information.
#
# $Id$
#
# Author: Alberto Solino
#
# Description:
#   WKSSVC interface implementation.
#

from mitmflib.impacket.structure import Structure
from mitmflib.impacket import dcerpc
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_WKSSVC = uuidtup_to_bin(('6BFFD098-A112-3610-9833-46C3F87E345A','1.0'))

class WKSTA_TRANSPORT_INFO_0(Structure):
    structure = (
       ('UnUsed','<L'),
       ('NumberOfRemoteConnections','<L'),
       ('RefId1','<L'),
       ('RefId2','<L'),
       ('IsRoutableTransport','<L'),
#       ('TransportName',':',ndrutils.NDRStringW),
#       ('TransportAddress',':',ndrutils.NDRStringW),
    )

class WKSSVCNetrWkstaTransportEnum(Structure):
    opnum = 5
    alignment = 4
コード例 #24
0
ファイル: samr.py プロジェクト: Liljhon241/MITMf
# Author: Alberto Solino
#
# Description:
#   SAMR (Security Account Manager Remote) interface implementation.
#

import array
from time import strftime, gmtime
from struct import *

from mitmflib.impacket import ImpactPacket
from mitmflib.impacket.dcerpc import ndrutils, dcerpc
from mitmflib.impacket.structure import Structure
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SAMR = uuidtup_to_bin(
    ('12345778-1234-ABCD-EF00-0123456789AC', '1.0'))

KNOWN_SIDS = {}

OP_NUM_CREATE_USER_IN_DOMAIN = 0xC
OP_NUM_ENUM_USERS_IN_DOMAIN = 0xD
OP_NUM_CREATE_ALIAS_IN_DOMAIN = 0xE


def display_time(filetime_high, filetime_low, minutes_utc=0):
    if filetime_low == 4294967295L:
        r = "Infinity"
        return r
    d = filetime_high * 4.0 * 1.0 * (1 << 30)
    d += filetime_low
    d *= 1.0e-7
コード例 #25
0
ファイル: mgmt.py プロジェクト: LucaBongiorni/MITMf
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray, NDRUniConformantVaryingArray
from mitmflib.impacket.dcerpc.v5.epm import PRPC_IF_ID
from mitmflib.impacket.dcerpc.v5.dtypes import ULONG, DWORD_ARRAY, ULONGLONG
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket import nt_errors

MSRPC_UUID_MGMT  = uuidtup_to_bin(('afa8bd80-7d8a-11c9-bef4-08002b102989','1.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if nt_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = nt_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] 
            return 'MGMT SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'MGMT SessionError: unknown error code: 0x%x' % self.error_code

################################################################################
コード例 #26
0
#
# $Id$
#
# Author: Alberto Solino
#
# Description:
#   ATSVC implementation of some methods [MS-TSCH]
#

from struct import *
from mitmflib.impacket.structure import Structure
from mitmflib.impacket import dcerpc
from mitmflib.impacket.dcerpc import ndrutils, dcerpc
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))
MSRPC_UUID_SASEC = uuidtup_to_bin(('378E52B0-C0A9-11CF-822D-00AA0051E40F', '1.0'))
MSRPC_UUID_TSS   = uuidtup_to_bin(('86D35949-83C9-4044-B424-DB363231FD0C', '1.0'))

# Constants
S_OK                      = 0x00000000
S_FALSE                   = 0x00000001
E_OUTOFMEMORY             = 0x80000002
E_ACCESSDENIED            = 0x80000009
E_INVALIDARG              = 0x80000003
E_FAIL                    = 0x80000008
E_UNEXPECTED              = 0x8000FFFF

# Structures

class AT_INFO(Structure):
コード例 #27
0
ファイル: printer.py プロジェクト: LucaBongiorni/MITMf
# This library will be deprecated soon. You should use impacket.dcerpc.v5      #
# classes instead                                                              #
################################################################################
# Copyright (c) 2003-2012 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id$
#

from mitmflib.impacket.structure import Structure
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_SPOOLSS   = uuidtup_to_bin(('12345678-1234-ABCD-EF00-0123456789AB', '1.0'))

def zeroize(s):
    return '\x00'.join(str(s)) + '\x00'

class SpoolSS_DevModeContainer(Structure):
    alignment = 4
    structure = (
            ('cbBuf','<L-DevMode'),
            ('pDevMode','<L&DevMode'),
            ('DevMode',':'),
        )

class SpoolSS_OpenPrinter(Structure):
    alignment = 4
    opnum = 1
コード例 #28
0
ファイル: rrp.py プロジェクト: Liljhon241/MITMf
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from struct import unpack

from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantVaryingArray, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, UUID, ULONG, LPULONG, BOOLEAN, SECURITY_INFORMATION, PFILETIME, \
    RPC_UNICODE_STRING, FILETIME, NULL, MAXIMUM_ALLOWED, OWNER_SECURITY_INFORMATION, PWCHAR, PRPC_UNICODE_STRING
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException
from mitmflib.impacket import system_errors
from mitmflib.impacket.uuid import uuidtup_to_bin

MSRPC_UUID_RRP = uuidtup_to_bin(
    ('338CD001-2244-31F1-AAAA-900038001003', '1.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if system_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = system_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = system_errors.ERROR_MESSAGES[key][1]
            return 'RRP SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'RRP SessionError: unknown error code: 0x%x' % self.error_code
コード例 #29
0
ファイル: test_dcomrt.py プロジェクト: LucaBongiorni/MITMf
 def test_RemoteGetClassObject(self):
     dce, rpctransport = self.connect()
     IID_IClassFactory = uuidtup_to_bin(('00000001-0000-0000-C000-000000000046','0.0'))
     scm = dcomrt.IRemoteSCMActivator(dce)
     iInterface = scm.RemoteGetClassObject(comev.CLSID_EventSystem, IID_IClassFactory)
     iInterface.RemRelease()
コード例 #30
0
#   Best way to learn how to use these calls is to grab the protocol standard
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT, NDRPOINTER, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, UCHAR, ULONG, LPDWORD, NULL
from mitmflib.impacket import hresult_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_ATSVC = uuidtup_to_bin(
    ('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'TSCH SessionError: unknown error code: 0x%x' % self.error_code
コード例 #31
0
# Author: Pablo A. Schachner
#         Alberto Solino
#
# Description:
#   LSARPC interface implementation.
#

from mitmflib.impacket.structure import Structure
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket.dcerpc.samr import SAMR_RPC_SID_IDENTIFIER_AUTHORITY, SAMR_RPC_SID
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.nt_errors import ERROR_MESSAGES
import random
from struct import pack, unpack

MSRPC_UUID_LSARPC = uuidtup_to_bin(
    ('12345778-1234-ABCD-EF00-0123456789AB', '0.0'))

# Constants

# POLICY_INFORMATION_CLASS
POLICY_AUDIT_LOG_INFORMATION = 1
POLICY_AUDIT_EVENTS_INFORMATION = 2
POLICY_PRIMARY_DOMAIN_INFORMATION = 3
POLICY_PD_ACCOUNT_INFORMATION = 4
POLICY_ACCOUNT_DOMAIN_INFORMATION = 5
POLICY_LSA_SERVER_ROLE_INFORMATION = 6
POLICY_REPLICA_SOURCE_INFORMATION = 7
POLICY_DEFAULT_QUOTA_INFORMATION = 8
POLICY_MODIFICATION_INFORMATION = 9
POLICY_AUDIT_FULL_SET_INFORMATION = 10
POLICY_AUDIT_FULL_QUERY_INFORMATION = 11
コード例 #32
0
ファイル: dcerpc.py プロジェクト: Liljhon241/MITMf
    def bind(self, uuid, alter=0, bogus_binds=0):
        bind = MSRPCBind()
        # Standard NDR Representation
        NDRSyntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')
        # NDR 64
        NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0')
        #item['TransferSyntax']['Version'] = 1
        ctx = self._ctx
        for i in range(bogus_binds):
            item = CtxItem()
            item['ContextID'] = ctx
            item['TransItems'] = 1
            item['ContextID'] = ctx
            # We generate random UUIDs for bogus binds
            item['AbstractSyntax'] = generate() + stringver_to_bin('2.0')
            item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
            bind.addCtxItem(item)
            self._ctx += 1
            ctx += 1

        # The true one :)
        item = CtxItem()
        item['AbstractSyntax'] = uuid
        item['TransferSyntax'] = uuidtup_to_bin(NDRSyntax)
        item['ContextID'] = ctx
        item['TransItems'] = 1
        bind.addCtxItem(item)

        packet = MSRPCHeader()
        packet['type'] = MSRPC_BIND
        packet['pduData'] = str(bind)
        packet['call_id'] = self.__callid

        if alter:
            packet['type'] = MSRPC_ALTERCTX

        if (self.__auth_level != RPC_C_AUTHN_LEVEL_NONE):
            if (self.__username is None) or (self.__password is None):
                self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__TGT, self.__TGS = self._transport.get_credentials(
                )
            if self.__auth_type == RPC_C_AUTHN_WINNT:
                auth = ntlm.getNTLMSSPType1(
                    '',
                    self.__domain,
                    signingRequired=True,
                    use_ntlmv2=self._transport.doesSupportNTLMv2())
            elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
                from mitmflib.impacket.dcerpc import netlogon
                auth = netlogon.getSSPType1(self.__username[:-1],
                                            self.__domain,
                                            signingRequired=True)

            sec_trailer = SEC_TRAILER()
            sec_trailer['auth_type'] = self.__auth_type
            sec_trailer['auth_level'] = self.__auth_level
            sec_trailer['auth_ctx_id'] = self._ctx + 79231

            pad = (4 - (len(packet.get_packet()) % 4)) % 4
            if pad != 0:
                packet['pduData'] = packet['pduData'] + '\xFF' * pad
                sec_trailer['auth_pad_len'] = pad

            packet['sec_trailer'] = sec_trailer
            packet['auth_data'] = str(auth)

        self._transport.send(packet.get_packet())

        s = self._transport.recv()

        if s != 0:
            resp = MSRPCHeader(s)
        else:
            return 0  #mmm why not None?

        if resp['type'] == MSRPC_BINDACK or resp['type'] == MSRPC_ALTERCTX_R:
            bindResp = MSRPCBindAck(str(resp))
        elif resp['type'] == MSRPC_BINDNAK:
            resp = MSRPCBindNak(resp['pduData'])
            status_code = resp['RejectedReason']
            if rpc_status_codes.has_key(status_code):
                raise Exception(rpc_status_codes[status_code], resp)
            elif rpc_provider_reason.has_key(status_code):
                raise Exception("Bind context rejected: %s" %
                                rpc_provider_reason[status_code])
            else:
                raise Exception(
                    'Unknown DCE RPC fault status code: %.8x' % status_code,
                    resp)
        else:
            raise Exception('Unknown DCE RPC packet type received: %d' %
                            resp['type'])

        # check ack results for each context, except for the bogus ones
        for ctx in range(bogus_binds + 1, bindResp['ctx_num'] + 1):
            result = bindResp.getCtxItem(ctx)['Result']
            if result != 0:
                msg = "Bind context %d rejected: " % ctx
                msg += rpc_cont_def_result.get(
                    result,
                    'Unknown DCE RPC context result code: %.4x' % result)
                msg += "; "
                reason = bindResp.getCtxItem(ctx)['Reason']
                msg += rpc_provider_reason.get(
                    reason, 'Unknown reason code: %.4x' % reason)
                if (result, reason) == (
                        2, 1
                ):  # provider_rejection, abstract syntax not supported
                    msg += " (this usually means the interface isn't listening on the given endpoint)"
                raise Exception(msg, resp)

        self.__max_xmit_size = bindResp['max_tfrag']

        if self.__auth_level != RPC_C_AUTHN_LEVEL_NONE:
            if self.__auth_type == RPC_C_AUTHN_WINNT:
                response, randomSessionKey = ntlm.getNTLMSSPType3(
                    auth,
                    bindResp['auth_data'],
                    self.__username,
                    self.__password,
                    self.__domain,
                    self.__lmhash,
                    self.__nthash,
                    use_ntlmv2=self._transport.doesSupportNTLMv2())
                self.__flags = response['flags']
            elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
                response = None

            self.__sequence = 0

            if self.__auth_level in (RPC_C_AUTHN_LEVEL_CONNECT,
                                     RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,
                                     RPC_C_AUTHN_LEVEL_PKT_PRIVACY):
                if self.__auth_type == RPC_C_AUTHN_WINNT:
                    if self.__flags & ntlm.NTLMSSP_NTLM2_KEY:
                        self.__clientSigningKey = ntlm.SIGNKEY(
                            self.__flags, randomSessionKey)
                        self.__serverSigningKey = ntlm.SIGNKEY(
                            self.__flags, randomSessionKey, "Server")
                        self.__clientSealingKey = ntlm.SEALKEY(
                            self.__flags, randomSessionKey)
                        self.__serverSealingKey = ntlm.SEALKEY(
                            self.__flags, randomSessionKey, "Server")
                        # Preparing the keys handle states
                        cipher3 = ARC4.new(self.__clientSealingKey)
                        self.__clientSealingHandle = cipher3.encrypt
                        cipher4 = ARC4.new(self.__serverSealingKey)
                        self.__serverSealingHandle = cipher4.encrypt
                    else:
                        # Same key for everything
                        self.__clientSigningKey = randomSessionKey
                        self.__serverSigningKey = randomSessionKey
                        self.__clientSealingKey = randomSessionKey
                        self.__serverSealingKey = randomSessionKey
                        cipher = ARC4.new(self.__clientSigningKey)
                        self.__clientSealingHandle = cipher.encrypt
                        self.__serverSealingHandle = cipher.encrypt
                elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
                    pass

            sec_trailer = SEC_TRAILER()
            sec_trailer['auth_type'] = self.__auth_type
            sec_trailer['auth_level'] = self.__auth_level
            sec_trailer['auth_ctx_id'] = self._ctx + 79231

            if response is not None:
                auth3 = MSRPCHeader()
                auth3['type'] = MSRPC_AUTH3
                # pad (4 bytes): Can be set to any arbitrary value when set and MUST be
                # ignored on receipt. The pad field MUST be immediately followed by a
                # sec_trailer structure whose layout, location, and alignment are as
                # specified in section 2.2.2.11
                auth3['pduData'] = '    '
                auth3['sec_trailer'] = sec_trailer
                auth3['auth_data'] = str(response)

                # Use the same call_id
                self.__callid = resp['call_id']
                auth3['call_id'] = self.__callid
                self._transport.send(auth3.get_packet(), forceWriteAndx=1)

            self.__callid += 1

        return resp  # means packet is signed, if verifier is wrong it fails
コード例 #33
0
ファイル: srvsvc.py プロジェクト: LucaBongiorni/MITMf
#   [MS-SRVS] interface implementation.
#
# TODO: NetServerEnum2 

import array
from struct import *
import exceptions

from mitmflib.impacket import ImpactPacket
from mitmflib.impacket.structure import Structure
from mitmflib.impacket import dcerpc
from mitmflib.impacket.dcerpc import ndrutils
from mitmflib.impacket.uuid import uuidtup_to_bin


MSRPC_UUID_SRVSVC = uuidtup_to_bin(('4B324FC8-1670-01D3-1278-5A47BF6EE188', '3.0'))

# Error Codes
ERROR_ACCESS_DENIED             = 0x00000005
ERROR_INVALID_LEVEL             = 0x0000007C
ERROR_INVALID_PARAMETER         = 0x00000057
ERROR_MORE_DATA                 = 0x000000EA
ERROR_NOT_ENOUGH_MEMORY         = 0x00000000
ERROR_FILE_NOT_FOUND            = 0x00000002
ERROR_DUP_NAME                  = 0x00000034
ERROR_INVALID_DOMAINNAME        = 0x000004BC
ERROR_NOT_SUPPORTED             = 0x00000032
ERROR_SERVICE_DOES_NOT_EXIST    = 0x00000424
NERR_BufTooSmall                = 0x0000084B
NERR_ClientNameNotFound         = 0x00000908
NERR_InvalidComputer            = 0x0000092F
コード例 #34
0
ファイル: sasec.py プロジェクト: LucaBongiorni/MITMf
#   Best way to learn how to use these calls is to grab the protocol standard
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file. 
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too. 
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, ULONG, WSTR, NULL
from mitmflib.impacket import hresult_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_SASEC  = uuidtup_to_bin(('378E52B0-C0A9-11CF-822D-00AA0051E40F','1.0'))

class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__( self ):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'TSCH SessionError: unknown error code: 0x%x' % self.error_code

################################################################################
コード例 #35
0
ファイル: sasec.py プロジェクト: Liljhon241/MITMf
#   Best way to learn how to use these calls is to grab the protocol standard
#   so you understand what the call does, and then read the test case located
#   at https://github.com/CoreSecurity/impacket/tree/master/impacket/testcases/SMB_RPC
#
#   Some calls have helper functions, which makes it even easier to use.
#   They are located at the end of this file.
#   Helper functions start with "h"<name of the call>.
#   There are test cases for them too.
#
from mitmflib.impacket.dcerpc.v5.ndr import NDRCALL, NDRUniConformantArray
from mitmflib.impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, ULONG, WSTR, NULL
from mitmflib.impacket import hresult_errors
from mitmflib.impacket.uuid import uuidtup_to_bin
from mitmflib.impacket.dcerpc.v5.rpcrt import DCERPCException

MSRPC_UUID_SASEC = uuidtup_to_bin(
    ('378E52B0-C0A9-11CF-822D-00AA0051E40F', '1.0'))


class DCERPCSessionError(DCERPCException):
    def __init__(self, error_string=None, error_code=None, packet=None):
        DCERPCException.__init__(self, error_string, error_code, packet)

    def __str__(self):
        key = self.error_code
        if hresult_errors.ERROR_MESSAGES.has_key(key):
            error_msg_short = hresult_errors.ERROR_MESSAGES[key][0]
            error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1]
            return 'TSCH SessionError: code: 0x%x - %s - %s' % (
                self.error_code, error_msg_short, error_msg_verbose)
        else:
            return 'TSCH SessionError: unknown error code: 0x%x' % self.error_code