示例#1
0
    def __init__(self, ci=None, mi=None, mr=None, me=None):
        """
        [MS-PSRP] 2.2.2.16 RUNSPACEPOOL_HOST_RESPONSE Message
        https://msdn.microsoft.com/en-us/library/dd358453.aspx

        :param ci:
        :param mi:
        :param mr:
        :param me:
        """
        super(RunspacePoolHostResponse, self).__init__()
        self._extended_properties = (
            ('ci', ObjectMeta("I64", name="ci")),
            ('mi', ObjectMeta("Obj", name="mi", object=HostMethodIdentifier)),
            ('mr', ObjectMeta(name="mr")),
            ('me',
             ObjectMeta("Obj", name="me", object=ErrorRecord, optional=True)),
        )
        self.ci = ci
        self.mi = mi
        self.mr = mr
        self.me = me
示例#2
0
文件: host.py 项目: trir262/pypsrp
    def GetVersion(self, runspace, pipeline):
        """
        MI: 2
        SHOULD return the version number of the hosting application.
        https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.host.pshost.version

        :param runspace: The runspace the host call relates to
        :param pipeline: The pipeline (if any) that the call relates to
        :return: Version number of the hosting application
        """
        meta = ObjectMeta("Version")
        value = runspace.serialize(self.version, meta)
        return value
示例#3
0
 def test_parse_three_dimensional_array(self):
     serializer = Serializer()
     actual = serializer.deserialize(self.THREE_ARRAY,
                                     ObjectMeta("Obj", object=Array))
     array = actual.array
     assert array == [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]],
                      [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23,
                                                            24]]]
     assert actual.mae == [
         1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
         20, 21, 22, 23, 24
     ]
     assert actual.mal == [2, 3, 4]
示例#4
0
    def __init__(self, session_key=None):
        """
        [MS-PSRP] 2.2.2.4 ENCRYPTED_SESSION_KEY Message
        https://msdn.microsoft.com/en-us/library/dd644930.aspx

        :param session_key: The 256-bit key for AES encryption that has been
            encrypted using the public key from the PUBLIC_KEY message using
            the RSAES-PKCS-v1_5 encryption scheme and then Base64 formatted.
        """
        super(EncryptedSessionKey, self).__init__()
        self._extended_properties = (('session_key',
                                      ObjectMeta(
                                          "S", name="EncryptedSessionKey")), )
        self.session_key = session_key
示例#5
0
    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
示例#6
0
    def test_parse_pipeline_multiple(self):
        serializer = Serializer()
        actual = serializer.deserialize(normalise_xml(self.PIPE_MULTIPLE),
                                        ObjectMeta("Obj", object=Pipeline))
        assert actual.history is None
        assert actual.is_nested is False
        assert actual.redirect_err_to_out is False
        assert len(actual.commands) == 3
        assert len(actual.commands[0].args) == 2
        assert actual.commands[0].args[0].name == "Name"
        assert actual.commands[0].args[0].value == "var"
        assert actual.commands[0].args[1].name == "Value"
        assert actual.commands[0].args[1].value == "abc"
        assert actual.commands[0].cmd == "Set-Variable"
        assert actual.commands[0].end_of_statement is True
        assert actual.commands[0].is_script is False
        assert str(actual.commands[0].merge_debug) == "None"
        assert str(actual.commands[0].merge_error) == "None"
        assert str(actual.commands[0].merge_my_result) == "None"
        assert str(actual.commands[0].merge_previous) == "None"
        assert str(actual.commands[0].merge_verbose) == "None"
        assert str(actual.commands[0].merge_warning) == "None"
        assert actual.commands[0].use_local_scope is False

        assert len(actual.commands[1].args) == 1
        assert actual.commands[1].args[0].name == "Name"
        assert actual.commands[1].args[0].value == "var"
        assert actual.commands[1].cmd == "Get-Variable"
        assert actual.commands[1].end_of_statement is False
        assert actual.commands[1].is_script is False
        assert str(actual.commands[1].merge_debug) == "None"
        assert str(actual.commands[1].merge_error) == "None"
        assert str(actual.commands[1].merge_my_result) == "None"
        assert str(actual.commands[1].merge_previous) == "None"
        assert str(actual.commands[1].merge_verbose) == "None"
        assert str(actual.commands[1].merge_warning) == "None"
        assert actual.commands[1].use_local_scope is False

        assert len(actual.commands[2].args) == 0
        assert actual.commands[2].cmd == "Write-Output"
        assert actual.commands[2].end_of_statement is True
        assert actual.commands[2].is_script is False
        assert str(actual.commands[2].merge_debug) == "None"
        assert str(actual.commands[2].merge_error) == "None"
        assert str(actual.commands[2].merge_my_result) == "None"
        assert str(actual.commands[2].merge_previous) == "None"
        assert str(actual.commands[2].merge_verbose) == "None"
        assert str(actual.commands[2].merge_warning) == "None"
        assert actual.commands[2].use_local_scope is False
示例#7
0
    def __init__(
        self,
        public_key: typing.Optional[str] = None,
    ) -> None:
        """
        [MS-PSRP] 2.2.2.3 PUBLIC_KEY Message
        https://msdn.microsoft.com/en-us/library/dd644859.aspx

        :param public_key: The Base64 encoding of the public key in the PKCS1
            format.
        """
        super(PublicKey, self).__init__()
        self._extended_properties = (("public_key",
                                      ObjectMeta("S", name="PublicKey")), )
        self.public_key = public_key
示例#8
0
    def __init__(
        self,
        event_id=None,
        source_id=None,
        time=None,
        sender=None,
        args=None,
        data=None,
        computer=None,
        runspace_id=None,
    ):
        """
        [MS-PSRP] 2.2.2.12 USER_EVENT Message
        https://msdn.microsoft.com/en-us/library/dd359395.aspx

        :param event_id:
        :param source_id:
        :param time:
        :param sender:
        :param args:
        :param data:
        :param computer:
        :param runspace_id:
        """
        super(UserEvent, self).__init__()
        self._extended_properties = (
            ("event_id", ObjectMeta("I32",
                                    name="PSEventArgs.EventIdentifier")),
            ("source_id", ObjectMeta("S",
                                     name="PSEventArgs.SourceIdentifier")),
            ("time", ObjectMeta("DT", name="PSEventArgs.TimeGenerated")),
            ("sender", ObjectMeta(name="PSEventArgs.Sender")),
            ("args", ObjectMeta(name="PSEventArgs.SourceArgs")),
            ("data", ObjectMeta(name="PSEventArgs.MessageData")),
            ("computer", ObjectMeta("S", name="PSEventArgs.ComputerName")),
            ("runspace_id", ObjectMeta("G", name="PSEventArgs.RunspaceId")),
        )
        self.event_id = event_id
        self.source_id = source_id
        self.time = time
        self.sender = sender
        self.args = args
        self.data = data
        self.computer = computer
        self.runspace_id = runspace_id
