Advertisement
BaSs_HaXoR

.NET Reverse Engineering-1:CIL Programming

Jan 28th, 2017
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scilab 33.75 KB | None | 0 0
  1. [.NET REVERSE ENGINEERING - PART 1]
  2.  
  3.                                                                                             [.NET Reverse Engineering-1:CIL Programming]
  4. LINK: http://adf.ly/1iqyI3
  5. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  6. [Introduction]
  7.  
  8. The prime objective of this article is to confront with the .NET mother tongue language termed as Common Instruction Language (CIL) which laid down the foundation of .NET Reverse Engineering. Here, you will comprehend the distinction between CIL directive, attributes, opcodes and will come across numerous CIL tools that associate a significant role in code execution. The triggering point to writing this article is to provide a deep analysis and examination of CIL grammar.
  9.  
  10. The source code of any software or executable application, is intellectual property of a vendor company and not to be disclosed due to proprietary issues. Without the actual code, we have to rely on what is called the native code, so it is required to delve into CIL before moving ahead to code dissembling. Apart from that, we shall discuss some of the advance conceptions related to reverse engineering such as: round-tripping engineering, obfuscation and code disassembling which uses some advance tools such as IDAPro, Ollydbg, Hex Editor, Ilasm and Reflector in the forthcoming articles of this series.
  11.  
  12. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  13. [Abstract]
  14.  
  15. MSIL (Microsoft Intermediate Language) is an essential fragment of CLR and the code that is written and executed under CLR is referred to as “managed code”. The managed compiler translates that code (*.cs file) into CIL code, manifest and metadata. This process typically undergoes two compilation phases. The first compilation phase is performed by compiler in which source code is transformed to MSIL. The second compilation phase occurs at run time, when the MSIL code is compiled to native code. The .NET platform is considered language-independent because the process execution of a managed application is identical regardless of the source language. Finally CIL is full- fledged .NET programming language, with its own syntax and compiler.
  16.  
  17. The beauty of MSIL code is that it compiled once and executes anywhere by using JIT compiler which, compiles assemblies into native binary code that targets a specific platform. You can write an application and deploy that application to Windows, Linux, Mac and other platforms that support .NET run time.
  18.  
  19. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  20. [Prerequisite]
  21.  
  22. In order to execute and examine MSIL/CIL code, you have to configure your machine with the following tools;
  23.  
  24. .NET framework 3.5 or higher
  25. Either SharpDeveloper Studio or Xamarin Studio
  26. Visual Studio Command Prompt
  27. IL Disassembler (ildasm.exe)
  28. Reflector
  29. Understanding CIL
  30.  
  31. When you build a .NET assembly using your managed language of choice (C#, VB, F#, Perl, COBOL), the associate compiler translates your source code into Common Instruction Language. CIL is just an another structural .NET programming language, it possible to build .NET assemblies directly using CIL and CIL compiler (ILASM.EXE) that ships with .NET framework.
  32.  
  33. The more you understand the grammar of CIL, the better able you are to move into the arena of advanced .NET programming. The programmer having comprehensive knowledge of CIL, can perform the following tasks:
  34.  
  35. Disassembling an existing assembly, edit the CIL code, and recompile the updated code.
  36. CIL is the only .NET language that allows you to access each aspect of CTS and CLS.
  37. Building in-house dynamic assemblies using the System.Reflection.Emit namespace API.
  38. CIL does not simply define a general set of keywords such as public, private, new, get, set, this. Rather, the token set understood by the CIL compiler is sub-divided into three categories. Each category of CIL token is expressed using a particular syntax. The three categories are:
  39.  
  40. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  41. [CIL Directive]
  42.  
  43. Directives are represented syntactically using a single dot prefix (.class, .assembly). They are a set of CIL tokens that are used to describe the structure of a .NET assembly called CIL directives. They are used to inform the CIL compiler how to define the namespace, class and methods that will populate an assembly.
  44.  
  45. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  46. [CIL Attributes]
  47.  
  48. Sometimes CIL directives are not descriptive enough to fully express the definition of a given type. However, they can be further specified with various CIL attributes to qualify how a directive should be processed.
  49.  
  50. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  51. [CIL Opcodes]
  52.  
  53. The Opcodes (or operation code) provides the type of implementation logic once a .NET assembly, namespace and type has been defined in terms of CIL code.
  54.  
  55. Despite catering numerous advantages, CIL programming has some drawbacks as such maintaining of safe code. CIL source code is inherently unsafe and could lead to disaster.
  56.  
  57. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  58. [First CIL Program]
  59.  
  60. We need a code editor in order to author our First CIL program, for instance Notepad or Wordpad but it is good to write code by using other full-fledged open source .NET IDE such as SharpDevelop or Xamarin Studio. They are integrated with existing .NET FCL an automatic directive recognition feature. No matter which IDE or editor we are using, the important point is to save that CIL code file with *.il extension.
  61.  
  62. The following code illustrates the first hello world program using CIL programming language. Open notepad, and place the following code, then save this file as Test.il
  63.  
  64. .assembly extern mscorlib {}<b></b>
  65. <pre>.assembly FirstApp
  66.  {
  67.  
  68.  }
  69.  
  70.  .namespace FirstApp
  71.  {
  72.      .class private auto ansi beforefieldinit Test
  73.      {
  74.          .method public hidebysig static void Main(string[] argd) cil managed
  75.          {
  76.               .entrypoint
  77.               .maxstack    1
  78.               ldstr        "Welcome to CIL programming world"
  79.               call         void [mscorlib] System.Console::WriteLine(string)
  80.               ret
  81.          }
  82.      }
  83.  }
  84. File:- Test.il
  85.  
  86. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  87. [CIL code Compilation]
  88.  
  89. After finish coding, save this file as Test.il and compile it using the .NET framework shipped tool ILASM.exe as the following command:
  90.  
  91. ILASM /exe /debug Test.il
  92.  
  93. Here the exe option indicates that the target is a console base application. The debug option asks the compiler to generate a debug file (test.pdb) for the application which is a useful viewing source code in a debugger or disassembler.
  94.  
  95. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  96. After successfully compiling the Test.il file, Test.exe is created in the project directory which is finally executable and yields our desired output as the following:
  97.  
  98. When building or modifying assemblies using CIL code, it is always advisable to verify that the compiled binary image is a well-formed .NET image using the peverify.exe utility as shown below:
  99.  
  100. Here in the aforementioned figure, it is proved that the all opcodes within the test.exe binary are valid CIL codes. While the CIL compiler has numerous command-line options as the following:
  101.  
  102. Flags   Description
  103. /dll    It produce a *.dll file as an output.
  104. /exe    This is the default option and produce an *.exe file as an output.
  105. /debug  Includes debug information.
  106. /output It specifies the output file name and extension.
  107. /snk    It compile the *.il file with a strong name.
  108. In the aforementioned CIL code source file Test.il, the first declaration is an external reference to the mscorlib library. The mscorlib.dll contains the core of the .NET Framework FCL which includes the System.Console class. The second assembly directive is simple name of assembly, which is FirstApp and third directive defines the namespace.
  109.  
  110. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  111. .assembly extern mscorlib {}
  112. .assembly FirstApp
  113. {
  114.  
  115. }
  116. // class namespace
  117. .namespace FirstApp
  118. { ……}
  119. The following lines define a class and a method within the class. The class directive introduces a public class named Test which implicitly inherits the System.Object class. The method directive defines the public Main as a member method. The cil keyword indicates that the method contains Intermediate code.
  120.  
  121. .class private auto ansi beforefieldinit Test
  122.     {
  123.         .method public hidebysig static void Main(string[] argd) cil managed
  124.         {}
  125.     }
  126. The Main method commences with two directives. The .entrypoint directive, designates Main as the entry point of the application. The .maxstack set the size of the memory stack to 1 slot. The ldstr directive loads the string into memory. The call directive consumes one item from the memory and displays them using the WriteLine method. Finally ret directive indicates return or exit from the method.
  127.  
  128. .entrypoint
  129. .maxstack    1
  130. ldstr     "Welcome to CIL programming world"
  131. call      void [mscorlib] System.Console::WriteLine(string)
  132. ret
  133.  
  134.  
  135. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  136. [CIL Code Post-mortem Analysis]
  137.  
  138. CIL is much easier to understand and interpret when compared to assembly language. The contents of source code in CIL programming are case sensitive like C# in statements and, not terminated with a semicolon. Apart from that, the most significant part of CIL application is dotted prefixed directives and actual executable source code. There are several categories of directives proposed by .NET CLR such as assembly, class and method.
  139.  
  140. In order understand the CIL code directive, we shall write a console application using the Xamarin Studio that produces the addition of two integer types. Although we can develop such an application using other code editors but Xamarin studio provides more functionality and facilities in terms of writing crucial IL coding rather than other editors.
  141.  
  142. So first open the Xamarin studio and select New
  143. Solution from File menu. Then choose IL type Console Project from project template as shown below:
  144.  
  145. Thereafter, rename the main.il to MathFun.il and place the following code in the MathFun.il file. We shall discuss each segments of the *.il file in the next section.
  146.  
  147. .assembly extern mscorlib
  148. {
  149.   .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
  150.   .ver 2:0:0:0
  151. }
  152. .assembly MathFun
  153. {
  154.   .ver 1:0:0:0
  155.   .locale "en.US"
  156. }
  157. .module MathFun.exe
  158.  
  159. .imagebase 0x00400000
  160. .file alignment 0x00000200
  161. .stackreserve 0x00100000
  162. .subsystem 0x0003
  163. .corflags 0x00000003
  164.  
  165. // =============== CLASS MEMBERS DECLARATION ===================
  166.  
  167. .class public auto ansi beforefieldinit MathFun
  168.        extends [mscorlib]System.Object
  169. {
  170.   .field private string '<Name>k__BackingField'
  171.   .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  172.   .method public hidebysig specialname rtspecialname
  173.           instance void  .ctor(string name) cil managed
  174.   {
  175.     // Code size       18 (0x12)
  176.     .maxstack  8
  177.     IL_0000:  ldarg.0
  178.     IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
  179.     IL_0006:  nop
  180.     IL_0007:  nop
  181.     IL_0008:  ldarg.0
  182.     IL_0009:  ldarg.1
  183.     IL_000a:  call       instance void MathFun::set_Name(string)
  184.     IL_000f:  nop
  185.     IL_0010:  nop
  186.     IL_0011:  ret
  187.   } // end of method Test::.ctor
  188.  
  189.   .method public hidebysig specialname instance string get_Name() cil managed
  190.   {
  191.     .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  192.     // Code size       11 (0xb)
  193.     .maxstack  1
  194.     .locals init (string V_0)
  195.     IL_0000:  ldarg.0
  196.     IL_0001:  ldfld      string MathFun::'<Name>k__BackingField'
  197.     IL_0006:  stloc.0
  198.     IL_0007:  br.s       IL_0009
  199.  
  200.     IL_0009:  ldloc.0
  201.     IL_000a:  ret
  202.   } // end of method Test::get_Name
  203.  
  204.   .method public hidebysig specialname instance void set_Name(string 'value') cil managed
  205.   {
  206.     .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  207.     // Code size       8 (0x8)
  208.     .maxstack  8
  209.     IL_0000:  ldarg.0
  210.     IL_0001:  ldarg.1
  211.     IL_0002:  stfld      string MathFun::'<Name>k__BackingField'
  212.     IL_0007:  ret
  213.   } // end of method Test::set_Name
  214.  
  215.   .method public hidebysig instance string Display() cil managed
  216.   {
  217.     // Code size       22 (0x16)
  218.     .maxstack  2
  219.     .locals init ([0] string CS$1$0000)
  220.     IL_0000:  nop
  221.     IL_0001:  ldstr      "Hello "
  222.     IL_0006:  ldarg.0
  223.     IL_0007:  call       instance string MathFun::get_Name()
  224.     IL_000c:  call       string [mscorlib]System.String::Concat(string,string)
  225.     IL_0011:  stloc.0
  226.     IL_0012:  br.s       IL_0014
  227.  
  228.     IL_0014:  ldloc.0
  229.     IL_0015:  ret
  230.   } // end of method Test::Display
  231.  
  232.   .method public hidebysig instance int32 Addition(int32 x, int32 y) cil managed
  233.   {
  234.     // Code size       9 (0x9)
  235.     .maxstack  2
  236.     .locals init ([0] int32 CS$1$0000)
  237.     IL_0000:  nop
  238.     IL_0001:  ldarg.1
  239.     IL_0002:  ldarg.2
  240.     IL_0003:  add
  241.     IL_0004:  stloc.0
  242.     IL_0005:  br.s       IL_0007
  243.  
  244.     IL_0007:  ldloc.0
  245.     IL_0008:  ret
  246.   } // end of method Test::Addition
  247.  
  248.   .property instance string Name()
  249.   {
  250.     .get instance string MathFun::get_Name()
  251.     .set instance void MathFun::set_Name(string)
  252.   } // end of property Test::Name
  253. } // end of class MathOperation.Test
  254.  
  255. .class private auto ansi beforefieldinit MathFun extends [mscorlib]System.Object
  256. {
  257.   .method private hidebysig static void  Main(string[] args) cil managed
  258.   {
  259.     .entrypoint
  260.     // Code size       57 (0x39)
  261.     .maxstack  4
  262.     .locals init ([0] class MathFun obj)
  263.     IL_0000:  nop
  264.     IL_0001:  ldstr      "Ajay"
  265.     IL_0006:  newobj     instance void MathFun::.ctor(string)
  266.     IL_000b:  stloc.0
  267.     IL_000c:  ldloc.0
  268.     IL_000d:  callvirt   instance string MathFun::Display()
  269.     IL_0012:  call       void [mscorlib]System.Console::WriteLine(string)
  270.     IL_0017:  nop
  271.     IL_0018:  ldstr      "Addition is: {0}"
  272.     IL_001d:  ldloc.0
  273.     IL_001e:  ldc.i4.s   15
  274.     IL_0020:  ldc.i4.s   35
  275.     IL_0022:  callvirt   instance int32 MathFun::Addition(int32,int32)
  276.     IL_0027:  box        [mscorlib]System.Int32
  277.     IL_002c:  call        void [mscorlib]System.Console::WriteLine(string,object)
  278.     IL_0031:  nop
  279.     IL_0032:  call       valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
  280.     IL_0037:  pop
  281.     IL_0038:  ret
  282.   }
  283. }
  284. MathFun.il
  285.  
  286. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  287. Now build this program using F8. After successful compilation, the final executable MathFun.exe file is created in the project Bin/Debug folder of the solution directory.
  288. [Assembly Directives]
  289.  
  290. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  291. The assembly directive contains information that the compiler produces to the manifest, which is metadata pertaining to the overall assembly. This section lists common assembly directives as following;
  292.  
  293. .assembly extern
  294.  
  295. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  296. This directive represents an external assembly. The public types and methods of the referenced assembly are available to the current assembly. Here, is the syntax as:
  297.  
  298. .assembly extern name as alaisname { }
  299.  
  300. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  301. We implement such construct in the MathFun.il file by referencing the mscorlib.dll as following:
  302.  
  303. .assembly extern mscorlib
  304. {
  305. .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
  306. .ver 2:0:0:0
  307. }
  308.  
  309. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  310. Because of the importance of mscorlib.dll, the ILASM compiler automatically includes an external assembly reference to that library.
  311.  
  312. .assembly
  313.  
  314. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  315. It defines the simple name of the assembly. Assembly can be defined by specifying the friendly name of the binary;
  316.  
  317. .assembly CILType { }
  318.  
  319. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  320. There are some of the sub-directives available in the assembly block as:
  321.  
  322. .ver
  323. .locale
  324. .publickey
  325. By taking the reference of MathFun.il file, we are updating the assembly definition to include a version number of 1.0.0.0 using .ver directive and culture information using .locale; such construct would be as the following:
  326.  
  327. .assembly MathFun
  328. {
  329. .ver 1:0:0:0
  330. .locale “en.US”
  331. }
  332.  
  333. .module
  334.  
  335. The .module directive ensures the final executable extension of the files such as *.exe;
  336.  
  337. .module MathFun.exe
  338.  
  339. .imagebase
  340.  
  341. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  342. The .imagebase directive sets the base address where the application is loaded. The default is 0x00400000.
  343.  
  344. .imagebase 0x00400000
  345.  
  346. .file
  347.  
  348. The .file directive adds a file to the manifest of the assembly. This is useful for associating helper documents with an assembly.
  349.  
  350. .file alignment 0x00000200
  351.  
  352. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  353. The nometadata is the primary option and stipulates that the file is unmanaged.
  354.  
  355. .stackreserve
  356.  
  357. The .stackreserve directive configures the stack size to 0x00100000 which is default.
  358.  
  359. .stackreserve 0x00100000
  360.  
  361. .subsystem
  362.  
  363. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  364. The .subsystem directive indicates the subsystem used by the application, such as console or GUI subsystem. Here the syntax as shown below:
  365.  
  366. .subsystem number
  367.  
  368. In the aforementioned example, we are constructing a console application. So mention 3 which are for console application and 2 for GUI applications.
  369.  
  370. .subsystem
  371. 0x0003
  372.  
  373. .corflags
  374.  
  375. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  376. The .corflags directive sets the runtime flag in the CLI header which stipulates an IL only assembly. The default value is 1 of the corflags.
  377.  
  378. .corflags 0x00000003 (As reference to MathFun.il)
  379.  
  380. .maxstack
  381.  
  382. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  383. The .maxstack directive establishes the maximum number of variables that may be pushed onto the stack during execution.
  384.  
  385. .maxstack 8 (default value)
  386.  
  387. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  388. [Class Directives]
  389.  
  390. This part describes the important class directives. It has contains the following significant directive:
  391.  
  392. .class
  393.  
  394. The .class directive defines a new reference, value or interface type. Here, the syntax is shown below:
  395.  
  396. attributes classname extends basetype implements interface
  397.  
  398. As per the aforementioned MathTest.il file, we implement the class MathOperation using .class directive in this way as the following:
  399.  
  400. .class public auto ansi beforefieldinit MathFun
  401. extends [mscorlib]System.Object
  402.  
  403. << + #################################### --------------------------------------------------------------- + | + || + | + --------------------------------------------------------------- #################################### + >>
  404. The class directive is also adorned with variety of attributes. Here is the short list of the most common:
  405.  
  406. abstract: indicates class that can’t be instantiated.
  407. ansi and Unicode : determine the format of string.
  408. auto : CLR controlled the Memory layout of fields by this.
  409. beforefieldinit: the type should be initialized before a static class is accessed.
  410. private and public : set the visibility outside the class
  411. The Test class also implements a constructor specification as Test() in order to initialize the field’s data as in C#.net version.
  412.  
  413. public Test(string name)
  414.         {
  415.             this.Name = name;
  416.         }
  417. So its IL code would be as the following:
  418.  
  419. .field private string '<Name>k__BackingField'
  420.   .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  421.   .method public hidebysig specialname rtspecialname
  422.           instance void  .ctor(string name) cil managed
  423.   {
  424.     // Code size       18 (0x12)
  425.     .maxstack  8
  426.     IL_0000:  ldarg.0
  427.     IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
  428.     IL_0006:  nop
  429.     IL_0007:  nop
  430.     IL_0008:  ldarg.0
  431.     IL_0009:  ldarg.1
  432.     IL_000a:  call       instance void MathFun::set_Name(string)
  433.     IL_000f:  nop
  434.     IL_0010:  nop
  435.     IL_0011:  ret
  436.   }
  437. .property
  438.  
  439. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  440. The property directive adds a property member to a class. Here, the syntax as shown below;
  441.  
  442. .property attributes return propertyname parametrs default { body }
  443.  
  444. If we define a property in C# code as the following:
  445.  
  446. public String Name
  447.         {
  448.             get;
  449.             set;
  450.         }
  451.  
  452. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  453. Then its corresponding MSIL code counterpart for Get and Set property would be as the following:
  454.  
  455.   .method public hidebysig specialname instance string
  456.           get_Name() cil managed
  457.   {
  458.     .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  459.     // Code size       11 (0xb)
  460.     .maxstack  1
  461.     .locals init (string V_0)
  462.     IL_0000:  ldarg.0
  463.     IL_0001:  ldfld      string MathFun::'<Name>k__BackingField'
  464.     IL_0006:  stloc.0
  465.     IL_0007:  br.s       IL_0009
  466.  
  467.     IL_0009:  ldloc.0
  468.     IL_000a:  ret
  469.   } // end of method Test::get_Name
  470.  
  471.   .method public hidebysig specialname instance void
  472.           set_Name(string 'value') cil managed
  473.   {
  474.     .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  475.     // Code size       8 (0x8)
  476.     .maxstack  8
  477.     IL_0000:  ldarg.0
  478.     IL_0001:  ldarg.1
  479.     IL_0002:  stfld      string MathFun::'<Name>k__BackingField'
  480.     IL_0007:  ret
  481.   }
  482. .property instance string Name()
  483.   {
  484.     .get instance string MathFun::get_Name()
  485.     .set instance void MathFun::set_Name(string)
  486.   }
  487. .method
  488.  
  489. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  490. This directive defines the method in a class. Here is the syntax as:
  491.  
  492. .method attributes callingconv return methodname arguments { body }
  493.  
  494. We are defining two methods Display() and Addition(). First one would show “Hello” text on the screen and second Addition() method would compute the sum of two integer type supplied variables in the method as following:
  495.  
  496. public String Display()
  497.         {
  498.             return "Hello " + Name;
  499.         }
  500. public int Addition(int x, int y)
  501.         {
  502.             return (x+y);
  503.         }
  504.  
  505. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  506. The resemble IL code for methods as:
  507.  
  508. .method public hidebysig instance string
  509.           Display() cil managed
  510.   {
  511.     // Code size       22 (0x16)
  512.     .maxstack  2
  513.     .locals init ([0] string CS$1$0000)
  514.     IL_0000:  nop
  515.     IL_0001:  ldstr      "Hello "
  516.     IL_0006:  ldarg.0
  517.     IL_0007:  call       instance string MathFun::get_Name()
  518.     IL_000c:  call       string [mscorlib]System.String::Concat(string,
  519.                                                                 string)
  520.     IL_0011:  stloc.0
  521.     IL_0012:  br.s       IL_0014
  522.  
  523.     IL_0014:  ldloc.0
  524.     IL_0015:  ret
  525.   }
  526.  
  527. << + #################################### --------------------------------------------------- + | + || + | + --------------------------------------------------- #################################### + >>
  528. The method attribute has some additional attributes as:
  529.  
  530. hidebysig: hides the base class interface of this method.
  531. Specialname: this is used for special methods such get_Property and set_Property.
  532. Rtspecialname: this indicates the special method referred as constructor.
  533. Cil or il: the method contains the MSIL code.
  534. Native: the method contains platform-specific code.
  535. Managed: indicates the implementation is managed.
  536. .field
  537.  
  538. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  539. The field directive indicates a new defined field which is state information for a class. Here, the syntax as shown below:
  540.  
  541. .field attributes type fieldname
  542.  
  543. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  544. In the C# code, we can define an integer type field as the following:
  545.  
  546. .field private initonly int32 x
  547. .field private initonly int32 y
  548. Main() Method Directives
  549.  
  550. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  551. The method block can contain both directives and the implementation code (CIL).
  552.  
  553. .entrtpoint
  554.  
  555. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  556. This directive designates a method as an entry point of the application. This directive can appear anywhere in the program.
  557.  
  558. .locals
  559.  
  560. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  561. The .locals directive declares the local variables that are available by name. Here, we are defining two integer types local variable in the MathFun.il as:
  562.  
  563. .locals init ([0] int32 x,[1] int32 y)
  564.  
  565. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  566. And we are assigning a string slot by also passing a string data into the class constructor as:
  567.  
  568. .locals init ([0] class MathFun obj)
  569.  
  570. << + #################################### --------------------------------------------------- + | + || + | + --------------------------------------------------- #################################### + >>
  571. [MSIL Instructions]
  572. Each MSIL instruction assigned an opcode, which is commonly 1 or 2 bytes. Opcodes which caters an alternative means of identifying MSIL instructions, are used primarily when producing code dynamically at run time.
  573.  
  574.     IL_0000:  nop
  575.     IL_0001:  ldstr      "Ajay"
  576.     IL_0006:  newobj     instance void MathFun::.ctor(string)
  577.     IL_000b:  stloc.0
  578.     IL_000c:  ldloc.0
  579.     IL_000d:  callvirt   instance string MathFun::Display()
  580.     IL_0012:  call       void [mscorlib]System.Console::WriteLine(string)
  581.     IL_0017:  nop
  582.     IL_0018:  ldstr      "Addition is: {0}"
  583.     IL_001d:  ldloc.0
  584.     IL_001e:  ldc.i4.s   15
  585.     IL_0020:  ldc.i4.s   35
  586.     IL_0022:  callvirt   instance int32 MathFun::Addition(int32,
  587.                                                                      int32)
  588.     IL_0027:  box        [mscorlib]System.Int32
  589.     IL_002c:  call       void [mscorlib]System.Console::WriteLine(string,
  590.                                                                   object)
  591.     IL_0031:  nop
  592.     IL_0032:  call       valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
  593.     IL_0037:  pop
  594.     IL_0038:  ret
  595.  
  596.  
  597. << + #################################### --------------------------------------------------- + | + || + | + --------------------------------------------------- #################################### + >>
  598. [Synopsis]
  599. This article touched briefly on the most important features of the common language runtime and ILAsm. You now know how the runtime functions, how a program in ILAsm is written,compile using either ilasm or Xamarin studio, and how to define the basic components (classes, fields, property and methods).We will pick opcode specification in depth along with the remaining crucial segments of the MSIL grammar in the next articles of this series.
  600.  
  601. << + #################################### --------------------------------------------------- + | + || + | + --------------------------------------------------- #################################### + >>
  602. NEXT: .NET REVERSE ENGINEERING –PART 2
  603.  
  604. AUTHOR: Ajay Yadav
  605. Ajay Yadav is an author, Cyber Security Specialist, SME, Software Engineer, and System Programmer with more than eight years of work experience. He earned a Master and Bachelor Degree in Computer Science, along with abundant premier professional certifications. For several years, he has been researching Reverse Engineering, Secure Source Coding, Advance Software Debugging, Vulnerability Assessment, System Programming and Exploit Development. He is a regular contributor to programming journal and assistance developer community with blogs, research articles, tutorials, training material and books on sophisticated technology. His spare time activity includes tourism, movies and meditation. He can be reached at om.ajay007[at]gmail[dot]com
  606. CSSP Certification: Who, How, and Why
  607.  
  608. About InfoSec
  609. InfoSec Institute is the best source for high quality information security training. We have been training Information Security and IT Professionals since 1998 with a diverse lineup of relevant training courses. In the past 16 years, over 50,000 individuals have trusted InfoSec Institute for their professional development needs!
  610.  
  611. Stay up to date with InfoSec Institute and Intense School - at info@infosecinstitute.com
  612. Follow @infosecedu
  613. © INFOSEC RESOURCES 2017
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement