# 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. # # Description: # [MS-TSTS] Terminal Services Terminal Server Runtime Interface Protocol implementation # # Interface Implementation based on: # [MS-TSTS] - v20210625: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/ # [MS-TSTS] – v20080207: https://docplayer.net/22134151-Ms-tsts-terminal-services-terminal-server-runtime-interface-protocol-specification.html # # Some RPC Calls are marked with #COMMENT_LIKE tags with following meaning: # #NOT_IMPLEMENTED : RPC Call or Structure is not implemented in current revision. # #DOES_NOT_WORK : I was unable to acheive documented response or properly construct RPC request. # #OLD : RPC Call was taken from [MS-TSTS] – v20080207 documentation, which might be deprecated. # # Some not implemented RPC Calls and structures contains with multi-line comments for future work # # Author: # Alexander Korznikov (@nopernik) https://korznikov.com # import struct from datetime import datetime, timedelta from ldap3.protocol.formatters.formatters import format_sid from impacket.dcerpc.v5 import transport from impacket.uuid import uuidtup_to_bin, bin_to_string, string_to_bin from impacket.dcerpc.v5.ndr import NDR, NDRCALL, NDRSTRUCT, NDRENUM, NDRUNION, NDRUniConformantArray, \ NDRPOINTER, NDRUniConformantVaryingArray, UNKNOWNDATA from impacket.dcerpc.v5.dtypes import NULL, BOOL, BOOLEAN, STR, WSTR, LPWSTR, WIDESTR, RPC_UNICODE_STRING, \ LONG, UINT, ULONG, PULONG, LPDWORD, LARGE_INTEGER, DWORD, NDRHYPER, USHORT, UCHAR, PCHAR, BYTE, PBYTE, \ UUID, GUID from impacket import system_errors from impacket.dcerpc.v5.enum import Enum from impacket.dcerpc.v5.rpcrt import DCERPCException, RPC_C_AUTHN_GSS_NEGOTIATE, RPC_C_AUTHN_LEVEL_PKT_PRIVACY ################################################################################ # Constants ################################################################################ TermSrvSession_UUID = uuidtup_to_bin(('484809d6-4239-471b-b5bc-61df8c23ac48','1.0')) TermSrvNotification_UUID = uuidtup_to_bin(('11899a43-2b68-4a76-92e3-a3d6ad8c26ce','1.0')) TermSrvEnumeration_UUID = uuidtup_to_bin(('88143fd0-c28d-4b2b-8fef-8d882f6a9390','1.0')) RCMPublic_UUID = uuidtup_to_bin(('bde95fdf-eee0-45de-9e12-e5a61cd0d4fe','1.0')) RcmListener_UUID = uuidtup_to_bin(('497d95a6-2d27-4bf5-9bbd-a6046957133c','1.0')) LegacyAPI_UUID = uuidtup_to_bin(('5ca4a760-ebb1-11cf-8611-00a0245420ed','1.0')) AUDIODRIVENAME_LENGTH = 9 WDPREFIX_LENGTH = 12 STACK_ADDRESS_LENGTH = 128 MAX_BR_NAME = 65 DIRECTORY_LENGTH = 256 INITIALPROGRAM_LENGTH = 256 USERNAME_LENGTH = 20 DOMAIN_LENGTH = 17 PASSWORD_LENGTH = 14 NASISPECIFICNAME_LENGTH = 14 NASIUSERNAME_LENGTH = 47 NASIPASSWORD_LENGTH = 24 NASISESSIONNAME_LENGTH = 16 NASIFILESERVER_LENGTH = 47 CLIENTDATANAME_LENGTH = 7 CLIENTNAME_LENGTH = 20 CLIENTADDRESS_LENGTH = 30 IMEFILENAME_LENGTH = 32 DIRECTORY_LENGTH = 256 CLIENTLICENSE_LENGTH = 32 CLIENTMODEM_LENGTH = 40 CLIENT_PRODUCT_ID_LENGTH = 32 MAX_COUNTER_EXTENSIONS = 2 WINSTATIONNAME_LENGTH = 32 PROTOCOL_CONSOLE = 0 PROTOCOL_ICA = 1 PROTOCOL_TSHARE = 2 PROTOCOL_RDP = 2 PDNAME_LENGTH = 32 WDNAME_LENGTH = 32 CDNAME_LENGTH = 32 DEVICENAME_LENGTH = 128 MODEMNAME_LENGTH = DEVICENAME_LENGTH CALLBACK_LENGTH = 50 DLLNAME_LENGTH = 32 WINSTATIONCOMMENT_LENGTH = 60 MAX_LICENSE_SERVER_LENGTH = 1024 LOGONID_CURRENT = ULONG MAX_PDCONFIG = 10 TERMSRV_TOTAL_SESSIONS = 1 TERMSRV_DISC_SESSIONS = 2 TERMSRV_RECON_SESSIONS = 3 TERMSRV_CURRENT_ACTIVE_SESSIONS = 4 TERMSRV_CURRENT_DISC_SESSIONS = 5 TERMSRV_PENDING_SESSIONS = 6 TERMSRV_SUCC_TOTAL_LOGONS = 7 TERMSRV_SUCC_LOCAL_LOGONS = 8 TERMSRV_SUCC_REMOTE_LOGONS = 9 TERMSRV_SUCC_SESSION0_LOGONS = 10 TERMSRV_CURRENT_TERMINATING_SESSIONS = 11 TERMSRV_CURRENT_LOGGEDON_SESSIONS = 12 NO_FALLBACK_DRIVERS = 0x0 FALLBACK_BESTGUESS = 0x1 FALLBACK_PCL = 0x2 FALLBACK_PS = 0x3 FALLBACK_PCLANDPS = 0x4 VIRTUALCHANNELNAME_LENGTH = 7 WINSTATION_QUERY = 0x00000001 # WinStationQueryInformation() WINSTATION_SET = 0x00000002 # WinStationSetInformation() WINSTATION_RESET = 0x00000004 # WinStationReset() WINSTATION_VIRTUAL = 0x00000008 # read/write direct data WINSTATION_SHADOW = 0x00000010 # WinStationShadow() WINSTATION_LOGON = 0x00000020 # logon to WinStation WINSTATION_LOGOFF = 0x00000040 # WinStationLogoff() WINSTATION_MSG = 0x00000080 # WinStationMsg() WINSTATION_CONNECT = 0x00000100 # WinStationConnect() WINSTATION_DISCONNECT = 0x00000200 # WinStationDisconnect() ################################################################################ # Types ################################################################################ _NDRENUM = NDRENUM class NDRENUM(_NDRENUM): def dump(self, msg = None, indent = 0): if msg is None: msg = self.__class__.__name__ if msg != '': print(msg, end=' ') try: print(" %s" % self.enumItems(self.fields['Data']).name, end=' ') except: print(" %s" % hex(self.fields['Data']), end=' ') class TS_WCHAR(WSTR): commonHdr = ( ('ActualCount',' WEVENT_ALL = 0x7fffffff # Wait for all event types. WEVENT_FLUSH = 0x80000000 # Release all waiting clients. class ADDRESSFAMILY_ENUM(NDRENUM): structure = ( ('Data','>= 1 return keys else: return NDR.__getitem__(self,key) structure = ( # I have no idea to to do it properly, so i'm parsing bit flags inside another structure class ('flags', FLAGS), ('ClientName', WCHAR_CLIENTNAME_LENGTH), ('Domain', WCHAR_DOMAIN_LENGTH), ('UserName', WCHAR_USERNAME_LENGTH), ('Password', WCHAR_PASSWORD_LENGTH), ('WorkDirectory', WCHAR_DIRECTORY_LENGTH), ('InitialProgram', WCHAR_INITIALPROGRAM_LENGTH), ('SerialNumber', ULONG), ('EncryptionLevel', BYTE), ('ClientAddressFamily', ADDRESSFAMILY_ENUM), ('ClientAddress', WCHAR_CLIENTADDRESS_LENGTH), ('HRes', USHORT), ('VRes', USHORT), ('ColorDepth', USHORT), ('ProtocolType', USHORT), ('KeyboardLayout', ULONG), ('KeyboardType', ULONG), ('KeyboardSubType', ULONG), ('KeyboardFunctionKey', ULONG), ('imeFileName', WCHAR_IMEFILENAME_LENGTH), ('ClientDirectory', WCHAR_DIRECTORY_LENGTH), ('ClientLicense', WCHAR_CLIENTLICENSE_LENGTH), ('ClientModem', WCHAR_CLIENTMODEM_LENGTH), ('ClientBuildNumber', ULONG), ('ClientHardwareId', ULONG), ('ClientProductId', USHORT), ('OutBufCountHost', USHORT), ('OutBufCountClient', USHORT), ('OutBufLength', USHORT), ('AudioDriverName', WCHAR_AUDIODRIVENAME_LENGTH), ('ClientTimeZone', TS_TIME_ZONE_INFORMATION), ('ClientSessionId', ULONG), ('clientDigProductId', WCHAR_CLIENT_PRODUCT_ID_LENGTH), ('PerformanceFlags', ULONG), ('ActiveInputLocale', ULONG), ) class PWINSTATIONCLIENT(NDRPOINTER): referent = ( ('Data', WINSTATIONCLIENT), ) # 2.2.2.17.1 TS_COUNTER_HEADER class TS_COUNTER_HEADER(NDRSTRUCT): structure = ( ('dwCounterID', DWORD), ('bResult', BOOLEAN), ) # 2.2.2.17 TS_COUNTER class TS_COUNTER(NDRSTRUCT): structure = ( ('counterHead', TS_COUNTER_HEADER), ('dwValue', DWORD), ('startTime', LARGE_INTEGER), ) class TS_COUNTER_ARRAY(NDRUniConformantArray): item = TS_COUNTER class PTS_COUNTER(NDRPOINTER): referent = ( ('Data', TS_COUNTER_ARRAY), ) # 2.2.2.11 LSM_SESSIONINFO_EX_LEVEL1 class SESSIONFLAGS(NDRENUM): structure = ( ('Data', '>= bits return keys else: return NDR.__getitem__(self,key) structure = ( # I have no idea to to do it properly, so i'm parsing bit flags inside another structure class ('flags', FLAGS), ('UserName', WCHAR_USERNAME_LENGTH), ('Domain', WCHAR_DOMAIN_LENGTH), ('Password', WCHAR_PASSWORD_LENGTH), ('WorkDirectory', WCHAR_DIRECTORY_LENGTH), ('InitialProgram', WCHAR_INITIALPROGRAM_LENGTH), ('CallbackNumber', WCHAR_CALLBACK_LENGTH), ('Callback', CALLBACKCLASS), ('Shadow', SHADOWCLASS), ('MaxConnectionTime', ULONG), ('MaxDisconnectionTime', ULONG), ('MaxIdleTime', ULONG), ('KeyboardLayout', ULONG), ('MinEncryptionLevel', BYTE), ('NWLogonServer', WCHAR_NASIFILESERVER_LENGTH), ('PublishedName', WCHAR_MAX_BR_NAME), ('WFProfilePath', WCHAR_DIRECTORY_LENGTH), ('WFHomeDir', WCHAR_DIRECTORY_LENGTH), ('WFHomeDirDrive', WCHAR_ARRAY_4), ) class OEMId(NDRSTRUCT): structure = ( ('OEMId', '4s=""'), ) # 2.2.2.30.1 WINSTATIONCONFIG class WINSTATIONCONFIG(NDRSTRUCT): pass structure = ( ('Comment', WCHAR_WINSTATIONCOMMENT_LENGTH), ('User', USERCONFIG), ('OEMId', OEMId), ) class PWINSTATIONCONFIG(NDRPOINTER): referent = ( ('Data', WINSTATIONCONFIG), ) #NOT_IMPLEMETED 2.2.2.20.1.2 PROTOCOLCOUNTERS class PROTOCOLCOUNTERS(NDRSTRUCT): pass #NOT_IMPLEMENTED 2.2.2.20.1.3 CACHE_STATISTICS class CACHE_STATISTICS(NDRSTRUCT): pass #NOT_IMPLEMENTED 2.2.2.20.1 PROTOCOLSTATUS class PROTOCOLSTATUS(NDRSTRUCT): pass class PPROTOCOLSTATUS(NDRPOINTER): referent = ( ('Data', PROTOCOLSTATUS), ) # 2.2.2.43 RCM_REMOTEADDRESS class IPv4ADDRESS(NDRSTRUCT): structure = ( ('Data', '>= 8 return '.'.join(y) else: return super().__getitem__(key) class RCM_REMOTEADDRESS_UNION_CASE_IPV4(NDRSTRUCT): class _4CHAR(NDRSTRUCT): structure = ( ('sin_zero', '4s=b""'), ) structure = ( ('sin_port', USHORT), ('sin_port2', USHORT), ('in_addr', IPv4ADDRESS), ('sin_zero', _4CHAR), ) class RCM_REMOTEADDRESS_UNION_CASE_IPV6(NDRSTRUCT): class _8CHAR(NDRSTRUCT): structure = ( ('sin_zero', '8s=b""'), ) structure = ( ('sin_port', USHORT), ('in_addr', ULONG), ('sin_zero', _8CHAR), ('sin6_scope_id', ULONG), ) class RCM_REMOTEADDRESS(NDRUNION): commonHdr = ( ('tag', USHORT), ) union = { 2 : ('ipv4', RCM_REMOTEADDRESS_UNION_CASE_IPV4), 23: ('ipv6', RCM_REMOTEADDRESS_UNION_CASE_IPV6), } class pResult_ENUM(NDRENUM): structure = ( ('Data', ' 12: break data = data[offset+2:] arrayOffset = arrayOffset + offset + 2 procInfo = '' while len(data)>1: if len(data[len(procInfo):]) < 16: break # I think there some alignment problems... # in the structure, second DWORD is thread count, i'm looking for the second DWORD # in order to align the data correctly # There is no proper errors handling! b,c,d,e = struct.unpack('