示例#9
0
    def test_deserialize_unknown_tag(self):
        serializer = Serializer()
        xml = '''<Obj N="Value" RefId="14">
    <MS>
        <S N="T">System.Management.Automation.Host.Size</S>
        <Obj N="V" RefId="15">
            <MS>
                <I32 N="height">50</I32>
                <I32 N="width">60</I32>
            </MS>
        </Obj>
    </MS>
</Obj>'''
        actual = serializer.deserialize(
            xml, ObjectMeta("fake", object=GenericComplexObject))
        assert actual == xml
示例#10
0
    def test_deserialize_obj_missing_prop(self):
        class SerialObject(ComplexObject):
            def __init__(self, **kwargs):
                super(SerialObject, self).__init__()
                self._types = ["System.Test", "System.Object"]
                self._extended_properties = (("man_prop",
                                              ObjectMeta("S",
                                                         optional=False)), )
                self.man_prop = kwargs.get("man_prop")

        serializer = Serializer()
        xml = '<Obj RefId="0"><TN RefId="0"><T>System.Test</T>' "<T>System.Object</T></TN><MS /></Obj>"
        with pytest.raises(SerializationError) as err:
            serializer.deserialize(xml, ObjectMeta("Obj", object=SerialObject))
        assert str(
            err.value
        ) == "Mandatory return value for 'Unknown' was not found on object Unknown"
示例#11
0
    def _create_obj(
        self,
        parent: ET.Element,
        obj: typing.Any,
        key: typing.Optional[str] = None,
        meta: typing.Optional[ObjectMeta] = None,
    ) -> None:
        if isinstance(obj, ComplexObject):
            for ref, value in self.obj.items():
                if value == obj:
                    sub_element = ET.SubElement(parent, "Ref", RefId=ref)
                    if key is not None:
                        sub_element.attrib["N"] = key
                    return

        if meta is None:
            meta = ObjectMeta(name=key)
        self.serialize(obj, metadata=meta, parent=parent, clear=False)
示例#12
0
    def __init__(
        self,
        no_input: typing.Optional[bool] = None,
        apartment_state: typing.Optional[ApartmentState] = None,
        remote_stream_options: typing.Optional[RemoteStreamOptions] = None,
        add_to_history: typing.Optional[bool] = None,
        host_info: typing.Optional[HostInfo] = None,
        pipeline: typing.Optional[Pipeline] = None,
        is_nested: typing.Optional[bool] = None,
    ) -> None:
        """
        [MS-PSRP] 2.2.2.10 CREATE_PIPELINE Message
        https://msdn.microsoft.com/en-us/library/dd340567.aspx

        :param no_input: Whether the pipeline will take input
        :param apartment_state: The ApartmentState of the pipeline
        :param remote_stream_options: The RemoteStreamOptions of the pipeline
        :param add_to_history: Whether to add the pipeline being execute to
            the history field of the runspace
        :param host_info: The HostInformation of the pipeline
        :param pipeline: The PowerShell object to create
        :param is_nested: Whether the pipeline is run in nested or
            steppable mode
        """
        super(CreatePipeline, self).__init__()
        self._extended_properties = (
            ("no_input", ObjectMeta("B", name="NoInput")),
            ("apartment_state",
             ObjectMeta("Obj", name="ApartmentState", object=ApartmentState)),
            ("remote_stream_options",
             ObjectMeta("Obj",
                        name="RemoteStreamOptions",
                        object=RemoteStreamOptions)),
            ("add_to_history", ObjectMeta("B", name="AddToHistory")),
            ("host_info", ObjectMeta("Obj", name="HostInfo", object=HostInfo)),
            ("pipeline", ObjectMeta("Obj", name="PowerShell",
                                    object=Pipeline)),
            ("is_nested", ObjectMeta("B", name="IsNested")),
        )

        self.no_input = no_input
        self.apartment_state = apartment_state
        self.remote_stream_options = remote_stream_options
        self.add_to_history = add_to_history
        self.host_info = host_info
        self.pipeline = pipeline
        self.is_nested = is_nested
示例#13
0
    def __init__(
        self,
        activity=None,
        activity_id=None,
        description=None,
        current_operation=None,
        parent_activity_id=None,
        percent_complete=None,
        progress_type=None,
        seconds_remaining=None,
    ):
        """
        [MS-PSRP] 2.2.2.25 PROGRESS_RECORD Message
        https://msdn.microsoft.com/en-us/library/dd340751.aspx

        :param kwargs:
        """
        super(ProgressRecord, self).__init__()
        self._extended_properties = (
            ("activity", ObjectMeta("S", name="Activity")),
            ("activity_id", ObjectMeta("I32", name="ActivityId")),
            ("description", ObjectMeta("S", name="StatusDescription")),
            ("current_operation", ObjectMeta("S", name="CurrentOperation")),
            ("parent_activity_id", ObjectMeta("I32", name="ParentActivityId")),
            ("percent_complete", ObjectMeta("I32", name="PercentComplete")),
            ("progress_type",
             ObjectMeta("Obj", name="Type", object=ProgressRecordType)),
            ("seconds_remaining", ObjectMeta("I32", name="SecondsRemaining")),
        )
        self.activity = activity
        self.activity_id = activity_id
        self.description = description
        self.current_operation = current_operation
        self.parent_activity_id = parent_activity_id
        self.percent_complete = percent_complete
        self.progress_type = progress_type
        self.seconds_remaining = seconds_remaining
