Ejemplo n.º 1
0
        //From Seatbelt
        public static Dictionary <string, string> GetBasicOSInfo()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                string ProductName = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
                string EditionID   = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "EditionID");
                string ReleaseId   = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId");
                string BuildBranch = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "BuildBranch");
                string CurrentMajorVersionNumber = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentMajorVersionNumber");
                string CurrentVersion            = MyUtils.GetRegValue("HKLM", "Software\\Microsoft\\Windows NT\\CurrentVersion", "CurrentVersion");

                bool isHighIntegrity = MyUtils.IsHighIntegrity();

                CultureInfo   ci                = CultureInfo.InstalledUICulture;
                string        systemLang        = ci.Name;
                var           timeZone          = TimeZoneInfo.Local;
                InputLanguage myCurrentLanguage = InputLanguage.CurrentInputLanguage;

                string arch           = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
                string userName       = Environment.GetEnvironmentVariable("USERNAME");
                string ProcessorCount = Environment.ProcessorCount.ToString();
                bool   isVM           = IsVirtualMachine();

                DateTime now = DateTime.Now;

                String             strHostName = Dns.GetHostName();
                IPGlobalProperties properties  = IPGlobalProperties.GetIPGlobalProperties();
                string             dnsDomain   = properties.DomainName;

                const string query      = "SELECT HotFixID FROM Win32_QuickFixEngineering";
                var          search     = new ManagementObjectSearcher(query);
                var          collection = search.Get();
                string       hotfixes   = "";
                foreach (ManagementObject quickFix in collection)
                {
                    hotfixes += quickFix["HotFixID"].ToString() + ", ";
                }

                results.Add("Hostname", strHostName);
                if (dnsDomain.Length > 1)
                {
                    results.Add("Domain Name", dnsDomain);
                }
                results.Add("ProductName", ProductName);
                results.Add("EditionID", EditionID);
                results.Add("ReleaseId", ReleaseId);
                results.Add("BuildBranch", BuildBranch);
                results.Add("CurrentMajorVersionNumber", CurrentMajorVersionNumber);
                results.Add("CurrentVersion", CurrentVersion);
                results.Add("Architecture", arch);
                results.Add("ProcessorCount", ProcessorCount);
                results.Add("SystemLang", systemLang);
                results.Add("KeyboardLang", myCurrentLanguage.Culture.EnglishName);
                results.Add("TimeZone", timeZone.DisplayName);
                results.Add("IsVirtualMachine", isVM.ToString());
                results.Add("Current Time", now.ToString());
                results.Add("HighIntegrity", isHighIntegrity.ToString());
                results.Add("PartOfDomain", Program.partofdomain.ToString());
                results.Add("Hotfixes", hotfixes);
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Ejemplo n.º 2
0
        public static List <Dictionary <string, string> > GetNetCardInfo()
        {
            List <Dictionary <string, string> >            results  = new List <Dictionary <string, string> >();
            Dictionary <int, Dictionary <string, string> > adapters = new Dictionary <int, Dictionary <string, string> >();

            try
            {
                foreach (NetworkInterface netElement in NetworkInterface.GetAllNetworkInterfaces())
                {
                    Dictionary <string, string> card = new Dictionary <string, string>()
                    {
                        { "Index", netElement.GetIPProperties().GetIPv4Properties().Index.ToString() },
                        { "Name", netElement.Name },
                        { "PysicalAddr", "" },
                        { "DNSs", String.Join(", ", netElement.GetIPProperties().DnsAddresses) },
                        { "Gateways", "" },
                        { "IPs", "" },
                        { "Netmasks", "" },
                        { "arp", "" }
                    };
                    card["PysicalAddrIni"] = netElement.GetPhysicalAddress().ToString();
                    for (int i = 0; i < card["PysicalAddrIni"].Length; i += 2)
                    {
                        card["PysicalAddr"] += card["PysicalAddrIni"].Substring(i, 2) + ":";
                    }

                    foreach (GatewayIPAddressInformation address in netElement.GetIPProperties().GatewayAddresses.Reverse()) //Reverse so first IPv4
                    {
                        card["Gateways"] += address.Address + ", ";
                    }

                    foreach (UnicastIPAddressInformation ip in netElement.GetIPProperties().UnicastAddresses.Reverse())
                    { //Reverse so first IPv4
                        card["IPs"]      += ip.Address.ToString() + ", ";
                        card["Netmasks"] += ip.IPv4Mask.ToString() + ", ";
                    }

                    //Delete last separator
                    if (card["PysicalAddr"].Length > 0)
                    {
                        card["PysicalAddr"] = card["PysicalAddr"].Remove(card["PysicalAddr"].Length - 1);
                    }

                    if (card["Gateways"].Length > 0)
                    {
                        card["Gateways"] = card["Gateways"].Remove(card["Gateways"].Length - 2);
                    }

                    if (card["IPs"].Length > 0)
                    {
                        card["IPs"] = card["IPs"].Remove(card["IPs"].Length - 2);
                    }

                    if (card["Netmasks"].Length > 0)
                    {
                        card["Netmasks"] = card["Netmasks"].Remove(card["Netmasks"].Length - 2);
                    }

                    adapters[netElement.GetIPProperties().GetIPv4Properties().Index] = card;
                }
                //return results;

                // GET ARP values

                int bytesNeeded = 0;

                int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);

                // call the function, expecting an insufficient buffer.
                if (result != ERROR_INSUFFICIENT_BUFFER)
                {
                    Console.WriteLine("  [X] Exception: {0}", result);
                }

                IntPtr buffer = IntPtr.Zero;

                // allocate sufficient memory for the result structure
                buffer = Marshal.AllocCoTaskMem(bytesNeeded);

                result = GetIpNetTable(buffer, ref bytesNeeded, false);

                if (result != 0)
                {
                    Console.WriteLine("  [X] Exception allocating buffer: {0}", result);
                }

                // now we have the buffer, we have to marshal it. We can read the first 4 bytes to get the length of the buffer
                int entries = Marshal.ReadInt32(buffer);

                // increment the memory pointer by the size of the int
                IntPtr currentBuffer = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(int)));

                // allocate a list of entries
                List <MIB_IPNETROW> arpEntries = new List <MIB_IPNETROW>();

                // cycle through the entries
                for (int index = 0; index < entries; index++)
                {
                    arpEntries.Add((MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)));
                }

                // sort the list by interface index
                List <MIB_IPNETROW> sortedARPEntries = arpEntries.OrderBy(o => o.dwIndex).ToList();
                int currentIndexAdaper = -1;

                foreach (MIB_IPNETROW arpEntry in sortedARPEntries)
                {
                    int indexAdapter = arpEntry.dwIndex;
                    if (!adapters.ContainsKey(indexAdapter))
                    {
                        Console.WriteLine("Error: No interface found with Index " + arpEntry.dwIndex.ToString());
                        continue;
                    }
                    currentIndexAdaper = indexAdapter;

                    IPAddress    ipAddr    = new IPAddress(BitConverter.GetBytes(arpEntry.dwAddr));
                    byte[]       macBytes  = new byte[] { arpEntry.mac0, arpEntry.mac1, arpEntry.mac2, arpEntry.mac3, arpEntry.mac4, arpEntry.mac5 };
                    string       physAddr  = BitConverter.ToString(macBytes);
                    ArpEntryType entryType = (ArpEntryType)arpEntry.dwType;
                    adapters[arpEntry.dwIndex]["arp"] += String.Format("          {0,-22}{1,-22}{2}\n", ipAddr, physAddr, entryType);
                }

                FreeMibTable(buffer);
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            results = adapters.Values.ToList();
            return(results);
        }
        public static List <Dictionary <string, string> > GetRecycleBin()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                // lists recently deleted files (needs to be run from a user context!)

                // Reference: https://stackoverflow.com/questions/18071412/list-filenames-in-the-recyclebin-with-c-sharp-without-using-any-external-files
                int lastDays = 30;

                var startTime = System.DateTime.Now.AddDays(-lastDays);

                // Shell COM object GUID
                Type   shell    = Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000"));
                Object shellObj = Activator.CreateInstance(shell);

                // namespace for recycle bin == 10 - https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494(v=vs.85).aspx
                Object recycle = shellObj.GetType().InvokeMember("Namespace", BindingFlags.InvokeMethod, null, shellObj, new object[] { 10 });
                // grab all the deletes items
                Object items = recycle.GetType().InvokeMember("Items", BindingFlags.InvokeMethod, null, recycle, null);
                // grab the number of deleted items
                Object count        = items.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, items, null);
                int    deletedCount = Int32.Parse(count.ToString());

                // iterate through each item
                for (int i = 0; i < deletedCount; i++)
                {
                    // grab the specific deleted item
                    Object   item         = items.GetType().InvokeMember("Item", BindingFlags.InvokeMethod, null, items, new object[] { i });
                    Object   DateDeleted  = item.GetType().InvokeMember("ExtendedProperty", BindingFlags.InvokeMethod, null, item, new object[] { "System.Recycle.DateDeleted" });
                    DateTime modifiedDate = DateTime.Parse(DateDeleted.ToString());
                    if (modifiedDate > startTime)
                    {
                        // additional extended properties from https://blogs.msdn.microsoft.com/oldnewthing/20140421-00/?p=1183
                        Object Name        = item.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, item, null);
                        Object Path        = item.GetType().InvokeMember("Path", BindingFlags.GetProperty, null, item, null);
                        Object Size        = item.GetType().InvokeMember("Size", BindingFlags.GetProperty, null, item, null);
                        Object DeletedFrom = item.GetType().InvokeMember("ExtendedProperty", BindingFlags.InvokeMethod, null, item, new object[] { "System.Recycle.DeletedFrom" });
                        results.Add(new Dictionary <string, string>()
                        {
                            { "Name", String.Format("{0}", Name) },
                            { "Path", String.Format("{0}", Path) },
                            { "Size", String.Format("{0}", Size) },
                            { "Deleted from", String.Format("{0}", DeletedFrom) },
                            { "Date Deleted", String.Format("{0}", DateDeleted) }
                        });
                    }
                    Marshal.ReleaseComObject(item);
                    item = null;
                }
                Marshal.ReleaseComObject(recycle);
                recycle = null;
                Marshal.ReleaseComObject(shellObj);
                shellObj = null;
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint("Error: " + ex);
            }
            return(results);
        }
