Full Trust CLR Verification issue Exploiting Passing Reference Types by Reference

1. create a file called byValueTypeTest.cs and compile it using csc byValueTypeTest.csc

using System;
using System.Text;
namespace Owasp 
  {
    class byValueTypetest
     {
       public static void Main()
       {
           // this will compile:
           object objString = (object)"I'm a String";
           
           // this will not compile:
           // string objString = "I'm a String";
           // it will throw the error:
           
           /*
               byValueTypeTest.cs(14,4): error CS1502: The best overloaded method match for
               'Owasp.byValueTypetest.byRefObject(ref object)' has some invalid arguments
                byValueTypeTest.cs(14,20): error CS1503: Argument '1': cannot convert from 'ref
               string' to 'ref object'
           */

           // which is why we need to do it directly in IL
           // values before call
           Console.WriteLine("\nbefore: " + objString + "\n  type: " + objString.GetType());

           // this method will allocate a StringBuilder variable to objString
           byRefObject(ref objString);

           // values after call
           Console.WriteLine("\nafter: " + objString + "\n type: " + objString.GetType());
       }       

       public static void byRefObject(ref object oVar)
       {                   
           StringBuilder sb = new StringBuilder("I'm a StringBuilder");
           oVar = sb;
           //Console.WriteLine(oVar);
       }
   }
}

2. execute it just to see what it does:

before: I'm a String
type: System.String

after: I'm a StringBuilder
type: System.Text.StringBuilder

3. then ILDASM it

ildasm byValueTypeTest.exe /out:_byValtest.il

4. make this change in the IL code

// change from
        .locals init ( object V_0, object[] V_1)
// to
        .locals init ( string V_0, object[] V_1)

5. ILASM it

ilasm _byValTest.il

6. execute it, and the result will be

before: I'm a String
type: System.String`

after: I'm a StringBuilder
type: System.Text.StringBuilder

7. Open assembly in reflector to confirm that the IL manipulation was successfull

public static void Main()
{
     Console.WriteLine("\n\n staticInvokeTest\n\n");
     string text1 = "I'm a String";
     object[] objArray1 = new object[] { "\nbefore: ", text1, "\n  type: ", text1.GetType() } ;
     Console.WriteLine(string.Concat(objArray1));
     byValueTypetest.byRefObject(ref text1);
     objArray1 = new object[] { "\nafter: ", text1, "\n type: ", text1.GetType() } ;
     Console.WriteLine(string.Concat(objArray1));
}

8. compare with with the output

And you will see that we were able to change the type of text1 (using reflector’s variable name) from System.String to System.Text.StringBuilder