示例#14
0
    def test_psrp(self, functional_transports):
        for wsman in functional_transports:
            with wsman, RunspacePool(wsman) as pool:
                pool.exchange_keys()
                ps = PowerShell(pool)
                ps.add_cmdlet("Get-Item").add_parameter("Path", "C:\\Windows")
                ps.add_statement()

                sec_string = pool.serialize("super secret", ObjectMeta("SS"))
                ps.add_cmdlet("Set-Variable")
                ps.add_parameter("Name", "password")
                ps.add_parameter("Value", sec_string)

                ps.add_statement().add_script(
                    "[System.Runtime.InteropServices.marshal]"
                    "::PtrToStringAuto([System.Runtime.InteropServices.marshal]"
                    "::SecureStringToBSTR($password))")
                ps.add_statement().add_cmdlet("ConvertTo-SecureString")
                ps.add_parameter("String", "host secret")
                ps.add_parameter("AsPlainText")
                ps.add_parameter("Force")

                large_string = "hello world " * 3000
                ps.add_statement()
                ps.add_script(
                    "$VerbosePreference = 'Continue'; Write-Verbose '%s'" %
                    large_string)

                actual = ps.invoke()

            assert ps.had_errors is False
            assert len(actual) == 3
            assert str(actual[0]) == "C:\\Windows"
            assert actual[1] == "super secret"
            assert actual[2] == "host secret"
            assert str(ps.streams.verbose[0]) == large_string
示例#15
0
    def test_parse_msg(self):
        xml = """<Obj RefId="0">
            <MS>
                <I32 N="PSEventArgs.EventIdentifier">1</I32>
                <S N="PSEventArgs.SourceIdentifier">ae6245f2-c179-4a9a-a039-47b60fc44500</S>
                <DT N="PSEventArgs.TimeGenerated">2009-06-17T10:57:23.1578277-07:00</DT>
                <Obj N="PSEventArgs.Sender" RefId="1">
                    <TN RefId="0">
                        <T>System.Timers.Timer</T>
                        <T>System.ComponentModel.Component</T>
                        <T>System.MarshalByRefObject</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>System.Timers.Timer</ToString>
                    <Props>
                        <B N="AutoReset">true</B>
                        <B N="Enabled">true</B>
                        <Db N="Interval">5000</Db>
                        <Nil N="Site"/>
                        <Nil N="SynchronizingObject"/>
                        <Nil N="Container"/>
                    </Props>
                </Obj>
                <Obj N="PSEventArgs.SourceArgs" RefId="2">
                    <TN RefId="1">
                        <T>System.Object[]</T>
                        <T>System.Array</T>
                        <T>System.Object</T>
                    </TN>
                    <LST>
                        <Ref RefId="1"/>
                        <Obj RefId="3">
                            <TN RefId="2">
                                <T>System.Timers.ElapsedEventArgs</T>
                                <T>System.EventArgs</T>
                                <T>System.Object</T>
                            </TN>
                            <ToString>System.Timers.ElapsedEventArgs</ToString>
                            <Props>
                                <DT N="SignalTime">2009-06-17T10:57:23.1568275-07:00</DT>
                            </Props>
                        </Obj>
                    </LST>
                </Obj>
                <Nil N="PSEventArgs.MessageData"/>
                <Nil N="PSEventArgs.ComputerName"/>
                <G N="PSEventArgs.RunspaceId">fb9c87e8-1190-40a7-a681-6fc9b9f84a17</G>
            </MS>
        </Obj>"""
        serializer = Serializer()
        meta = ObjectMeta("Obj", object=UserEvent)
        actual = serializer.deserialize(xml, meta)

        assert str(actual.args[0]) == "System.Timers.Timer"
        assert actual.args[0].adapted_properties["Interval"] == 5000.0
        assert str(actual.args[1]) == "System.Timers.ElapsedEventArgs"
        assert actual.args[1].adapted_properties[
            "SignalTime"] == "2009-06-17T10:57:23.1568275-07:00"
        assert actual.computer is None
        assert actual.data is None
        assert actual.event_id == 1
        assert actual.runspace_id == uuid.UUID(
            "fb9c87e8-1190-40a7-a681-6fc9b9f84a17")
        assert str(actual.sender) == "System.Timers.Timer"
        assert actual.sender.adapted_properties["Interval"] == 5000.0
        assert actual.source_id == "ae6245f2-c179-4a9a-a039-47b60fc44500"
        assert actual.time == "2009-06-17T10:57:23.1578277-07:00"