Ejemplo n.º 4
0
        public static List <List <string> > GetNetConnections()
        {
            List <List <string> > results = new List <List <string> >();

            try
            {
                var props = IPGlobalProperties.GetIPGlobalProperties();
                results.Add(new List <string>()
                {
                    "Proto", "Local Address", "Foreing Address", "State"
                });

                //foreach (var conn in props.GetActiveTcpConnections())
                //    results.Add(new List<string>() { "TCP", conn.LocalEndPoint.ToString(), conn.RemoteEndPoint.ToString(), conn.State.ToString() });

                foreach (var listener in props.GetActiveTcpListeners())
                {
                    bool repeated = false;
                    foreach (List <string> inside_entry in results)
                    {
                        if (inside_entry.SequenceEqual(new List <string>()
                        {
                            "TCP", listener.ToString(), "", "Listening"
                        }))
                        {
                            repeated = true;
                        }
                    }
                    if (!repeated)
                    {
                        results.Add(new List <string>()
                        {
                            "TCP", listener.ToString(), "", "Listening"
                        });
                    }
                }

                foreach (var listener in props.GetActiveUdpListeners())
                {
                    bool repeated = false;
                    foreach (List <string> inside_entry in results)
                    {
                        if (inside_entry.SequenceEqual(new List <string>()
                        {
                            "UDP", listener.ToString(), "", "Listening"
                        }))
                        {
                            repeated = true;
                        }
                    }
                    if (!repeated)
                    {
                        results.Add(new List <string>()
                        {
                            "UDP", listener.ToString(), "", "Listening"
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }

            return(results);
        }
Ejemplo n.º 5
0
        public static List <Dictionary <string, string> > GetFirewallRules()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                //Filtrado por DENY como Seatbelt??
                // GUID for HNetCfg.FwPolicy2 COM object
                Type   firewall    = Type.GetTypeFromCLSID(new Guid("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD"));
                Object firewallObj = Activator.CreateInstance(firewall);

                // now grab all the rules
                Object rules = firewallObj.GetType().InvokeMember("Rules", BindingFlags.GetProperty, null, firewallObj, null);

                // manually get the enumerator() method
                System.Collections.IEnumerator enumerator = (System.Collections.IEnumerator)rules.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, rules, null);

                // move to the first item
                enumerator.MoveNext();
                Object currentItem = enumerator.Current;

                while (currentItem != null)
                {
                    // only display enabled rules
                    Object Enabled = currentItem.GetType().InvokeMember("Enabled", BindingFlags.GetProperty, null, currentItem, null);
                    if (Enabled.ToString() == "True")
                    {
                        Object Action = currentItem.GetType().InvokeMember("Action", BindingFlags.GetProperty, null, currentItem, null);
                        if (Action.ToString() == "0") //Only DENY rules
                        {
                            // extract all of our fields
                            Object Name            = currentItem.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, currentItem, null);
                            Object Description     = currentItem.GetType().InvokeMember("Description", BindingFlags.GetProperty, null, currentItem, null);
                            Object Protocol        = currentItem.GetType().InvokeMember("Protocol", BindingFlags.GetProperty, null, currentItem, null);
                            Object ApplicationName = currentItem.GetType().InvokeMember("ApplicationName", BindingFlags.GetProperty, null, currentItem, null);
                            Object LocalAddresses  = currentItem.GetType().InvokeMember("LocalAddresses", BindingFlags.GetProperty, null, currentItem, null);
                            Object LocalPorts      = currentItem.GetType().InvokeMember("LocalPorts", BindingFlags.GetProperty, null, currentItem, null);
                            Object RemoteAddresses = currentItem.GetType().InvokeMember("RemoteAddresses", BindingFlags.GetProperty, null, currentItem, null);
                            Object RemotePorts     = currentItem.GetType().InvokeMember("RemotePorts", BindingFlags.GetProperty, null, currentItem, null);
                            Object Direction       = currentItem.GetType().InvokeMember("Direction", BindingFlags.GetProperty, null, currentItem, null);
                            Object Profiles        = currentItem.GetType().InvokeMember("Profiles", BindingFlags.GetProperty, null, currentItem, null);

                            string ruleAction = "ALLOW";
                            if (Action.ToString() != "1")
                            {
                                ruleAction = "DENY";
                            }

                            string ruleDirection = "IN";
                            if (Direction.ToString() != "1")
                            {
                                ruleDirection = "OUT";
                            }

                            string ruleProtocol = "TCP";
                            if (Protocol.ToString() != "6")
                            {
                                ruleProtocol = "UDP";
                            }

                            Dictionary <string, string> rule = new Dictionary <string, string> {
                            };
                            rule["Name"]        = String.Format("{0}", Name);
                            rule["Description"] = String.Format("{0}", Description);
                            rule["AppName"]     = String.Format("{0}", ApplicationName);
                            rule["Protocol"]    = String.Format("{0}", ruleProtocol);
                            rule["Action"]      = String.Format("{0}", ruleAction);
                            rule["Direction"]   = String.Format("{0}", ruleDirection);
                            rule["Profiles"]    = String.Format("{0}", Int32.Parse(Profiles.ToString()));
                            rule["Local"]       = String.Format("{0}:{1}", LocalAddresses, LocalPorts);
                            rule["Remote"]      = String.Format("{0}:{1}", RemoteAddresses, RemotePorts);
                            results.Add(rule);
                        }
                    }
                    // manually move the enumerator
                    enumerator.MoveNext();
                    currentItem = enumerator.Current;
                }
                Marshal.ReleaseComObject(firewallObj);
                firewallObj = null;
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
Ejemplo n.º 6
0
        public static List <Dictionary <string, string> > GetNonstandardServicesFromReg()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                foreach (string key in MyUtils.GetRegSubkeys("HKLM", @"SYSTEM\CurrentControlSet\Services"))
                {
                    Dictionary <string, object> key_values = MyUtils.GetRegValues("HKLM", @"SYSTEM\CurrentControlSet\Services\" + key);

                    if (key_values.ContainsKey("DisplayName") && key_values.ContainsKey("ImagePath"))
                    {
                        string companyName = "";
                        string isDotNet    = "";
                        string pathName    = Environment.ExpandEnvironmentVariables(String.Format("{0}", key_values["ImagePath"]).Replace("\\SystemRoot\\", "%SystemRoot%\\"));
                        string binaryPath  = MyUtils.ReconstructExecPath(pathName);
                        if (binaryPath != "")
                        {
                            try
                            {
                                FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(binaryPath);
                                companyName = myFileVersionInfo.CompanyName;
                                isDotNet    = MyUtils.CheckIfDotNet(binaryPath) ? "isDotNet" : "";
                            }
                            catch (Exception ex)
                            {
                                // Not enough privileges
                            }
                        }

                        string displayName = String.Format("{0}", key_values["DisplayName"]);
                        string imagePath   = String.Format("{0}", key_values["ImagePath"]);
                        string description = key_values.ContainsKey("Description") ? String.Format("{0}", key_values["Description"]) : "";
                        string startMode   = "";
                        if (key_values.ContainsKey("Start"))
                        {
                            switch (key_values["Start"].ToString())
                            {
                            case "0":
                                startMode = "Boot";
                                break;

                            case "1":
                                startMode = "System";
                                break;

                            case "2":
                                startMode = "Autoload";
                                break;

                            case "3":
                                startMode = "System";
                                break;

                            case "4":
                                startMode = "Manual";
                                break;

                            case "5":
                                startMode = "Disabled";
                                break;
                            }
                        }
                        if (String.IsNullOrEmpty(companyName) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase)))
                        {
                            Dictionary <string, string> toadd = new Dictionary <string, string>();
                            toadd["Name"]         = String.Format("{0}", displayName);
                            toadd["DisplayName"]  = String.Format("{0}", displayName);
                            toadd["CompanyName"]  = companyName;
                            toadd["State"]        = "";
                            toadd["StartMode"]    = startMode;
                            toadd["PathName"]     = pathName;
                            toadd["FilteredPath"] = binaryPath;
                            toadd["isDotNet"]     = isDotNet;
                            toadd["Description"]  = description;
                            results.Add(toadd);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
        //From Seatbelt
        public static Dictionary <string, string> GetPowerShellSettings()
        {
            Dictionary <string, string> results = new Dictionary <string, string>();

            try
            {
                results["PowerShell v2 Version"]        = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\1\\PowerShellEngine", "PowerShellVersion");
                results["PowerShell v5 Version"]        = MyUtils.GetRegValue("HKLM", "SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", "PowerShellVersion");
                results["Transcription Settings"]       = "";
                results["Module Logging Settings"]      = "";
                results["Scriptblock Logging Settings"] = "";
                results["PS history file"] = "";
                results["PS history size"] = "";

                Dictionary <string, object> transcriptionSettings = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription");
                if ((transcriptionSettings == null) || (transcriptionSettings.Count == 0))
                {
                    transcriptionSettings = MyUtils.GetRegValues("HKLM", @"HKLM\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\Transcription");
                }

                if ((transcriptionSettings != null) && (transcriptionSettings.Count != 0))
                {
                    foreach (KeyValuePair <string, object> kvp in transcriptionSettings)
                    {
                        results["Transcription Settings"] += String.Format("  {0,30} : {1}\r\n", kvp.Key, kvp.Value);
                    }
                }

                Dictionary <string, object> moduleLoggingSettings = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ModuleLogging");
                if ((moduleLoggingSettings == null) || (moduleLoggingSettings.Count == 0))
                {
                    moduleLoggingSettings = MyUtils.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ModuleLogging");
                }

                if ((moduleLoggingSettings != null) && (moduleLoggingSettings.Count != 0))
                {
                    foreach (KeyValuePair <string, object> kvp in moduleLoggingSettings)
                    {
                        results["Module Logging Settings"] += String.Format("  {0,30} : {1}\r\n", kvp.Key, kvp.Value);
                    }
                }

                Dictionary <string, object> scriptBlockSettings = MyUtils.GetRegValues("HKLM", "SOFTWARE\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging");
                if ((scriptBlockSettings == null) || (scriptBlockSettings.Count == 0))
                {
                    scriptBlockSettings = MyUtils.GetRegValues("HKLM", @"SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging");
                }

                if ((scriptBlockSettings != null) && (scriptBlockSettings.Count != 0))
                {
                    foreach (KeyValuePair <string, object> kvp in scriptBlockSettings)
                    {
                        results["Scriptblock Logging Settings"] = String.Format("  {0,30} : {1}\r\n", kvp.Key, kvp.Value);
                    }
                }

                string ps_history_path = Environment.ExpandEnvironmentVariables(@"%APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt");
                if (File.Exists(ps_history_path))
                {
                    FileInfo fi   = new FileInfo(ps_history_path);
                    long     size = fi.Length;
                    results["PS history file"] = ps_history_path;
                    results["PS history size"] = size.ToString() + "B";
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }
        public static List <Dictionary <string, string> > GetRDPSessions()
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();
            // adapted from http://www.pinvoke.net/default.aspx/wtsapi32.wtsenumeratesessions
            IntPtr        server = IntPtr.Zero;
            List <String> ret    = new List <string>();

            server = OpenServer("localhost");

            try
            {
                IntPtr ppSessionInfo = IntPtr.Zero;

                Int32 count    = 0;
                Int32 level    = 1;
                Int32 retval   = WTSEnumerateSessionsEx(server, ref level, 0, ref ppSessionInfo, ref count);
                Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO_1));
                Int64 current  = (Int64)ppSessionInfo;

                if (retval != 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        Dictionary <string, string> rdp_session = new Dictionary <string, string>();
                        WTS_SESSION_INFO_1          si          = (WTS_SESSION_INFO_1)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO_1));
                        current += dataSize;
                        if (si.pUserName == null || si.pUserName == "")
                        {
                            continue;
                        }

                        rdp_session["SessionID"]    = String.Format("{0}", si.SessionID);
                        rdp_session["pSessionName"] = String.Format("{0}", si.pSessionName);
                        rdp_session["pUserName"]    = String.Format("{0}", si.pUserName);
                        rdp_session["pDomainName"]  = String.Format("{0}", si.pDomainName);
                        rdp_session["State"]        = String.Format("{0}", si.State);
                        rdp_session["SourceIP"]     = "";

                        // Now use WTSQuerySessionInformation to get the remote IP (if any) for the connection
                        IntPtr addressPtr = IntPtr.Zero;
                        uint   bytes      = 0;

                        WTSQuerySessionInformation(server, (uint)si.SessionID, WTS_INFO_CLASS.WTSClientAddress, out addressPtr, out bytes);
                        WTS_CLIENT_ADDRESS address = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure((System.IntPtr)addressPtr, typeof(WTS_CLIENT_ADDRESS));

                        if (address.Address[2] != 0)
                        {
                            string sourceIP = String.Format("{0}.{1}.{2}.{3}", address.Address[2], address.Address[3], address.Address[4], address.Address[5]);
                            rdp_session["SourceIP"] = String.Format("{0}", sourceIP);
                        }
                        results.Add(rdp_session);
                    }
                    WTSFreeMemory(ppSessionInfo);
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex));
            }
            finally
            {
                CloseServer(server);
            }
            return(results);
        }
