Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions impacket/dcerpc/v5/dcom/wmi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2852,8 +2852,10 @@ def innerMethod(staticArgs, *args):
methodDefinition = staticArgs[1]
if methodDefinition['InParams'] is not None:
if len(args) != len(methodDefinition['InParams']):
LOG.error("Function called with %d parameters instead of %d!" % (len(args), len(methodDefinition['InParams'])))
return None
# Previously this only logged and returned None, silently

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

argument validation is conditional on methodDefinition['InParams'] is not None. Methods without input parameters are represented by None, so a call such as process.GetOwner('unexpected') bypasses validation. At wmi.py:3001 (impacket/dcerpc/v5/dcom/wmi.py:3001), the wrapper sends pInParams=NULL, silently discarding the supplied argument and executing the no-argument method instead.
Please validate against zero arguments when InParams is None. Add regression coverage beside tests/SMB_RPC/test_wmi_methods.py:34 (tests/SMB_RPC/test_wmi_methods.py:34), asserting that process.GetOwner('unexpected') raises TypeError.

# producing a bogus "successful" call with no result.
raise TypeError("%s() takes %d argument(s) but %d were given" % (
methodDefinition['name'], len(methodDefinition['InParams']), len(args)))
# In Params
encodingUnit = ENCODING_UNIT()

Expand Down Expand Up @@ -3030,11 +3032,15 @@ def innerMethod(staticArgs, *args):
return self.__iWbemServices.ExecMethod(classOrInstance, methodDefinition['name'], pInParams = objRefCustomIn )
#return self.__iWbemServices.ExecMethod('Win32_Process.Handle="436"', methodDefinition['name'],
# pInParams=objRefCustomIn).getObject().ctCurrent['properties']
except Exception as e:
except Exception:
if LOG.level == logging.DEBUG:
import traceback
traceback.print_exc()
LOG.error(str(e))
# Previously the error was only logged and None returned, which
# made a failed remote method call indistinguishable from a
# successful one (callers then hit an opaque AttributeError on
# the None result). Propagate it so callers can handle failures.
raise

for methodName in methods:
innerMethod.__name__ = methodName
Expand Down Expand Up @@ -3141,7 +3147,20 @@ def Next(self, lTimeout, uCount):
request = IEnumWbemClassObject_Next()
request['lTimeout'] = lTimeout
request['uCount'] = uCount
resp = self.request(request, iid = self._iid, uuid = self.get_iPid())
try:
resp = self.request(request, iid = self._iid, uuid = self.get_iPid())
except DCERPCSessionError as e:
# [MS-WMI] 3.1.4.4.2: when fewer than uCount objects are still
# available, the server returns the remaining objects together with
# a WBEM_S_FALSE status in the *same* response. impacket's DCERPC
# layer raises on that non-zero status before Next() can read the
# objects, which would silently drop the final partial batch when
# uCount > 1. Recover those objects from the decoded packet. When no
# objects are returned the enumeration is exhausted, so we re-raise
# to preserve the historical WBEM_S_FALSE end-of-iteration signal.
resp = e.get_packet()
if e.get_error_code() != WBEMSTATUS.enumItems.WBEM_S_FALSE.value or resp is None or not resp['apObjects']:
raise
interfaces = list()
for interface in resp['apObjects']:
interfaces.append(IWbemClassObject(
Expand Down
47 changes: 47 additions & 0 deletions tests/SMB_RPC/test_wmi_methods.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env python
# Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Remote method-dispatch regression tests. Run directly:
# python tests/SMB_RPC/test_wmi_methods.py 'domain/user:password@target'
#
from pathlib import Path
import sys

if __name__ == '__main__' and __package__ is None:
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))

from impacket.dcerpc.v5.dcom import wmi
from tests.SMB_RPC import test_wmi_next


class WMIMethodTests(test_wmi_next.WMIRemoteTests):
def test_wrong_argument_count_raises_type_error(self):
process, _ = self.services.GetObject('Win32_Process')
# Create takes three arguments. Neither call can start a process.
for arguments in ((), (None, None, None, None)):
with self.subTest(argument_count=len(arguments)):
with self.assertRaisesRegex(TypeError, r'Create\(\) takes 3 argument\(s\)'):
process.Create(*arguments)

def test_remote_method_error_is_propagated(self):
process, _ = self.services.GetObject('Win32_Process')
# GetOwner requires a process instance. Calling it on the class makes
# the server reject ExecMethod; the wrapper must propagate that error.
with self.assertRaises(wmi.DCERPCSessionError) as ctx:
process.GetOwner()
self.assertEqual(
ctx.exception.get_error_code(),
wmi.WBEMSTATUS.enumItems.WBEM_E_INVALID_METHOD_PARAMETERS.value,
)


if __name__ == '__main__':
sys.exit(test_wmi_next.main(WMIMethodTests))
168 changes: 168 additions & 0 deletions tests/SMB_RPC/test_wmi_next.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
#!/usr/bin/env python
# Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Remote regression tests for IEnumWbemClassObject.Next(). Run directly:
# python tests/SMB_RPC/test_wmi_next.py 'domain/user:password@target'
# Omitting the password prompts for it, as in wmiquery.py.
#
import argparse
from getpass import getpass
from pathlib import Path
import sys
import unittest
import uuid

# Direct execution should test the checkout, even if another Impacket version
# is installed. Module execution and pytest already put the checkout on sys.path.
if __name__ == '__main__' and __package__ is None:
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))

import pytest