示例#16
0
    def test_parse_warning(self):
        xml = """<Obj RefId="0">
            <TN RefId="0">
                <T>System.Management.Automation.WarningRecord</T>
                <T>System.Management.Automation.InformationalRecord</T>
                <T>System.Object</T>
            </TN>
            <ToString>warning stream</ToString>
            <MS>
                <S N="InformationalRecord_Message">warning stream</S>
                <B N="InformationalRecord_SerializeInvocationInfo">true</B>
                <Obj N="InvocationInfo_BoundParameters" RefId="1">
                    <TN RefId="1">
                        <T>System.Management.Automation.PSBoundParametersDictionary</T>
                        <T>System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
                        <T>System.Object</T>
                    </TN>
                    <DCT/>
                </Obj>
                <Obj N="InvocationInfo_CommandOrigin" RefId="2">
                    <TN RefId="2">
                        <T>System.Management.Automation.CommandOrigin</T>
                        <T>System.Enum</T>
                        <T>System.ValueType</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>Runspace</ToString>
                    <I32>0</I32>
                </Obj>
                <B N="InvocationInfo_ExpectingInput">false</B>
                <S N="InvocationInfo_InvocationName"/>
                <S N="InvocationInfo_Line"/>
                <I32 N="InvocationInfo_OffsetInLine">0</I32>
                <I64 N="InvocationInfo_HistoryId">1</I64>
                <Obj N="InvocationInfo_PipelineIterationInfo" RefId="3">
                    <TN RefId="3">
                        <T>System.Int32[]</T>
                        <T>System.Array</T>
                        <T>System.Object</T>
                    </TN>
                    <LST>
                        <I32>0</I32>
                        <I32>0</I32>
                    </LST>
                </Obj>
                <I32 N="InvocationInfo_PipelineLength">1</I32>
                <I32 N="InvocationInfo_PipelinePosition">1</I32>
                <S N="InvocationInfo_PSScriptRoot"/>
                <Nil N="InvocationInfo_PSCommandPath"/>
                <S N="InvocationInfo_PositionMessage"/>
                <I32 N="InvocationInfo_ScriptLineNumber">0</I32>
                <S N="InvocationInfo_ScriptName"/>
                <Obj N="InvocationInfo_UnboundArguments" RefId="4">
                    <TN RefId="4">
                        <T>System.Collections.Generic.List`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
                        <T>System.Object</T>
                    </TN>
                    <LST/>
                </Obj>
                <B N="SerializeExtent">false</B>
                <Obj N="CommandInfo_CommandType" RefId="5">
                    <TN RefId="5">
                        <T>System.Management.Automation.CommandTypes</T>
                        <T>System.Enum</T>
                        <T>System.ValueType</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>Script</ToString>
                    <I32>64</I32>
                </Obj>
                <S N="CommandInfo_Definition">Write-Warning 'warning stream'_x000A_</S>
                <S N="CommandInfo_Name"/>
                <Obj N="CommandInfo_Visibility" RefId="6">
                    <TN RefId="6">
                        <T>System.Management.Automation.SessionStateEntryVisibility</T>
                        <T>System.Enum</T>
                        <T>System.ValueType</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>Public</ToString>
                    <I32>0</I32>
                </Obj>
                <Obj N="InformationalRecord_PipelineIterationInfo" RefId="7">
                    <TN RefId="7">
                        <T>System.Collections.ObjectModel.ReadOnlyCollection`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
                        <T>System.Object</T>
                    </TN>
                    <LST>
                        <I32>0</I32>
                        <I32>0</I32>
                    </LST>
                </Obj>
            </MS>
        </Obj>"""
        serializer = Serializer()
        meta = ObjectMeta("Obj", object=WarningRecord)
        actual = serializer.deserialize(xml, meta)

        assert str(actual) == "warning stream"
        assert actual.invocation
        assert actual.message == "warning stream"
        assert actual.pipeline_iteration_info == [0, 0]
        assert actual.invocation_name == ""
        assert actual.invocation_bound_parameters == {}
        assert actual.invocation_unbound_arguments == []
        assert str(actual.invocation_command_origin) == "Runspace"
        assert actual.invocation_expecting_input is False
        assert actual.invocation_line == ""
        assert actual.invocation_offset_in_line == 0
        assert actual.invocation_position_message == ""
        assert actual.invocation_script_name == ""
        assert actual.invocation_script_line_number == 0
        assert actual.invocation_history_id == 1
        assert actual.invocation_pipeline_length == 1
        assert actual.invocation_pipeline_position == 1
        assert actual.invocation_pipeline_iteration_info == [0, 0]
        assert actual.command_definition == "Write-Warning 'warning stream'\n"
        assert actual.command_name == ""
        assert str(actual.command_type) == "Script"
        assert str(actual.command_visibility) == "Public"