Ejemplo n.º 9
0
        public static Dictionary <string, FileVersionInfo> GetDeviceDriversNoMicrosoft()
        {
            Dictionary <string, FileVersionInfo> results = new Dictionary <string, FileVersionInfo>();

            // ignore ghosts
            // https://devblogs.microsoft.com/oldnewthing/20160913-00/?p=94305
            Regex ignore_ghosts = new Regex("^dump_", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // manufacturer/providers to ignore
            Regex ignore_company = new Regex("^Microsoft", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            string system32 = Environment.SystemDirectory;

            // Get a list of loaded kernel modules
            UInt32 neededBytes;

            EnumAPI.EnumDeviceDrivers(null, 0, out neededBytes);
            UIntPtr[] drivers = new UIntPtr[neededBytes / UIntPtr.Size];
            EnumAPI.EnumDeviceDrivers(drivers, (UInt32)(drivers.Length * UIntPtr.Size), out neededBytes);

            // iterate over modules
            foreach (UIntPtr baseAddr in drivers)
            {
                StringBuilder buffer = new StringBuilder(1024);
                EnumAPI.GetDeviceDriverBaseName(baseAddr, buffer, (UInt32)buffer.Capacity);
                if (ignore_ghosts.IsMatch(buffer.ToString()))
                {
                    continue;
                }
                EnumAPI.GetDeviceDriverFileName(baseAddr, buffer, (UInt32)buffer.Capacity);
                string pathname = buffer.ToString();

                // GetDeviceDriverFileName can return a path in a various number of formats, below code tries to handle them.
                // https://community.osr.com/discussion/228671/querying-device-driver-list-from-kernel-mode
                if (pathname.StartsWith("\\??\\"))
                {
                    pathname = pathname.Remove(0, 4);
                }

                if (File.Exists(pathname))
                {
                    // intentionally empty
                }
                else if (pathname[0] == '\\')
                {
                    // path could be either in the NtObject namespace or from the filesystem root (without drive)
                    if (File.Exists("\\\\.\\GLOBALROOT" + pathname))
                    {
                        pathname = "\\\\.\\GLOBALROOT" + pathname;
                    }
                    else if (File.Exists(system32.Substring(0, 2) + pathname))
                    {
                        pathname = system32.Substring(0, 2) + pathname;
                    }
                    else
                    {
                        Beaprint.GrayPrint(string.Format("Ignoring unknown path {0}", pathname));
                        continue;
                    }
                }
                else
                {
                    // probably module is a boot driver without a full path
                    if (File.Exists(system32 + "\\drivers\\" + pathname))
                    {
                        pathname = system32 + "\\drivers\\" + pathname;
                    }
                    else if (File.Exists(system32 + "\\" + pathname))
                    {
                        pathname = system32 + "\\" + pathname;
                    }
                    else
                    {
                        Beaprint.GrayPrint(string.Format("Ignoring unknown path {0}", pathname));
                        continue;
                    }
                }

                try
                {
                    FileVersionInfo info = FileVersionInfo.GetVersionInfo(pathname.ToString());
                    if (!ignore_company.IsMatch(info.CompanyName))
                    {
                        results[pathname] = info;
                    }
                }
                catch (Exception ex)
                {
                    Beaprint.GrayPrint("Error: " + ex);
                }
            }
            return(results);
        }
Ejemplo n.º 10
0
        //////////////////////////////////////
        ///////  Get Autorun Registry ////////
        //////////////////////////////////////
        /// Find Autorun registry where you have write or equivalent access
        public static List <Dictionary <string, string> > GetRegistryAutoRuns(Dictionary <string, string> NtAccountNames)
        {
            List <Dictionary <string, string> > results = new List <Dictionary <string, string> >();

            try
            {
                List <List <String> > autorunLocations = new List <List <string> >()
                {
                    //Common Autoruns
                    new List <String> {
                        "HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
                    },
                    new List <String> {
                        "HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"
                    },
                    new List <String> {
                        "HKLM", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run"
                    },
                    new List <String> {
                        "HKLM", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce"
                    },
                    new List <String> {
                        "HKLM", @"Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\Run"
                    },
                    new List <String> {
                        "HKLM", @"Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\Runonce"
                    },
                    new List <String> {
                        "HKLM", @"Software\Microsoft\Windows NT\CurrentVersion\Terminal Server\Install\Software\Microsoft\Windows\CurrentVersion\RunEx"
                    },

                    //Service Autoruns
                    new List <String> {
                        "HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunService"
                    },
                    new List <String> {
                        "HKLM", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnceService"
                    },
                    new List <String> {
                        "HKLM", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunService"
                    },
                    new List <String> {
                        "HKLM", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnceService"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunService"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnceService"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunService"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnceService"
                    },

                    //Special Autorun
                    new List <String> {
                        "HKLM", "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnceEx"
                    },
                    new List <String> {
                        "HKLM", "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnceEx"
                    },
                    new List <String> {
                        "HKCU", "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnceEx"
                    },
                    new List <String> {
                        "HKCU", "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnceEx"
                    },

                    //Startup Path
                    new List <String> {
                        "HKCU", @"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", "Common Startup"
                    },
                    new List <String> {
                        "HKCU", @"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "Common Startup"
                    },
                    new List <String> {
                        "HKLM", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "Common Startup"
                    },
                    new List <String> {
                        "HKLM", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders", "Common Startup"
                    },

                    //Winlogon
                    new List <String> {
                        "HKLM", @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "Userinit"
                    },
                    new List <String> {
                        "HKLM", @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "Shell"
                    },

                    //Policy Settings
                    new List <String> {
                        "HKLM", @"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "Run"
                    },
                    new List <String> {
                        "HKCU", @"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "Run"
                    },

                    //AlternateShell in SafeBoot
                    new List <String> {
                        "HKLM", "SYSTEM\\CurrentControlSet\\Control\\SafeBoot", "AlternateShell"
                    },

                    //Font Drivers
                    new List <String> {
                        "HKLM", @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Font Drivers"
                    },
                    new List <String> {
                        "HKLM", @"SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Font Drivers"
                    },

                    //Open Command
                    new List <String> {
                        "HKLM", @"SOFTWARE\Classes\htmlfile\shell\open\command", ""
                    },                                                                              //Get (Default) value with empty string
                    new List <String> {
                        "HKLM", @"SOFTWARE\Wow6432Node\Classes\htmlfile\shell\open\command", ""
                    },                                                                                          //Get (Default) value with empty string
                };

                List <List <String> > autorunLocationsKeys = new List <List <String> >
                {
                    //Installed Components
                    new List <String> {
                        "HKLM", "SOFTWARE\\Microsoft\\Active Setup\\Installed Components", "StubPath"
                    },
                    new List <String> {
                        "HKLM", "SOFTWARE\\Wow6432Node\\Microsoft\\Active Setup\\Installed Components", "StubPath"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Microsoft\\Active Setup\\Installed Components", "StubPath"
                    },
                    new List <String> {
                        "HKCU", "SOFTWARE\\Wow6432Node\\Microsoft\\Active Setup\\Installed Components", "StubPath"
                    },
                };


                //This registry expect subkeys with the CLSID name
                List <List <String> > autorunLocationsKeysCLSIDs = new List <List <String> >
                {
                    //Browser Helper Objects
                    new List <String> {
                        "HKLM", @"Software\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects"
                    },
                    new List <String> {
                        "HKLM", @"Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects"
                    },

                    //Internet Explorer Extensions
                    new List <String> {
                        "HKLM", @"Software\Microsoft\Internet Explorer\Extensions"
                    },
                    new List <String> {
                        "HKLM", @"Software\Wow6432Node\Microsoft\Internet Explorer\Extensions"
                    },
                };

                //Add the keyvalues inside autorunLocationsKeys to autorunLocations
                foreach (List <String> autorunLocationKey in autorunLocationsKeys)
                {
                    List <String> subkeys = MyUtils.GetRegSubkeys(autorunLocationKey[0], autorunLocationKey[1]).ToList();
                    foreach (String keyname in subkeys)
                    {
                        string clsid_name = keyname;
                        Match  clsid      = Regex.Match(keyname, @"^\W*(\{[\w\-]+\})\W*");
                        if (clsid.Groups.Count > 1) //Sometime the CLSID is bad writting and this kind of fix common mistakes
                        {
                            clsid_name = clsid.Groups[1].ToString();
                        }

                        if (autorunLocationKey.Count > 2)
                        {
                            autorunLocations.Add(new List <string> {
                                autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name, autorunLocationKey[2]
                            });
                        }
                        else
                        {
                            autorunLocations.Add(new List <string> {
                                autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name
                            });
                        }
                    }
                }

                //Read registry and get values
                foreach (List <String> autorunLocation in autorunLocations)
                {
                    Dictionary <string, object> settings = MyUtils.GetRegValues(autorunLocation[0], autorunLocation[1]);
                    if ((settings != null) && (settings.Count != 0))
                    {
                        foreach (KeyValuePair <string, object> kvp in settings)
                        {
                            RegistryKey key = null;
                            if ("HKLM" == autorunLocation[0])
                            {
                                key = Registry.LocalMachine.OpenSubKey(autorunLocation[1]);
                            }
                            else
                            {
                                key = Registry.CurrentUser.OpenSubKey(autorunLocation[1]);
                            }


                            if (autorunLocation.Count > 2 && kvp.Key != autorunLocation[2])
                            {
                                continue; //If only interested on 1 key of the registry and it's that one, continue
                            }
                            string orig_filepath = Environment.ExpandEnvironmentVariables(String.Format("{0}", kvp.Value));
                            string filepath      = orig_filepath;
                            if (MyUtils.GetExecutableFromPath(Environment.ExpandEnvironmentVariables(String.Format("{0}", kvp.Value))).Length > 0)
                            {
                                filepath = MyUtils.GetExecutableFromPath(filepath);
                            }
                            string filepath_cleaned = filepath.Replace("'", "").Replace("\"", "");

                            string folder = System.IO.Path.GetDirectoryName(filepath_cleaned);
                            try
                            {     //If the path doesn't exist, pass
                                if (File.GetAttributes(filepath_cleaned).HasFlag(FileAttributes.Directory))
                                { //If the path is already a folder, change the values of the params
                                    orig_filepath = "";
                                    folder        = filepath_cleaned;
                                }
                            }
                            catch
                            {
                            }

                            results.Add(new Dictionary <string, string>()
                            {
                                { "Reg", autorunLocation[0] + "\\" + autorunLocation[1] },
                                { "RegKey", kvp.Key },
                                { "Folder", folder },
                                { "File", orig_filepath },
                                {
                                    "RegPermissions",
                                    string.Join(", ", MyUtils.GetMyPermissionsR(key, Program.currentUserSIDs))
                                },
                                {
                                    "interestingFolderRights",
                                    String.Join(", ", MyUtils.GetPermissionsFolder(folder, Program.currentUserSIDs))
                                },
                                {
                                    "interestingFileRights",
                                    orig_filepath.Length > 1 ? String.Join(", ", MyUtils.GetPermissionsFile(orig_filepath, Program.currentUserSIDs)) : ""
                                },
                                { "isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(filepath).ToString() }
                            });
                        }
                    }
                }

                //Check the autoruns that depends on CLSIDs
                foreach (List <String> autorunLocation in autorunLocationsKeysCLSIDs)
                {
                    List <String> CLSIDs = MyUtils.GetRegSubkeys(autorunLocation[0], autorunLocation[1]).ToList();
                    foreach (String clsid in CLSIDs)
                    {
                        string      reg = autorunLocation[1] + "\\" + clsid;
                        RegistryKey key = null;
                        if ("HKLM" == autorunLocation[0])
                        {
                            key = Registry.LocalMachine.OpenSubKey(reg);
                        }
                        else
                        {
                            key = Registry.CurrentUser.OpenSubKey(reg);
                        }

                        string orig_filepath = MyUtils.GetCLSIDBinPath(clsid);
                        if (String.IsNullOrEmpty(orig_filepath))
                        {
                            continue;
                        }
                        orig_filepath = Environment.ExpandEnvironmentVariables(orig_filepath).Replace("'", "").Replace("\"", "");
                        string folder = System.IO.Path.GetDirectoryName(orig_filepath);

                        results.Add(new Dictionary <string, string>()
                        {
                            { "Reg", autorunLocation[0] + "\\" + reg },
                            { "RegKey", "" },
                            { "Folder", folder },
                            { "File", orig_filepath },
                            {
                                "RegPermissions",
                                string.Join(", ", MyUtils.GetMyPermissionsR(key, Program.currentUserSIDs))
                            },
                            {
                                "interestingFolderRights",
                                String.Join(", ", MyUtils.GetPermissionsFolder(folder, Program.currentUserSIDs))
                            },
                            {
                                "interestingFileRights",
                                orig_filepath.Length > 1 ? String.Join(", ", MyUtils.GetPermissionsFile(orig_filepath, Program.currentUserSIDs)) : ""
                            },
                            { "isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(orig_filepath).ToString() }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Beaprint.GrayPrint(String.Format("  [X] Exception: {0}", ex.Message));
            }
            return(results);
        }