from tests import RemoteTestCase
from impacket.dcerpc.v5.dcom import wmi
from impacket.dcerpc.v5.dcomrt import DCOMConnection
from impacket.dcerpc.v5.dtypes import NULL
from impacket.examples.utils import parse_target


@pytest.mark.remote
class WMIRemoteTests(RemoteTestCase, unittest.TestCase):
connection_options = None

def setUp(self):
super(WMIRemoteTests, self).setUp()
if self.connection_options is None:
# Keep the standard remote configuration for pytest users.
self.set_transport_config()
connection_options = dict(
target=self.machine, username=self.username,
password=self.password, domain=self.domain,
lmhash=self.lmhash, nthash=self.nthash,
)
else:
connection_options = self.connection_options
self.machine = connection_options['target']
dcom = DCOMConnection(**connection_options)
self.addCleanup(dcom.disconnect)
interface = dcom.CoCreateInstanceEx(
wmi.CLSID_WbemLevel1Login, wmi.IID_IWbemLevel1Login,
)
login = wmi.IWbemLevel1Login(interface)
try:
self.services = login.NTLMLogin(
r'\\%s\root\cimv2' % self.machine, NULL, NULL,
)
self.addCleanup(self.services.RemRelease)
finally:
login.RemRelease()


class WMINextTests(WMIRemoteTests):
def _query(self, query='SELECT * FROM Win32_OperatingSystem'):
enum = self.services.ExecQuery(query)
self.addCleanup(enum.RemRelease)
return enum

def _assert_operating_system(self, objects):
# Win32_OperatingSystem has one instance for the running OS, so the
# result count does not depend on processes or services starting/stopping.
self.assertEqual(len(objects), 1)
self.assertIsInstance(objects[0], wmi.IWbemClassObject)
self.assertEqual(objects[0].getClassName(), 'Win32_OperatingSystem')
self.assertTrue(objects[0].getProperties()['Name']['value'])

def _assert_exhausted(self, enum, count):
with self.assertRaises(wmi.DCERPCSessionError) as ctx:
enum.Next(0xffffffff, count)
self.assertEqual(
ctx.exception.get_error_code(),
wmi.WBEMSTATUS.enumItems.WBEM_S_FALSE.value,
)
packet = ctx.exception.get_packet()
self.assertIsNotNone(packet)
self.assertEqual(packet['puReturned'], 0)
self.assertEqual(len(packet['apObjects']), 0)

def test_next_returns_all_objects_on_success(self):
enum = self._query()
self._assert_operating_system(enum.Next(0xffffffff, 1))

def test_next_recovers_final_partial_batch(self):
enum = self._query()
# Requesting two objects from this singleton class forces the server
# to return one object together with WBEM_S_FALSE. Before the fix,
# Next() raised here and lost that object.
self._assert_operating_system(enum.Next(0xffffffff, 2))
self._assert_exhausted(enum, 2)

def test_next_reraises_on_exhaustion(self):
enum = self._query()
self._assert_operating_system(enum.Next(0xffffffff, 1))
self._assert_exhausted(enum, 1)

def test_next_reraises_for_empty_query(self):
# Name is a key property, so it cannot be NULL.
enum = self._query('SELECT * FROM Win32_OperatingSystem WHERE Name IS NULL')
self._assert_exhausted(enum, 2)

def test_next_reraises_other_errors(self):
# Semisynchronous queries report the missing-class error through Next().
missing_class = 'ImpacketMissingClass_' + uuid.uuid4().hex
enum = self.services.ExecQuery(
'SELECT * FROM ' + missing_class, wmi.WBEM_FLAG_RETURN_IMMEDIATELY,
)
self.addCleanup(enum.RemRelease)
with self.assertRaises(wmi.DCERPCSessionError) as ctx:
enum.Next(0xffffffff, 1)
self.assertEqual(
ctx.exception.get_error_code(),
wmi.WBEMSTATUS.enumItems.WBEM_E_INVALID_CLASS.value,
)


def main(test_case=WMINextTests):
parser = argparse.ArgumentParser(description='Run remote WMI regression tests.')
parser.add_argument('target', help='[[domain/]username[:password]@]<targetName or address>')
authentication = parser.add_argument_group('authentication')
authentication.add_argument('-hashes', metavar='LMHASH:NTHASH', help='NTLM hashes')
authentication.add_argument('-no-pass', action='store_true', help="Don't ask for a password (useful for -k)")
authentication.add_argument('-k', action='store_true', help='Use Kerberos authentication (KRB5CCNAME cache)')
authentication.add_argument(
'-aesKey', metavar='hex key', help='AES key for Kerberos authentication (128 or 256 bits)',
)
authentication.add_argument('-dc-ip', metavar='ip address', help='IP address of the domain controller')
options = parser.parse_args()

domain, username, password, address = parse_target(options.target)
if not address:
parser.error('A target hostname or IP address is required')
lmhash, nthash = '', ''
if options.hashes is not None:
try:
lmhash, nthash = options.hashes.split(':')
except ValueError:
parser.error('-hashes must be in LMHASH:NTHASH format')
if password == '' and username != '' and options.hashes is None and not options.no_pass and options.aesKey is None:
password = getpass('Password:')

test_case.connection_options = dict(
target=address, username=username, password=password, domain=domain,
lmhash=lmhash, nthash=nthash, aesKey=options.aesKey,
doKerberos=options.k or options.aesKey is not None, kdcHost=options.dc_ip,
)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(test_case)
result = unittest.TextTestRunner(verbosity=2).run(suite)
return 0 if result.wasSuccessful() else 1


if __name__ == '__main__':
sys.exit(main())
Loading