示例#17
0
    def test_parse_error(self):
        xml = """<Obj RefId="0">
            <TN RefId="0">
                <T>System.Management.Automation.ErrorRecord</T>
                <T>System.Object</T>
            </TN>
            <ToString>error stream</ToString>
            <MS>
                <B N="writeErrorStream">true</B>
                <Obj N="Exception" RefId="1">
                    <TN RefId="1">
                        <T>Microsoft.PowerShell.Commands.WriteErrorException</T>
                        <T>System.SystemException</T>
                        <T>System.Exception</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>Microsoft.PowerShell.Commands.WriteErrorException: error stream</ToString>
                    <Props>
                        <S N="Message">error stream</S>
                        <Obj N="Data" RefId="2">
                            <TN RefId="2">
                                <T>System.Collections.ListDictionaryInternal</T>
                                <T>System.Object</T>
                            </TN>
                            <DCT/>
                        </Obj>
                        <Nil N="InnerException"/>
                        <Nil N="TargetSite"/>
                        <Nil N="StackTrace"/>
                        <Nil N="HelpLink"/>
                        <Nil N="Source"/>
                        <I32 N="HResult">-2146233087</I32>
                    </Props>
                </Obj>
                <Nil N="TargetObject"/>
                <S N="FullyQualifiedErrorId">Microsoft.PowerShell.Commands.WriteErrorException</S>
                <Obj N="InvocationInfo" RefId="3">
                    <TN RefId="3">
                        <T>System.Management.Automation.InvocationInfo</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>System.Management.Automation.InvocationInfo</ToString>
                    <Props>
                        <S N="MyCommand">Write-Error 'error stream'_x000A_</S>
                        <Obj N="BoundParameters" RefId="4">
                            <TN RefId="4">
                                <T>System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
                                <T>System.Object</T>
                            </TN>
                            <DCT/>
                        </Obj>
                        <Obj N="UnboundArguments" RefId="5">
                            <TN RefId="5">
                                <T>System.Collections.Generic.List`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
                                <T>System.Object</T>
                            </TN>
                            <LST/>
                        </Obj>
                        <I32 N="ScriptLineNumber">0</I32>
                        <I32 N="OffsetInLine">0</I32>
                        <I64 N="HistoryId">1</I64>
                        <S N="ScriptName"/>
                        <S N="Line"/>
                        <S N="PositionMessage"/>
                        <S N="PSScriptRoot"/>
                        <Nil N="PSCommandPath"/>
                        <S N="InvocationName"/>
                        <I32 N="PipelineLength">0</I32>
                        <I32 N="PipelinePosition">0</I32>
                        <B N="ExpectingInput">false</B>
                        <S N="CommandOrigin">Internal</S>
                        <Nil N="DisplayScriptPosition"/>
                    </Props>
                </Obj>
                <I32 N="ErrorCategory_Category">0</I32>
                <S N="ErrorCategory_Activity">Write-Error</S>
                <S N="ErrorCategory_Reason">WriteErrorException</S>
                <S N="ErrorCategory_TargetName"/>
                <S N="ErrorCategory_TargetType"/>
                <S N="ErrorCategory_Message">NotSpecified: (:) [Write-Error], WriteErrorException</S>
                <B N="SerializeExtendedInfo">true</B>
                <Ref N="InvocationInfo_BoundParameters" RefId="4"/>
                <Obj N="InvocationInfo_CommandOrigin" RefId="6">
                    <TN RefId="6">
                        <T>System.Management.Automation.CommandOrigin</T>
                        <T>System.Enum</T>
                        <T>System.ValueType</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>Internal</ToString>
                    <I32>1</I32>
                </Obj>
                <B N="InvocationInfo_ExpectingInput">false</B>
                <S N="InvocationInfo_InvocationName"/>
                <S N="InvocationInfo_Line"/>
                <I32 N="InvocationInfo_OffsetInLine">0</I32>
                <I64 N="InvocationInfo_HistoryId">1</I64>
                <Obj N="InvocationInfo_PipelineIterationInfo" RefId="7">
                    <TN RefId="7">
                        <T>System.Int32[]</T>
                        <T>System.Array</T>
                        <T>System.Object</T>
                    </TN>
                    <LST/>
                </Obj>
                <I32 N="InvocationInfo_PipelineLength">0</I32>
                <I32 N="InvocationInfo_PipelinePosition">0</I32>
                <S N="InvocationInfo_PSScriptRoot"/>
                <Nil N="InvocationInfo_PSCommandPath"/>
                <S N="InvocationInfo_PositionMessage"/>
                <I32 N="InvocationInfo_ScriptLineNumber">0</I32>
                <S N="InvocationInfo_ScriptName"/>
                <Ref N="InvocationInfo_UnboundArguments" RefId="5"/>
                <B N="SerializeExtent">false</B>
                <Obj N="CommandInfo_CommandType" RefId="8">
                    <TN RefId="8">
                        <T>System.Management.Automation.CommandTypes</T>
                        <T>System.Enum</T>
                        <T>System.ValueType</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>Script</ToString>
                    <I32>64</I32>
                </Obj>
                <S N="CommandInfo_Definition">Write-Error 'error stream'_x000A_</S>
                <S N="CommandInfo_Name"/>
                <Obj N="CommandInfo_Visibility" RefId="9">
                    <TN RefId="9">
                        <T>System.Management.Automation.SessionStateEntryVisibility</T>
                        <T>System.Enum</T>
                        <T>System.ValueType</T>
                        <T>System.Object</T>
                    </TN>
                    <ToString>Public</ToString>
                    <I32>0</I32>
                </Obj>
                <Obj N="PipelineIterationInfo" RefId="10">
                    <TN RefId="10">
                        <T>System.Collections.ObjectModel.ReadOnlyCollection`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</T>
                        <T>System.Object</T>
                    </TN>
                    <LST>
                        <I32>0</I32>
                        <I32>0</I32>
                    </LST>
                </Obj>
                <S N="ErrorDetails_ScriptStackTrace">at &lt;ScriptBlock&gt;, &lt;No file&gt;: line 5</S>
                <Nil N="PSMessageDetails"/>
            </MS>
        </Obj>"""
        serializer = Serializer()
        meta = ObjectMeta("Obj", object=ErrorRecordMessage)
        actual = serializer.deserialize(xml, meta)

        assert str(actual) == "error stream"
        assert actual.exception.adapted_properties["Message"] == "error stream"
        assert actual.exception.adapted_properties["HResult"] == -2146233087
        assert actual.target_object is None
        assert actual.fq_error == "Microsoft.PowerShell.Commands.WriteErrorException"
        assert actual.invocation
        invoc_props = actual.invocation_info.adapted_properties
        assert invoc_props["MyCommand"] == "Write-Error 'error stream'\n"
        assert invoc_props["BoundParameters"] == {}
        assert invoc_props["UnboundArguments"] == []
        assert invoc_props["ScriptLineNumber"] == 0
        assert invoc_props["OffsetInLine"] == 0
        assert invoc_props["HistoryId"] == 1
        assert invoc_props["CommandOrigin"] == "Internal"
        assert actual.fq_error == "Microsoft.PowerShell.Commands.WriteErrorException"
        assert actual.category == 0
        assert actual.reason == "WriteErrorException"
        assert actual.target_name == ""
        assert actual.target_type == ""
        assert actual.message == "NotSpecified: (:) [Write-Error], WriteErrorException"
        assert actual.details_message is None
        assert actual.action is None
        assert actual.script_stacktrace == "at <ScriptBlock>, <No file>: line 5"
        assert actual.extended_info_present
        assert actual.invocation_name == ""
        assert actual.invocation_bound_parameters == {}
        assert actual.invocation_unbound_arguments == []
        assert str(actual.invocation_command_origin) == "Internal"
        assert actual.invocation_expecting_input is False
        assert actual.invocation_line == ""
        assert actual.invocation_offset_in_line == 0
        assert actual.invocation_position_message == ""
        assert actual.invocation_script_name == ""
        assert actual.invocation_script_line_number == 0
        assert actual.invocation_history_id == 1
        assert actual.invocation_pipeline_length == 0
        assert actual.invocation_pipeline_position == 0
        assert actual.invocation_pipeline_iteration_info == []
        assert str(actual.command_type) == "Script"
        assert actual.command_definition == "Write-Error 'error stream'\n"
        assert actual.command_name == ""
        assert str(actual.command_visibility) == "Public"
        assert actual.pipeline_iteration_info == [0, 0]
示例#18
0
    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
示例#19
0
    def serialize(
        self,
        value: typing.Any,
        metadata: typing.Optional[ObjectMeta] = None,
        parent: typing.Optional[ET.Element] = None,
        clear: bool = True,
    ) -> typing.Optional[ET.Element]:
        """
        Serializes a raw value or class into an XML Element that can be sent
        over to the remote host.

        :param value: The value to serialize
        :param metadata: Any extra metadata to control how to serialize the
            value, if None then the value will be inferred by the type
        :param parent: Whether to append the element onto a parent element
        :param clear: Whether to clear the Obj and TN reference map, this
            should only be True when initially calling serialize
        :return: The XML Element from the serializied value
        """
        if clear:
            self._clear()

        if isinstance(value, ET.Element):
            if metadata is not None and metadata.name is not None:
                value.attrib["N"] = metadata.name

            if parent is not None:
                parent.append(value)

            return value

        metadata = metadata or ObjectMeta()
        if metadata.tag == "*":
            if isinstance(value, TaggedValue):
                metadata.tag = value.tag
                value = value.value
            else:
                metadata.tag = self._get_tag_from_value(value)

        pack_function: typing.Callable[[ObjectMeta, typing.Any], ET.Element] = {  # type: ignore[assignment] # Not sure why
            # primitive types
            "S": lambda m, d: self._serialize_string(d),
            "ToString": lambda d: self._serialize_string(d),
            "C": lambda m, d: str(ord(d)),
            "B": lambda m, d: str(d).lower(),
            "DT": lambda m, d: None,
            "TS": lambda m, d: str(d),
            "By": lambda m, d: str(d),
            "SB": lambda m, d: str(d),
            "U16": lambda m, d: str(d),
            "I16": lambda m, d: str(d),
            "U32": lambda m, d: str(d),
            "I32": lambda m, d: str(d),
            "U64": lambda m, d: str(d),
            "I64": lambda m, d: str(d),
            "Sg": lambda m, d: str(d),
            "Db": lambda m, d: str(d),
            "D": lambda m, d: str(d),
            "BA": lambda m, d: to_string(base64.b64encode(d)),
            "G": lambda m, d: str(d),
            "URI": lambda m, d: self._serialize_string(d),
            "Version": lambda m, d: str(d),
            "XD": lambda m, d: self._serialize_string(d),
            "SBK": lambda m, d: self._serialize_string(d),
            "SS": lambda m, d: self._serialize_secure_string(d),
            "Obj": self._serialize_obj,
            "ObjDynamic": self._serialize_dynamic_obj,
            "LST": self._serialize_lst,
            "IE": self._serialize_ie,
            "QUE": self._serialize_que,
            "STK": self._serialize_stk,
            "DCT": self._serialize_dct,
        }[
            metadata.tag
        ]

        if value is None:
            if metadata.optional:
                return None
            element = ET.Element("Nil")
        else:
            element_value = pack_function(metadata, value)
            if isinstance(element_value, str):
                element = ET.Element(metadata.tag)
                element.text = element_value
            else:
                element = element_value

        if metadata.name is not None:
            element.attrib["N"] = metadata.name

        if parent is not None:
            parent.append(element)

        return element
