C#

2 min readArticle

C# (C Sharp) is Microsoft's primary managed programming language, running on the .NET runtime. It's heavily used in enterprise Windows environments, Windows application development, ASP.NET web apps, and increasingly in cross-platform development via .NET Core/.NET 6+. Relevant for security because a lot of Windows malware, red team tooling, and enterprise apps are C#.

Security Relevance

  • Many red team C2 frameworks (Covenant, SharpC2) are C#
  • Active Directory attack tools: SharpHound, Rubeus, SharpView, Seatbelt
  • Windows post-exploitation tooling is mostly C#
  • .NET assemblies can be loaded in-memory (living off the land)
  • Understanding C# helps analyze .NET malware

Setup

bash
# Install .NET SDK (Linux/Mac)
# Download from dotnet.microsoft.com
dotnet --version

# Create new console project
dotnet new console -n MyProject
cd MyProject
dotnet run

Basics

csharp
using System;
using System.Net;
using System.Net.Sockets;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Hello, World!");
        
        // Variables
        string target = "192.168.1.1";
        int port = 443;
        bool isOpen = false;
        
        // Try-catch
        try {
            TcpClient client = new TcpClient(target, port);
            isOpen = true;
            client.Close();
        } catch (Exception e) {
            Console.WriteLine($"Port closed: {e.Message}");
        }
        
        Console.WriteLine($"Port {port} open: {isOpen}");
    }
}

Common Patterns in Security Tools

csharp
// Process execution
using System.Diagnostics;
Process.Start("cmd.exe", "/c whoami");

// Read registry
using Microsoft.Win32;
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\...");

// P/Invoke (calling Windows APIs directly)
[DllImport("kernel32.dll")]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, 
    uint flAllocationType, uint flProtect);

// LDAP queries for Active Directory
using System.DirectoryServices;
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=corp,DC=com");

Useful Namespaces

  • System.Net — networking
  • System.IO — file operations
  • System.Diagnostics — process management
  • System.Security.Cryptography — crypto
  • System.DirectoryServices — Active Directory
  • Microsoft.Win32 — Windows registry

In-Memory Execution (Red Team Concept)

C# assemblies can be loaded and executed in memory using Assembly.Load(), avoiding writing to disk — a common AV evasion technique used by offensive tools.

Key Tools Written in C#

  • Rubeus - Kerberos attacks
  • SharpHound - AD enumeration (BloodHound collector)
  • Seatbelt - Windows host enumeration
  • Covenant - C2 framework

See Also

  • cpp-programming-guide - C++ notes
  • powershell-scripting-guide - Another key Windows language
techzonesite.comUnlock Your IT Potential