From 0e4f9d3cf5894519bcec882d89c192626565208b Mon Sep 17 00:00:00 2001 From: nullsection Date: Tue, 15 Sep 2026 21:13:38 +1000 Subject: [PATCH 1/3] fix: correct WMI enumeration and method-dispatch error handling Two related correctness bugs in impacket.dcerpc.v5.dcom.wmi: IEnumWbemClassObject.Next() dropped the final partial batch. Per [MS-WMI] 3.1.4.4.2, when fewer than uCount objects remain the server returns the trailing objects together with a WBEM_S_FALSE status in the same response. The generic DCERPC layer raises on that non-zero status before Next() can read apObjects, so fetching more than one row per call silently discarded the last rows (this also affects the bundled wmiquery.py and dpapidump.py). Next() now recovers those objects from the decoded packet on WBEM_S_FALSE and re-raises only when the enumeration is truly exhausted, preserving the historical end-of-iteration signal for existing callers. IWbemClassObject dynamic method dispatch (createMethods/innerMethod) swallowed ExecMethod exceptions and argument-count mismatches, logging them and returning None. A failed remote method call (e.g. Win32_Process.Create used by wmiexec.py) was therefore indistinguishable from success and only surfaced later as an opaque AttributeError on the None result. Both now propagate. Adds host-free unit tests for Next()'s partial-batch handling. --- ChangeLog.md | 7 ++- impacket/dcerpc/v5/dcom/wmi.py | 29 ++++++++-- tests/SMB_RPC/test_wmi_next.py | 103 +++++++++++++++++++++++++++++++++ 3 files changed, 133 insertions(+), 6 deletions(-) create mode 100644 tests/SMB_RPC/test_wmi_next.py diff --git a/ChangeLog.md b/ChangeLog.md index bf8186c45e..977b641bdc 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -7,7 +7,12 @@ https://github.com/fortra/impacket/commits/master ## Unreleased: -1. Examples improvements +1. Library improvements + + * WMI: Fixed `IEnumWbemClassObject.Next()` silently dropping the final partial batch of objects. When fewer than `uCount` objects remain, the server returns the trailing objects together with a `WBEM_S_FALSE` status in the same response, and the generic DCERPC layer raised on that status before the objects could be read; they are now recovered from the decoded packet, while `WBEM_S_FALSE` is still surfaced once the enumeration is exhausted. + * WMI: Made `IWbemClassObject` dynamic method dispatch propagate `ExecMethod` failures and argument-count mismatches instead of logging them and returning `None`, so a failed remote method call is no longer indistinguishable from a successful one. + +2. Examples improvements * [atexec.py](examples/atexec.py): * Added mutually exclusive `-author-log` and `-overflow` options to poison or overflow the Task Scheduler Security Event 4698 Author field via task XML RegistrationInfo. diff --git a/impacket/dcerpc/v5/dcom/wmi.py b/impacket/dcerpc/v5/dcom/wmi.py index a77292324f..4e9e9b7773 100644 --- a/impacket/dcerpc/v5/dcom/wmi.py +++ b/impacket/dcerpc/v5/dcom/wmi.py @@ -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 + # 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() @@ -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 @@ -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( diff --git a/tests/SMB_RPC/test_wmi_next.py b/tests/SMB_RPC/test_wmi_next.py new file mode 100644 index 0000000000..2fceab61f8 --- /dev/null +++ b/tests/SMB_RPC/test_wmi_next.py @@ -0,0 +1,103 @@ +#!/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. +# +# Host-free unit tests for IEnumWbemClassObject.Next() partial-batch handling. +# +# Tested so far: +# IEnumWbemClassObject::Next (final partial batch recovery on WBEM_S_FALSE) +# +# These tests do not require a remote target: the DCERPC request layer and the +# per-object interface construction are mocked, so only Next()'s own decision +# logic is exercised. +# +import unittest +from unittest import mock + +from impacket.dcerpc.v5.dcom import wmi + +WBEM_S_FALSE = wmi.WBEMSTATUS.enumItems.WBEM_S_FALSE.value +WBEM_E_FAILED = wmi.WBEMSTATUS.enumItems.WBEM_E_FAILED.value + + +def _make_enum(): + """Build an IEnumWbemClassObject without touching the network.""" + enum = wmi.IEnumWbemClassObject.__new__(wmi.IEnumWbemClassObject) + enum._iid = wmi.IID_IEnumWbemClassObject + # Name-mangled attribute set by __init__ in normal operation. + enum._IEnumWbemClassObject__iWbemServices = None + # Interface plumbing Next() calls into; irrelevant once IWbemClassObject + # and INTERFACE are patched out below. + enum.get_iPid = mock.Mock(return_value=b"") + enum.get_cinstance = mock.Mock(return_value=object()) + enum.get_ipidRemUnknown = mock.Mock(return_value=b"") + enum.get_oxid = mock.Mock(return_value=0) + enum.get_target = mock.Mock(return_value="host") + return enum + + +def _fake_response(count): + """A minimal stand-in for IEnumWbemClassObject_NextResponse.""" + return { + "ErrorCode": 0, + "puReturned": count, + "apObjects": [{"abData": [b""]} for _ in range(count)], + } + + +def _false_response(count): + resp = _fake_response(count) + resp["ErrorCode"] = WBEM_S_FALSE + return resp + + +class WMINextTests(unittest.TestCase): + def test_next_returns_all_objects_on_success(self): + enum = _make_enum() + enum.request = mock.Mock(return_value=_fake_response(3)) + with mock.patch.object(wmi, "IWbemClassObject", side_effect=lambda *a, **k: object()), \ + mock.patch.object(wmi, "INTERFACE", side_effect=lambda *a, **k: object()): + result = enum.Next(0xffffffff, 5) + self.assertEqual(len(result), 3) + + def test_next_recovers_final_partial_batch(self): + # Server returned 2 trailing objects *and* WBEM_S_FALSE in one response. + # Before the fix these rows were dropped; Next() must now return them. + enum = _make_enum() + exc = wmi.DCERPCSessionError(packet=_false_response(2), error_code=WBEM_S_FALSE) + enum.request = mock.Mock(side_effect=exc) + with mock.patch.object(wmi, "IWbemClassObject", side_effect=lambda *a, **k: object()), \ + mock.patch.object(wmi, "INTERFACE", side_effect=lambda *a, **k: object()): + result = enum.Next(0xffffffff, 5) + self.assertEqual(len(result), 2) + + def test_next_reraises_on_exhaustion(self): + # WBEM_S_FALSE with no trailing objects is genuine end-of-enumeration; + # the historical exception must still be raised so existing callers that + # break on it keep working. + enum = _make_enum() + exc = wmi.DCERPCSessionError(packet=_false_response(0), error_code=WBEM_S_FALSE) + enum.request = mock.Mock(side_effect=exc) + with self.assertRaises(wmi.DCERPCSessionError) as ctx: + enum.Next(0xffffffff, 5) + self.assertEqual(ctx.exception.get_error_code(), WBEM_S_FALSE) + self.assertIn("S_FALSE", str(ctx.exception)) + + def test_next_reraises_other_errors(self): + enum = _make_enum() + exc = wmi.DCERPCSessionError(error_code=WBEM_E_FAILED) + enum.request = mock.Mock(side_effect=exc) + with self.assertRaises(wmi.DCERPCSessionError) as ctx: + enum.Next(0xffffffff, 5) + self.assertEqual(ctx.exception.get_error_code(), WBEM_E_FAILED) + + +if __name__ == "__main__": + unittest.main(verbosity=1) From 12b9337c0014fdfba20517cc7ac31e64c96d89bb Mon Sep 17 00:00:00 2001 From: nullsection Date: Wed, 30 Sep 2026 02:55:11 +1000 Subject: [PATCH 2/3] test: replace mocked WMI enumeration cases with remote tests --- ChangeLog.md | 7 +- tests/SMB_RPC/test_wmi_next.py | 139 ++++++++++++++++----------------- 2 files changed, 67 insertions(+), 79 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 977b641bdc..bf8186c45e 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -7,12 +7,7 @@ https://github.com/fortra/impacket/commits/master ## Unreleased: -1. Library improvements - - * WMI: Fixed `IEnumWbemClassObject.Next()` silently dropping the final partial batch of objects. When fewer than `uCount` objects remain, the server returns the trailing objects together with a `WBEM_S_FALSE` status in the same response, and the generic DCERPC layer raised on that status before the objects could be read; they are now recovered from the decoded packet, while `WBEM_S_FALSE` is still surfaced once the enumeration is exhausted. - * WMI: Made `IWbemClassObject` dynamic method dispatch propagate `ExecMethod` failures and argument-count mismatches instead of logging them and returning `None`, so a failed remote method call is no longer indistinguishable from a successful one. - -2. Examples improvements +1. Examples improvements * [atexec.py](examples/atexec.py): * Added mutually exclusive `-author-log` and `-overflow` options to poison or overflow the Task Scheduler Security Event 4698 Author field via task XML RegistrationInfo. diff --git a/tests/SMB_RPC/test_wmi_next.py b/tests/SMB_RPC/test_wmi_next.py index 2fceab61f8..52036996c1 100644 --- a/tests/SMB_RPC/test_wmi_next.py +++ b/tests/SMB_RPC/test_wmi_next.py @@ -9,95 +9,88 @@ # of the Apache Software License. See the accompanying LICENSE file # for more information. # -# Host-free unit tests for IEnumWbemClassObject.Next() partial-batch handling. -# -# Tested so far: -# IEnumWbemClassObject::Next (final partial batch recovery on WBEM_S_FALSE) -# -# These tests do not require a remote target: the DCERPC request layer and the -# per-object interface construction are mocked, so only Next()'s own decision -# logic is exercised. +# Remote regression tests for IEnumWbemClassObject.Next(). Configure the target +# using tests/dcetests.cfg or pytest's --remote-config option, as in test_wmi.py. # import unittest -from unittest import mock - -from impacket.dcerpc.v5.dcom import wmi - -WBEM_S_FALSE = wmi.WBEMSTATUS.enumItems.WBEM_S_FALSE.value -WBEM_E_FAILED = wmi.WBEMSTATUS.enumItems.WBEM_E_FAILED.value +import pytest -def _make_enum(): - """Build an IEnumWbemClassObject without touching the network.""" - enum = wmi.IEnumWbemClassObject.__new__(wmi.IEnumWbemClassObject) - enum._iid = wmi.IID_IEnumWbemClassObject - # Name-mangled attribute set by __init__ in normal operation. - enum._IEnumWbemClassObject__iWbemServices = None - # Interface plumbing Next() calls into; irrelevant once IWbemClassObject - # and INTERFACE are patched out below. - enum.get_iPid = mock.Mock(return_value=b"") - enum.get_cinstance = mock.Mock(return_value=object()) - enum.get_ipidRemUnknown = mock.Mock(return_value=b"") - enum.get_oxid = mock.Mock(return_value=0) - enum.get_target = mock.Mock(return_value="host") - return enum +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 -def _fake_response(count): - """A minimal stand-in for IEnumWbemClassObject_NextResponse.""" - return { - "ErrorCode": 0, - "puReturned": count, - "apObjects": [{"abData": [b""]} for _ in range(count)], - } +@pytest.mark.remote +class WMINextTests(RemoteTestCase, unittest.TestCase): + def setUp(self): + super(WMINextTests, self).setUp() + self.set_transport_config() + dcom = DCOMConnection( + self.machine, self.username, self.password, self.domain, + self.lmhash, self.nthash, + ) + 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() + def _query(self, query='SELECT * FROM Win32_OperatingSystem'): + enum = self.services.ExecQuery(query) + self.addCleanup(enum.RemRelease) + return enum -def _false_response(count): - resp = _fake_response(count) - resp["ErrorCode"] = WBEM_S_FALSE - return resp + 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) -class WMINextTests(unittest.TestCase): def test_next_returns_all_objects_on_success(self): - enum = _make_enum() - enum.request = mock.Mock(return_value=_fake_response(3)) - with mock.patch.object(wmi, "IWbemClassObject", side_effect=lambda *a, **k: object()), \ - mock.patch.object(wmi, "INTERFACE", side_effect=lambda *a, **k: object()): - result = enum.Next(0xffffffff, 5) - self.assertEqual(len(result), 3) + enum = self._query() + self._assert_operating_system(enum.Next(0xffffffff, 1)) def test_next_recovers_final_partial_batch(self): - # Server returned 2 trailing objects *and* WBEM_S_FALSE in one response. - # Before the fix these rows were dropped; Next() must now return them. - enum = _make_enum() - exc = wmi.DCERPCSessionError(packet=_false_response(2), error_code=WBEM_S_FALSE) - enum.request = mock.Mock(side_effect=exc) - with mock.patch.object(wmi, "IWbemClassObject", side_effect=lambda *a, **k: object()), \ - mock.patch.object(wmi, "INTERFACE", side_effect=lambda *a, **k: object()): - result = enum.Next(0xffffffff, 5) - self.assertEqual(len(result), 2) + 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): - # WBEM_S_FALSE with no trailing objects is genuine end-of-enumeration; - # the historical exception must still be raised so existing callers that - # break on it keep working. - enum = _make_enum() - exc = wmi.DCERPCSessionError(packet=_false_response(0), error_code=WBEM_S_FALSE) - enum.request = mock.Mock(side_effect=exc) - with self.assertRaises(wmi.DCERPCSessionError) as ctx: - enum.Next(0xffffffff, 5) - self.assertEqual(ctx.exception.get_error_code(), WBEM_S_FALSE) - self.assertIn("S_FALSE", str(ctx.exception)) + enum = self._query() + self._assert_operating_system(enum.Next(0xffffffff, 1)) + self._assert_exhausted(enum, 1) - def test_next_reraises_other_errors(self): - enum = _make_enum() - exc = wmi.DCERPCSessionError(error_code=WBEM_E_FAILED) - enum.request = mock.Mock(side_effect=exc) - with self.assertRaises(wmi.DCERPCSessionError) as ctx: - enum.Next(0xffffffff, 5) - self.assertEqual(ctx.exception.get_error_code(), WBEM_E_FAILED) + 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) -if __name__ == "__main__": +if __name__ == '__main__': unittest.main(verbosity=1) From 4ab670d4f2977dde3b572dbce94a3d94fb0a0af5 Mon Sep 17 00:00:00 2001 From: nullsection Date: Wed, 30 Sep 2026 03:09:50 +1000 Subject: [PATCH 3/3] test: cover WMI method errors with runnable remote scripts --- tests/SMB_RPC/test_wmi_methods.py | 47 ++++++++++++++++ tests/SMB_RPC/test_wmi_next.py | 92 +++++++++++++++++++++++++++---- 2 files changed, 129 insertions(+), 10 deletions(-) create mode 100644 tests/SMB_RPC/test_wmi_methods.py diff --git a/tests/SMB_RPC/test_wmi_methods.py b/tests/SMB_RPC/test_wmi_methods.py new file mode 100644 index 0000000000..335f509ba7 --- /dev/null +++ b/tests/SMB_RPC/test_wmi_methods.py @@ -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)) diff --git a/tests/SMB_RPC/test_wmi_next.py b/tests/SMB_RPC/test_wmi_next.py index 52036996c1..ecf61f07a5 100644 --- a/tests/SMB_RPC/test_wmi_next.py +++ b/tests/SMB_RPC/test_wmi_next.py @@ -9,10 +9,21 @@ # of the Apache Software License. See the accompanying LICENSE file # for more information. # -# Remote regression tests for IEnumWbemClassObject.Next(). Configure the target -# using tests/dcetests.cfg or pytest's --remote-config option, as in test_wmi.py. +# 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 @@ -20,17 +31,27 @@ 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 WMINextTests(RemoteTestCase, unittest.TestCase): +class WMIRemoteTests(RemoteTestCase, unittest.TestCase): + connection_options = None + def setUp(self): - super(WMINextTests, self).setUp() - self.set_transport_config() - dcom = DCOMConnection( - self.machine, self.username, self.password, self.domain, - self.lmhash, self.nthash, - ) + 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, @@ -44,6 +65,8 @@ def setUp(self): finally: login.RemRelease() + +class WMINextTests(WMIRemoteTests): def _query(self, query='SELECT * FROM Win32_OperatingSystem'): enum = self.services.ExecQuery(query) self.addCleanup(enum.RemRelease) @@ -91,6 +114,55 @@ def test_next_reraises_for_empty_query(self): 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]@]') + 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__': - unittest.main(verbosity=1) + sys.exit(main())