示例#20
0
    def unpack(data, serializer):
        destination = struct.unpack("<I", data[0:4])[0]
        message_type = struct.unpack("<I", data[4:8])[0]
        rpid = str(uuid.UUID(bytes=data[8:24]))
        pid = str(uuid.UUID(bytes=data[24:40]))

        if data[40:43] == b"\xEF\xBB\xBF":
            # 40-43 is the UTF-8 BOM which we don't care about
            message_data = to_string(data[43:])
        else:
            message_data = to_string(data[40:])

        log.info("Unpacking PSRP message of type %d: %s" %
                 (message_type, message_data))

        message_obj = {
            MessageType.SESSION_CAPABILITY: SessionCapability,
            MessageType.INIT_RUNSPACEPOOL: InitRunspacePool,
            MessageType.PUBLIC_KEY: PublicKey,
            MessageType.ENCRYPTED_SESSION_KEY: EncryptedSessionKey,
            MessageType.PUBLIC_KEY_REQUEST: PublicKeyRequest,
            MessageType.SET_MAX_RUNSPACES: SetMaxRunspaces,
            MessageType.SET_MIN_RUNSPACES: SetMinRunspaces,
            MessageType.RUNSPACE_AVAILABILITY: RunspaceAvailability,
            MessageType.RUNSPACEPOOL_STATE: RunspacePoolStateMessage,
            MessageType.CREATE_PIPELINE: CreatePipeline,
            MessageType.GET_AVAILABLE_RUNSPACES: GetAvailableRunspaces,
            MessageType.USER_EVENT: UserEvent,
            MessageType.APPLICATION_PRIVATE_DATA: ApplicationPrivateData,
            MessageType.GET_COMMAND_METADATA: GetCommandMetadata,
            MessageType.RUNSPACEPOOL_HOST_CALL: RunspacePoolHostCall,
            MessageType.RUNSPACEPOOL_HOST_RESPONSE: RunspacePoolHostResponse,
            MessageType.PIPELINE_INPUT: PipelineInput,
            MessageType.END_OF_PIPELINE_INPUT: EndOfPipelineInput,
            MessageType.PIPELINE_OUTPUT: PipelineOutput,
            MessageType.ERROR_RECORD: ErrorRecordMessage,
            MessageType.PIPELINE_STATE: PipelineState,
            MessageType.DEBUG_RECORD: DebugRecord,
            MessageType.VERBOSE_RECORD: VerboseRecord,
            MessageType.WARNING_RECORD: WarningRecord,
            MessageType.PROGRESS_RECORD: ProgressRecord,
            MessageType.INFORMATION_RECORD: InformationRecord,
            MessageType.PIPELINE_HOST_CALL: PipelineHostCall,
            MessageType.PIPELINE_HOST_RESPONSE: PipelineHostResponse,
            MessageType.CONNECT_RUNSPACEPOOL: ConnectRunspacePool,
            MessageType.RUNSPACEPOOL_INIT_DATA: RunspacePoolInitData,
            MessageType.RESET_RUNSPACE_STATE: ResetRunspaceState
        }[message_type]

        # PIPELINE_OUTPUT is a weird one, it contains the actual output objects
        # not encapsulated so we set it to a dynamic object and the serializer
        # will work out what is best
        if message_type == MessageType.PIPELINE_OUTPUT:
            # try to deserialize using our known objects, if that fails then
            # we want to get a generic object at least but raise a warning
            try:
                message_data = serializer.deserialize(message_data)
            except SerializationError as err:
                warnings.warn("Failed to deserialize msg, trying to "
                              "deserialize as generic complex object: %s" %
                              str(err))
                meta = ObjectMeta("ObjDynamic", object=GenericComplexObject)
                message_data = serializer.deserialize(message_data, meta)
            message = PipelineOutput()
            message.data = message_data
        elif message_type == MessageType.PIPELINE_INPUT:
            message_data = serializer.deserialize(message_data)
            message = PipelineInput()
            message.data = message_data
        elif message_type == MessageType.PUBLIC_KEY_REQUEST:
            message = PublicKeyRequest()
        else:
            message_meta = ObjectMeta("Obj", object=message_obj)
            message = serializer.deserialize(message_data, message_meta)

        return Message(destination, rpid, pid, message, serializer)
