def __init__(self, names=None, command_type=None, namespace=None, argument_list=None): """ [MS-PSRP] 2.2.2.14 GET_COMMAND_METADATA Message https://msdn.microsoft.com/en-us/library/ee175985.aspx :param names: :param command_type: :param namespace: :param argument_list: """ super(GetCommandMetadata, self).__init__() self._extended_properties = (('names', ListMeta(name="Name", list_value_meta=ObjectMeta("S"), list_types=[ "System.String[]", "System.Array", "System.Object" ])), ('command_type', ObjectMeta(name="CommandType", object=CommandType)), ('namespace', ObjectMeta(name="Namespace")), ('argument_list', ListMeta(name="ArgumentList"))) self.names = names self.command_type = command_type self.namespace = namespace self.argument_list = argument_list
def _serialize_lst(self, metadata, values, tag="LST"): obj = ET.Element("Obj", RefId=self._get_obj_id()) if not isinstance(metadata, ListMeta): metadata = ListMeta(name=metadata.name, optional=metadata.optional) self._create_tn(obj, metadata.list_types) lst = ET.SubElement(obj, tag) for value in iter(values): entry_meta = copy(metadata.list_value_meta) self.serialize(value, entry_meta, parent=lst, clear=False) return obj
def test_serialize_list_as_ie(self): serializer = Serializer() data = [] data.append("0") data.append("1") data.append("2") expected = ('<Obj RefId="0"><TN RefId="0"><T>System.Object[]</T>' "<T>System.Array</T><T>System.Object</T></TN>" "<IE><S>0</S><S>1</S><S>2</S></IE></Obj>") actual = serializer.serialize(data, ListMeta("IE")) actual_xml = to_string(ET.tostring(actual)) assert actual_xml == expected
def __init__( self, names: typing.Optional[typing.List[str]] = None, command_type: typing.Optional[int] = None, namespace: typing.Optional[typing.List[str]] = None, argument_list: typing.Optional[typing.List] = None, ) -> None: """ [MS-PSRP] 2.2.2.14 GET_COMMAND_METADATA Message https://msdn.microsoft.com/en-us/library/ee175985.aspx :param names: :param command_type: :param namespace: :param argument_list: """ super(GetCommandMetadata, self).__init__() self._extended_properties = ( ( "names", ListMeta( name="Name", list_value_meta=ObjectMeta("S"), list_types=[ "System.String[]", "System.Array", "System.Object" ], ), ), ("command_type", ObjectMeta(name="CommandType", object=CommandType)), ("namespace", ObjectMeta(name="Namespace")), ("argument_list", ListMeta(name="ArgumentList")), ) self.names = names self.command_type = command_type self.namespace = namespace self.argument_list = argument_list
def __init__( self, message_data=None, source=None, time_generated=None, tags=None, user=None, computer=None, pid=None, native_thread_id=None, managed_thread_id=None, write_information_stream=None, ): """ [MS-PSRP] 2.2.2.26 INFORMATION_RECORD Message https://msdn.microsoft.com/en-us/library/mt224023.aspx Only in protocol_version 2.3 and above :param kwargs: """ super(InformationRecord, self).__init__() self._types = [ "System.Management.Automation.InformationRecord", "System.Object" ] self._extended_properties = ( ("message_data", ObjectMeta(name="MessageData")), ("source", ObjectMeta("S", name="Source")), ("time_generated", ObjectMeta("DT", name="TimeGenerated")), ("tags", ListMeta(name="Tags", list_value_meta=ObjectMeta("S"))), ("user", ObjectMeta("S", name="User")), ("computer", ObjectMeta("S", name="Computer")), ("pid", ObjectMeta("U32", name="ProcessId")), ("native_thread_id", ObjectMeta("U32", name="NativeThreadId")), ("managed_thread_id", ObjectMeta("U32", name="ManagedThreadId")), ("write_information_stream", ObjectMeta("B", name="WriteInformationStream", optional=True)), ) self.message_data = message_data self.source = source self.time_generated = time_generated self.tags = tags self.user = user self.computer = computer self.pid = pid self.native_thread_id = native_thread_id self.managed_thread_id = managed_thread_id self.write_information_stream = write_information_stream
def __init__(self, ci=None, mi=None, mp=None): """ [MS-PSRP] 2.2.2.15 RUNSPACE_HOST_CALL Message https://msdn.microsoft.com/en-us/library/dd340830.aspx :param ci: :param mi: :param mp: """ super(RunspacePoolHostCall, self).__init__() self._extended_properties = ( ('ci', ObjectMeta("I64", name="ci")), ('mi', ObjectMeta("Obj", name="mi", object=HostMethodIdentifier)), ('mp', ListMeta(name="mp")) ) self.ci = ci self.mi = mi self.mp = mp
def deserialize(self, element, metadata=None, clear=True): if clear: self._clear() if isinstance(element, string_types): element_string = element try: element = ET.fromstring(element) except ET.ParseError as err: log.warning("Failed to parse data '%s' as XML, return raw " "xml: %s" % (element_string, str(err))) return element_string else: xml_string = ET.tostring(element, encoding='utf-8', method='xml') element_string = to_string(xml_string) metadata = metadata or ObjectMeta() if metadata.tag == "*": metadata.tag = element.tag # get the object types so we store the TN Ref ids for later use obj_types = self._get_types_from_obj(element) # check if it is a primitive object unpack_function = { # Primitive types 'S': lambda d: self._deserialize_string(d.text), 'ToString': lambda d: self._deserialize_string(d.text), 'C': lambda d: chr(int(d.text)), 'B': lambda d: d.text.lower() == "true", 'DT': lambda d: d.text, 'TS': lambda d: d.text, 'By': lambda d: int(d.text), 'SB': lambda d: int(d.text), 'U16': lambda d: int(d.text), 'I16': lambda d: int(d.text), 'U32': lambda d: int(d.text), 'I32': lambda d: int(d.text), 'U64': lambda d: int(d.text), 'I64': lambda d: int(d.text), 'Sg': lambda d: float(d.text), 'Db': lambda d: float(d.text), 'D': lambda d: d.text, # TODO: deserialize this 'BA': lambda d: base64.b64decode(d.text), 'G': lambda d: uuid.UUID(d.text), 'URI': lambda d: self._deserialize_string(d.text), 'Nil': lambda d: None, 'Version': lambda d: d.text, 'XD': lambda d: self._deserialize_string(d.text), 'SBK': lambda d: self._deserialize_string(d.text), 'SS': lambda d: self._deserialize_secure_string(d), # references an object already deserialized 'Ref': lambda d: self.obj[d.attrib['RefId']], }.get(element.tag) if unpack_function is not None: return unpack_function(element) # not a primitive object, so try and decode the complex object if type(metadata) == ObjectMeta and metadata.object is None: structures = { "Selected.Microsoft.PowerShell.Commands.GenericMeasureInfo": ObjectMeta("Obj", object=CommandMetadataCount), "System.Array": ListMeta(), "System.Collections.ArrayList": ListMeta(), "System.Collections.Hashtable": DictionaryMeta(), "System.Collections.Generic.List": ListMeta(), "System.Collections.Queue": QueueMeta(), "System.Collections.Stack": StackMeta(), "System.ConsoleColor": ObjectMeta("Obj", object=Color), "System.Management.Automation.CommandOrigin": ObjectMeta("Obj", object=CommandOrigin), "System.Management.Automation.DebugRecord": ObjectMeta("Obj", object=DebugRecord), "System.Management.Automation.ErrorRecord": ObjectMeta("Obj", object=ErrorRecord), "System.Management.Automation.Host.Coordinates": ObjectMeta("Obj", object=Coordinates), "System.Management.Automation.Host.KeyInfo": ObjectMeta("Obj", object=KeyInfoDotNet), "System.Management.Automation.Host.Size": ObjectMeta("Obj", object=Size), "System.Management.Automation.InformationalRecord": ObjectMeta("Obj", object=InformationalRecord), "System.Management.Automation.InformationRecord": ObjectMeta("Obj", object=InformationRecord), "System.Management.Automation.ParameterMetadata": ObjectMeta("Obj", object=ParameterMetadata), "System.Management.Automation.ProgressRecordType": ObjectMeta("Obj", object=ProgressRecordType), "System.Management.Automation.PSBoundParametersDictionary": DictionaryMeta(), "System.Management.Automation.PSCredential": ObjectMeta("Obj", object=PSCredential), "System.Management.Automation.PSObject": ObjectMeta("ObjDynamic", object=GenericComplexObject), "System.Management.Automation.PSPrimitiveDictionary": DictionaryMeta(), "System.Management.Automation.PSTypeName": ObjectMeta("S"), "System.Management.Automation.Remoting.RemoteHostMethodId": ObjectMeta("Obj", object=HostMethodIdentifier), "System.Management.Automation.Runspaces.ApartmentState": ObjectMeta("Obj", object=ApartmentState), "System.Management.Automation.Runspaces.PipelineResultTypes": ObjectMeta("Obj", object=PipelineResultTypes), "System.Management.Automation.Runspaces.PSThreadOptions": ObjectMeta("Obj", object=PSThreadOptions), "System.Management.Automation.Runspaces.RemoteStreamOptions": ObjectMeta("Obj", object=RemoteStreamOptions), "System.Management.Automation.SessionStateEntryVisibility": ObjectMeta("Obj", object=SessionStateEntryVisibility), "System.Management.Automation.VerboseRecord": ObjectMeta("Obj", object=VerboseRecord), "System.Management.Automation.WarningRecord": ObjectMeta("Obj", object=WarningRecord), "System.Globalization.CultureInfo": ObjectMeta("Obj", object=CultureInfo), # Fallback to the GenericComplexObject "System.Object": ObjectMeta("ObjDynamic", object=GenericComplexObject), # Primitive types "System.String": ObjectMeta("S"), "System.Char": ObjectMeta("C"), "System.Boolean": ObjectMeta("B"), "System.DateTime": ObjectMeta("DT"), # None: ObjectMeta("TS"), # duration timespan "System.Byte": ObjectMeta("By"), "System.SByte": ObjectMeta("SB"), "System.UInt16": ObjectMeta("U16"), "System.Int16": ObjectMeta("I16"), "System.UInt32": ObjectMeta("U32"), "System.Int32": ObjectMeta("I32"), "System.UInt64": ObjectMeta("U64"), "System.Int64": ObjectMeta("I64"), "System.Single": ObjectMeta("Sg"), "System.Double": ObjectMeta("Db"), "System.Decimal": ObjectMeta("D"), # None: ObjectMeta("BA"), # Byte array base64 encoded "System.Guid": ObjectMeta("G"), "System.Uri": ObjectMeta("URI"), "System.Version": ObjectMeta("Version"), "System.Xml.XmlDocument": ObjectMeta("XD"), "System.Management.Automation.ScriptBlock": ObjectMeta("SBK"), "System.Security.SecureString": ObjectMeta("SS"), } # fallback to GenericComplexObject if no types were defined if metadata.tag == "Obj" and len(obj_types) == 0: obj_types = ["System.Object"] metadata = None for obj_type in obj_types: if obj_type.startswith("Deserialized.System."): obj_type = obj_type[13:] is_list = False if obj_type.endswith("[]"): obj_type = obj_type[0:-2] is_list = True elif obj_type.startswith("System.Collections." "Generic.List`1[["): list_info = obj_type[35:-1] obj_type = list_info.split(",")[0] is_list = True elif obj_type.startswith("System.Collections.ObjectModel." "Collection`1[["): list_info = obj_type[45:-1] obj_type = list_info.split(",")[0] is_list = True elif obj_type.startswith("System.Collections.ObjectModel." "ReadOnlyCollection`1[["): list_info = obj_type[53:-1] obj_type = list_info.split(",")[0] is_list = True elif obj_type.startswith("System.Collections.Generic." "Dictionary`2[["): dict_meta = obj_type[41:-2].split("],[") key_type = structures.get(dict_meta[0].split(",")[0], ObjectMeta()) value_type = structures.get(dict_meta[1].split(",")[0], ObjectMeta()) metadata = DictionaryMeta(dict_key_meta=key_type, dict_value_meta=value_type) break obj_meta = structures.get(obj_type) if obj_meta is not None: metadata = obj_meta if is_list: metadata = ListMeta(list_value_meta=metadata) break # we were unable to find the complex object type so just return the # element if metadata is None: obj = element_string elif metadata.tag == "Obj": obj = self._deserialize_obj(element, metadata) elif metadata.tag == "ObjDynamic": obj = self._deserialize_dynamic_obj(element, metadata) elif metadata.tag == "LST": obj = self._deserialize_lst(element, metadata) elif metadata.tag == "QUE": obj = self._deserialize_que(element) elif metadata.tag == "STK": obj = self._deserialize_stk(element) elif metadata.tag == "DCT": obj = self._deserialize_dct(element) else: log.warning("Unknown metadata tag type '%s', failed to " "deserialize object" % metadata.tag) obj = element_string if element.tag == "Obj": self.obj[element.attrib['RefId']] = obj if isinstance(obj, ComplexObject): obj._xml = element_string return obj