示例#21
0
    def serialize(self, value, metadata=None, parent=None, clear=True):
        """
        Serializes a raw value or class into an XML Element that can be sent
        over to the remote host.

        :param value: The value to serialize
        :param metadata: Any extra metadata to control how to serialize the
            value, if None then the value will be inferred by the type
        :param parent: Whether to append the element onto a parent element
        :param clear: Whether to clear the Obj and TN reference map, this
            should only be True when initially calling serialize
        :return: The XML Element from the serializied value
        """
        if clear:
            self._clear()

        if isinstance(value, element_type):
            if metadata is not None and metadata.name is not None:
                value.attrib['N'] = metadata.name

            if parent is not None:
                parent.append(value)

            return value

        metadata = metadata or ObjectMeta()
        if metadata.tag == "*":
            metadata.tag = self._get_tag_from_value(value)

        pack_function = {
            # primitive types
            'S': lambda m, d: self._serialize_string(d),
            'ToString': lambda d: self._serialize_string(d),
            'C': lambda m, d: str(ord(d)),
            'B': lambda m, d: str(d).lower(),
            'DT': lambda m, d: None,
            'TS': lambda m, d: str(d),
            'By': lambda m, d: str(d),
            'SB': lambda m, d: str(d),
            'U16': lambda m, d: str(d),
            'I16': lambda m, d: str(d),
            'U32': lambda m, d: str(d),
            'I32': lambda m, d: str(d),
            'U64': lambda m, d: str(d),
            'I64': lambda m, d: str(d),
            'Sg': lambda m, d: str(d),
            'Db': lambda m, d: str(d),
            'D': lambda m, d: str(d),
            'BA': lambda m, d: to_string(base64.b64encode(d)),
            'G': lambda m, d: str(d),
            'URI': lambda m, d: self._serialize_string(d),
            'Version': lambda m, d: str(d),
            'XD': lambda m, d: self._serialize_string(d),
            'SBK': lambda m, d: self._serialize_string(d),
            'SS': lambda m, d: self._serialize_secure_string(d),
            'Obj': self._serialize_obj,
            "ObjDynamic": self._serialize_dynamic_obj,
            'LST': self._serialize_lst,
            'IE': self._serialize_ie,
            'QUE': self._serialize_que,
            'STK': self._serialize_stk,
            'DCT': self._serialize_dct
        }[metadata.tag]

        if value is None:
            if metadata.optional:
                return
            element = ET.Element("Nil")
        else:
            element_value = pack_function(metadata, value)
            if isinstance(element_value, string_types):
                element = ET.Element(metadata.tag)
                element.text = element_value
            else:
                element = element_value

        if metadata.name is not None:
            element.attrib['N'] = metadata.name

        if parent is not None:
            parent.append(element)

        return element
示例#22
0
    def test_psrp_pshost_ui_mocked_methods(self, wsman_conn, monkeypatch):
        # This tests that the args from an actual host call match up with our
        # definitions
        monkeypatch.setattr('cryptography.hazmat.primitives.asymmetric.rsa.'
                            'generate_private_key', gen_rsa_keypair)

        mock_read_line = MagicMock(return_value="ReadLine response")
        mock_read_line_as_ss = MagicMock()
        mock_write1 = MagicMock(return_value=None)
        mock_write2 = MagicMock(return_value=None)
        mock_write_line1 = MagicMock(return_value=None)
        mock_write_line2 = MagicMock(return_value=None)
        mock_write_line3 = MagicMock(return_value=None)
        mock_write_error = MagicMock(return_value=None)
        mock_write_debug = MagicMock(return_value=None)
        mock_write_progress = MagicMock(return_value=None)
        mock_write_verbose = MagicMock(return_value=None)
        mock_write_warning = MagicMock(return_value=None)
        mock_prompt = MagicMock(return_value={
            "prompt field": "prompt response",
        })
        mock_prompt_credential = MagicMock()
        mock_prompt_choice = MagicMock(return_value=1)

        host_ui = PSHostUserInterface()
        host_ui.ReadLine = mock_read_line
        host_ui.ReadLineAsSecureString = mock_read_line_as_ss
        host_ui.Write1 = mock_write1
        host_ui.Write2 = mock_write2
        host_ui.WriteLine1 = mock_write_line1
        host_ui.WriteLine2 = mock_write_line2
        host_ui.WriteLine3 = mock_write_line3
        host_ui.WriteErrorLine = mock_write_error
        host_ui.WriteDebugLine = mock_write_debug
        host_ui.WriteProgress = mock_write_progress
        host_ui.WriteVerboseLine = mock_write_verbose
        host_ui.WriteWarningLine = mock_write_warning
        host_ui.Prompt = mock_prompt
        # seems like PS never calls PromptForCredential1 so we will skip that
        host_ui.PromptForCredential2 = mock_prompt_credential
        host_ui.PromptForChoice = mock_prompt_choice

        host = PSHost(None, None, False, None, None, host_ui, None)

        with RunspacePool(wsman_conn, host=host) as pool:
            pool.exchange_keys()
            mock_read_line_as_ss.return_value = pool.serialize(
                u"ReadLineAsSecureString response", ObjectMeta("SS")
            )
            mock_ps_credential = PSCredential(username="******",
                                              password=u"password")
            mock_prompt_credential.return_value = mock_ps_credential

            ps = PowerShell(pool)
            ps.add_script('''$host.UI.ReadLine()
$host.UI.ReadLineAsSecureString()
$host.UI.Write("Write1")
$host.UI.Write([System.ConsoleColor]::Blue, [System.ConsoleColor]::White, "Write2")
$host.UI.WriteLine()
$host.UI.WriteLine("WriteLine2")
$host.UI.WriteLine([System.ConsoleColor]::Gray, [System.ConsoleColor]::Green, "WriteLine3")
$host.UI.WriteErrorLine("WriteErrorLine")
$host.UI.WriteDebugLine("WriteDebugLine")
$host.UI.WriteProgress(1, (New-Object -TypeName System.Management.Automation.ProgressRecord -ArgumentList 2, "activity", "description"))
$host.UI.WriteVerboseLine("WriteVerboseLine")
$host.UI.WriteWarningLine("WriteWarningLine")

$prompt_field = New-Object -TypeName System.Management.Automation.Host.FieldDescription -ArgumentList @("prompt field")
$prompt_field.Label = "PromptLabel"
$host.UI.Prompt("Prompt caption", "Prompt message", $prompt_field)

$host.UI.PromptForCredential("PromptForCredential caption", "PromptForCredential message", "PromptForCredential user", "PromptForCredential target")

$choice_field1 = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList "Prompt1 label", "Prompt1 help"
$choice_field2 = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList "Prompt2 label", "Prompt2 help"
$host.UI.PromptForChoice("PromptForChoice caption", "PromptForChoice message", @($choice_field1, $choice_field2), 0)''')
            actual = ps.invoke()

        assert len(actual) == 5

        assert actual[0] == "ReadLine response"
        assert mock_read_line.call_count == 1
        assert isinstance(mock_read_line.call_args[0][0], RunspacePool)
        assert isinstance(mock_read_line.call_args[0][1], PowerShell)

        assert actual[1] == "ReadLineAsSecureString response"
        assert mock_read_line_as_ss.call_count == 1
        assert isinstance(mock_read_line_as_ss.call_args[0][0],
                          RunspacePool)
        assert isinstance(mock_read_line_as_ss.call_args[0][1], PowerShell)

        assert mock_write1.call_count == 1
        assert isinstance(mock_write1.call_args[0][0], RunspacePool)
        assert isinstance(mock_write1.call_args[0][1], PowerShell)
        assert mock_write1.call_args[0][2] == "Write1"

        assert mock_write2.call_count == 1
        assert isinstance(mock_write2.call_args[0][0], RunspacePool)
        assert isinstance(mock_write2.call_args[0][1], PowerShell)
        assert mock_write2.call_args[0][2] == Color.BLUE
        assert mock_write2.call_args[0][3] == Color.WHITE
        assert mock_write2.call_args[0][4] == "Write2"

        assert mock_write_line1.call_count == 1
        assert isinstance(mock_write_line1.call_args[0][0], RunspacePool)
        assert isinstance(mock_write_line1.call_args[0][1], PowerShell)

        assert mock_write_line2.call_count == 1
        assert isinstance(mock_write_line2.call_args[0][0], RunspacePool)
        assert isinstance(mock_write_line2.call_args[0][1], PowerShell)
        assert mock_write_line2.call_args[0][2] == "WriteLine2"

        assert mock_write_line3.call_count == 1
        assert isinstance(mock_write_line3.call_args[0][0], RunspacePool)
        assert isinstance(mock_write_line3.call_args[0][1], PowerShell)
        assert mock_write_line3.call_args[0][2] == Color.GRAY
        assert mock_write_line3.call_args[0][3] == Color.GREEN
        assert mock_write_line3.call_args[0][4] == "WriteLine3"

        assert mock_write_error.call_count == 1
        assert isinstance(mock_write_error.call_args[0][0], RunspacePool)
        assert isinstance(mock_write_error.call_args[0][1], PowerShell)
        assert mock_write_error.call_args[0][2] == "WriteErrorLine"

        assert mock_write_debug.call_count == 1
        assert isinstance(mock_write_debug.call_args[0][0], RunspacePool)
        assert isinstance(mock_write_debug.call_args[0][1], PowerShell)
        assert mock_write_debug.call_args[0][2] == "WriteDebugLine"

        # On PSv5 a progress record is always sent, we still sent one
        # ourselves to ensure it works so we verify we received at least
        # one and assert the last
        assert mock_write_progress.call_count > 0
        progress_args = mock_write_progress.call_args_list[-1]
        assert isinstance(progress_args[0][0], RunspacePool)
        assert isinstance(progress_args[0][1], PowerShell)
        assert progress_args[0][2] == 1
        progress_record = pool._serializer.deserialize(
            progress_args[0][3], ObjectMeta("Obj", object=ProgressRecord)
        )
        assert progress_record.activity == "activity"
        assert progress_record.activity_id == 2
        assert progress_record.description == "description"

        assert mock_write_verbose.call_count == 1
        assert isinstance(mock_write_verbose.call_args[0][0], RunspacePool)
        assert isinstance(mock_write_verbose.call_args[0][1], PowerShell)
        assert mock_write_verbose.call_args[0][2] == "WriteVerboseLine"

        assert mock_write_warning.call_count == 1
        assert isinstance(mock_write_warning.call_args[0][0], RunspacePool)
        assert isinstance(mock_write_warning.call_args[0][1], PowerShell)
        assert mock_write_warning.call_args[0][2] == "WriteWarningLine"

        assert actual[2] == {"prompt field": "prompt response"}
        assert mock_prompt.call_count == 1
        assert isinstance(mock_prompt.call_args[0][0], RunspacePool)
        assert isinstance(mock_prompt.call_args[0][1], PowerShell)
        assert mock_prompt.call_args[0][2] == "Prompt caption"
        assert mock_prompt.call_args[0][3] == "Prompt message"
        assert isinstance(mock_prompt.call_args[0][4], list)
        assert len(mock_prompt.call_args[0][4]) == 1
        assert mock_prompt.call_args[0][4][0].extended_properties['name'] == \
            'prompt field'
        assert mock_prompt.call_args[0][4][0].extended_properties['label'] == \
            'PromptLabel'

        assert isinstance(actual[3], PSCredential)
        assert actual[3].username == "username"
        assert actual[3].password == "password"
        assert mock_prompt_credential.call_count == 1
        assert isinstance(mock_prompt_credential.call_args[0][0],
                          RunspacePool)
        assert isinstance(mock_prompt_credential.call_args[0][1],
                          PowerShell)
        assert mock_prompt_credential.call_args[0][2] == \
            "PromptForCredential caption"
        assert mock_prompt_credential.call_args[0][3] == \
            "PromptForCredential message"
        assert mock_prompt_credential.call_args[0][4] == \
            "PromptForCredential user"
        assert mock_prompt_credential.call_args[0][5] == \
            "PromptForCredential target"
        assert mock_prompt_credential.call_args[0][6] == 3
        assert mock_prompt_credential.call_args[0][7] == 1

        assert actual[4] == 1
        assert mock_prompt_choice.call_count == 1
        assert isinstance(mock_prompt_choice.call_args[0][0], RunspacePool)
        assert isinstance(mock_prompt_choice.call_args[0][1], PowerShell)
        assert mock_prompt_choice.call_args[0][2] == "PromptForChoice caption"
        assert mock_prompt_choice.call_args[0][3] == "PromptForChoice message"
        assert isinstance(mock_prompt_choice.call_args[0][4], list)
        assert len(mock_prompt_choice.call_args[0][4]) == 2
        assert mock_prompt_choice.call_args[0][4][0].extended_properties[
            'label'] == "Prompt1 label"
        assert mock_prompt_choice.call_args[0][4][0].extended_properties[
            'helpMessage'] == "Prompt1 help"
        assert mock_prompt_choice.call_args[0][4][1].extended_properties[
            'label'] == "Prompt2 label"
        assert mock_prompt_choice.call_args[0][4][1].extended_properties[
            'helpMessage'] == "Prompt2 help"