Beispiel #1
0
		/// <summary>
		/// Creates a TaskScan with a list of directories to scan,
		/// a key to tell the TaskScan what text to look for to begin a task,
		/// and a SearchOption.
		/// </summary>
		/// <param name="directory">The directories to search for tasks</param>
		/// <param name="key">The key for task lookup</param>
		/// <param name="option">Whether or not to delve deeper into repositories</param>
		public TaskScan (IEnumerable<string> directory, string key, SearchOption option)
		{
			TaskDir = new DirectorySearch (directory, option);
			Tasks = new TaskTable ();

			Key = key;
		}
        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();

            //Create DIrectorySearch object from given path
            DirectorySearch directorySearch = new DirectorySearch(txtPath.Text);
            //Create list of files returned by traversing the directory
            IEnumerable <System.IO.FileInfo> files = directorySearch.TraverseDirectory();

            Thread.Sleep(100);
            prgBar.Maximum = files.Count();

            //Create writeToExcel object from given path
            WriteToExcel writeToExcel = new WriteToExcel(txtSaveToPath.Text);

            //Setup Excel file prior to data input
            writeToExcel.setupExcel();
            //Iterate through the list of files and add data to the Excel file
            writeToExcel.addData(files);
            //Save the file and tidy up
            writeToExcel.saveExcelFile();


            watch.Stop();

            MessageBox.Show($"Excel file created in {watch.ElapsedMilliseconds} ms");
        }
Beispiel #3
0
 protected BaseProducer(string domainName, string query, string[] props)
 {
     Searcher   = Helpers.GetDirectorySearcher(domainName);
     Query      = query;
     Props      = props;
     DomainName = domainName;
     SetDomainControllerSids(GetDomainControllerSids());
 }
Beispiel #4
0
        public void Setup()
        {
            _mockFileSearch  = new Mock <IFileSearch>();
            _mockFileManager = new Mock <IFileManager>();
            _mockFileSystem  = new Mock <IFileSystem>();

            _directorySearch = new DirectorySearch(_mockFileSearch.Object, _mockFileManager.Object, _someDirectory, _mockFileSystem.Object);
        }
Beispiel #5
0
 protected BaseProducer(string domainName, string query, string[] props)
 {
     //Create a Directory Searcher using the domain specified
     Searcher   = Helpers.GetDirectorySearcher(domainName);
     Query      = query;
     Props      = props;
     DomainName = domainName;
     SetDomainControllerSids(GetDomainControllerSids());
 }
Beispiel #6
0
        public List <DFSShare> Get_DomainDFSShare(DirectorySearch DFSSearcher)
        {
            var DFSShares = new List <DFSShare>();

            DFSShares.AddRange(Get_DomainDFSShareV1(DFSSearcher));
            DFSShares.AddRange(Get_DomainDFSShareV2(DFSSearcher));

            return(DFSShares);
        }
Beispiel #7
0
        private List <DFSShare> Get_DomainDFSShareV2(DirectorySearch _directorySearch)
        {
            var DFSShares = new List <DFSShare>();

            string[] properties = new string[] { @"msdfs-linkpathv2", @"msDFS-TargetListv2", "cn", "name" };
            string   filter     = @"(&(objectClass=msDFS-Linkv2))";

            try
            {
                IEnumerable <SearchResultEntry> searchResultEntries = _directorySearch.QueryLdap(filter, properties, System.DirectoryServices.Protocols.SearchScope.Subtree);
                int count = searchResultEntries.Count();

                foreach (SearchResultEntry resEnt in searchResultEntries)
                {
                    //Console.WriteLine("Found a DFSv2 entry.");
                    string dfsnamespace = resEnt.DistinguishedName.Replace("CN=", "").Split(',')[1];

                    var    target_list = resEnt.GetPropertyAsBytes(@"msdfs-targetlistv2");
                    var    xml         = new XmlDocument();
                    string thing       = System.Text.Encoding.Unicode.GetString(target_list.Skip(2).Take(target_list.Length - 1 + 1 - 2).ToArray());
                    xml.LoadXml(System.Text.Encoding.Unicode.GetString(target_list.Skip(2).Take(target_list.Length - 1 + 1 - 2).ToArray()));

                    if (xml.FirstChild != null)
                    {
                        foreach (XmlNode node in xml.ChildNodes)
                        {
                            foreach (XmlNode babbynode in node.ChildNodes)
                            {
                                try
                                {
                                    var Target = node.InnerText;
                                    if (Target.Contains(@"\"))
                                    {
                                        var    DFSroot   = Target.Split('\\')[3];
                                        string ShareName = resEnt.GetProperty(@"msdfs-linkpathv2").Replace("/", "\\");
                                        DFSShares.Add(new DFSShare {
                                            Name = $@"{DFSroot}{ShareName}", RemoteServerName = Target.Split('\\')[2], DFSNamespace = dfsnamespace
                                        });
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Error in parsing DFSv2 share : " + e);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Get-DomainDfsShareV2 error : " + e);
            }
            return(DFSShares);
        }
Beispiel #8
0
        /// <summary>
        /// Search the specified searchDirectory, searchPhrase and outputFileName.
        /// </summary>
        /// <param name="searchDirectory">Search directory.</param>
        /// <param name="searchPhrase">Search phrase.</param>
        /// <param name="outputFileName">Output file name.</param>
        public void Search(string searchDirectory, string searchPhrase, string outputFileName)
        {
            var fileSearch  = new FileSearch(searchPhrase);
            var fileManager = new FileManager();

            var dirSearch = new DirectorySearch(fileSearch, fileManager, searchDirectory);

            dirSearch.SearchDirectory();
            dirSearch.BuildSearchResultsOutputFile(outputFileName);
            dirSearch.WriteSearchResultsToConsole();
        }
Beispiel #9
0
        public void OnGet()
        {
            searchQuery = RouteData.Values["searchQuery"].ToString();
            Console.WriteLine(searchQuery);
            string domain = HttpContext.Session.GetString("Domain");

            directorySearch = new DirectorySearch(searchQuery, domain);
            ADUsername      = directorySearch.userResult.SamAccountName;
            ADEmailaddress  = directorySearch.userResult.EmailAddress;
            //directorySearch.userResult.Dispose();
        }
Beispiel #10
0
        private string GetNetBiosDomainName()
        {
            string ldapBase = $"CN=Partitions,CN=Configuration,DC={_targetDomain.Replace(".", ",DC=")}";

            DirectorySearch ds = new DirectorySearch(_targetDomain, _targetDc, ldapBase, null, null, 0, false);

            string[] ldapProperties = new string[] { "netbiosname" };
            string   ldapFilter     = string.Format("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", _targetDomain);

            foreach (SearchResultEntry sre in ds.QueryLdap(ldapFilter, ldapProperties, System.DirectoryServices.Protocols.SearchScope.Subtree))
            {
                return(sre.GetProperty("netbiosname"));
            }

            return(null);
        }
Beispiel #11
0
        /// <summary>
        /// Runs search based on search properties
        /// </summary>
        private async Task Search()
        {
            // run validation before we do anything
            ValidateDirectory();

            if (PropertyHasErrors("DirectorySearchPath"))
            {
                return;
            }

            IsRunning      = true;
            ResultsVisible = true;
            _cancelToken   = new CancellationTokenSource();

            Results.Clear();

            // get each directory that should be searched
            foreach (string file in DirectorySearch.EnumerateFiles())
            {
                // check if search has been stopped
                if (_cancelToken.IsCancellationRequested)
                {
                    break;
                }

                //bool result = await SearchFile(file); // blocks ui thread because there are CPU bound operations
                bool result = await Task.Run(() => SearchFile(file)); // runs on a different thread

                if (result == true)
                {
                    var FM = new FileMatch(file);
                    Results.Add(FM);
                }

                // stop if limit reached
                if (Results.Count >= _appSettings.LimitResults)
                {
                    break;
                }
            }

            IsRunning = false;
        }
        public void FindSeriesNoMatch()
        {
            MoveableFile file = new MoveableFile
            {
                Names = new List <string> {
                    "Friends"
                },
                IsSeries = true
            };

            IList <string> dirs = new List <string> {
                @"C:\Series\Enemies\", @"C:\Series\Buddies\"
            };

            DirectorySearch ds = new DirectorySearch(dirs);

            var di = ds.FindDirectoryMatches(file);

            Assert.IsFalse(di.Any());
        }
        public void FindSeriesFolderSingleMatch()
        {
            MoveableFile file = new MoveableFile
            {
                Names = new List <string> {
                    "Friends"
                },
                IsSeries = true
            };

            IList <string> dirs = new List <string> {
                @"C:\Series\Friends\", @"C:\Series\Pals\", @"C:\Series\Buddies\"
            };

            DirectorySearch ds = new DirectorySearch(dirs);

            var di = ds.FindDirectoryMatches(file);

            Assert.AreEqual(1, di.Count());
        }
        private void StartSearch(string path, string filter)
        {
            DirectorySearch directory = new DirectorySearch(path, filter);
            int             state     = directory.FindFiles();

            switch (state)
            {
            case 0:
                Dispatcher.Invoke(() =>
                {
                    lvFindings.Items.Clear();
                    foreach (var p in directory.Findings)
                    {
                        lvFindings.Items.Add(new DisplayOfFindings {
                            Path = p
                        });
                    }
                });
                break;

            case 1:
                Dispatcher.Invoke(() =>
                {
                    tbcSearchError.Visibility = Visibility.Visible;
                });
                break;

            case 2:
                Dispatcher.Invoke(() =>
                {
                    tbcDirectoryError.Visibility = Visibility.Visible;
                });
                break;
            }
            Dispatcher.Invoke(() =>
            {
                pbSearch.Visibility = Visibility.Collapsed;
            });
        }
        public void FindSeriesFolderManyMatches()
        {
            MoveableFile file = new MoveableFile
            {
                Names = new List <string> {
                    "Friends", "Enemies"
                },
                IsSeries = true
            };

            IList <string> dirs = new List <string> {
                @"C:\Series\Friends\", @"C:\Series\Friends and Enemies\", @"C:\Series\Buddies\"
            };

            DirectorySearch ds = new DirectorySearch(dirs);

            var di = ds.FindDirectoryMatches(file);

            Assert.AreEqual(2, di.Count());
            Assert.AreEqual(2, di.OrderByDescending(d => d.Matches).First().Matches);
            Assert.AreEqual("Friends and Enemies", di.OrderByDescending(d => d.Matches).First().Directory.Name);
        }
Beispiel #16
0
        public virtual void VisitItem(Object item)
        {
            if (item == null)
            {
                return;
            }

            Module module = item as Module;

            if (module != null)
            {
                VisitModule(module);
                return;
            }
            Product product = item as Product;

            if (product != null)
            {
                VisitProduct(product);
                return;
            }
            Feature feature = item as Feature;

            if (feature != null)
            {
                VisitFeature(feature);
                return;
            }
            AdvtExecuteSequence advtExecuteSequence = item as AdvtExecuteSequence;

            if (advtExecuteSequence != null)
            {
                VisitAdvtExecuteSequence(advtExecuteSequence);
                return;
            }
            InstallUISequence installUISequence = item as InstallUISequence;

            if (installUISequence != null)
            {
                VisitInstallUISequence(installUISequence);
                return;
            }
            User user = item as User;

            if (user != null)
            {
                VisitUser(user);
                return;
            }
            Upgrade upgrade = item as Upgrade;

            if (upgrade != null)
            {
                VisitUpgrade(upgrade);
                return;
            }
            Directory directory = item as Directory;

            if (directory != null)
            {
                VisitDirectory(directory);
                return;
            }
            PropertyRef propertyRef = item as PropertyRef;

            if (propertyRef != null)
            {
                VisitPropertyRef(propertyRef);
                return;
            }
            WebSite webSite = item as WebSite;

            if (webSite != null)
            {
                VisitWebSite(webSite);
                return;
            }
            AdminUISequence adminUISequence = item as AdminUISequence;

            if (adminUISequence != null)
            {
                VisitAdminUISequence(adminUISequence);
                return;
            }
            CustomAction customAction = item as CustomAction;

            if (customAction != null)
            {
                VisitCustomAction(customAction);
                return;
            }
            DirectoryRef directoryRef = item as DirectoryRef;

            if (directoryRef != null)
            {
                VisitDirectoryRef(directoryRef);
                return;
            }
            AppId appId = item as AppId;

            if (appId != null)
            {
                VisitAppId(appId);
                return;
            }
            Media media = item as Media;

            if (media != null)
            {
                VisitMedia(media);
                return;
            }
            CustomTable customTable = item as CustomTable;

            if (customTable != null)
            {
                VisitCustomTable(customTable);
                return;
            }
            Condition condition = item as Condition;

            if (condition != null)
            {
                VisitCondition(condition);
                return;
            }
            SFPCatalog sFPCatalog = item as SFPCatalog;

            if (sFPCatalog != null)
            {
                VisitSFPCatalog(sFPCatalog);
                return;
            }
            UI ui = item as UI;

            if (ui != null)
            {
                VisitUI(ui);
                return;
            }
            FragmentRef fragmentRef = item as FragmentRef;

            if (fragmentRef != null)
            {
                VisitFragmentRef(fragmentRef);
                return;
            }
            Icon icon = item as Icon;

            if (icon != null)
            {
                VisitIcon(icon);
                return;
            }
            Property property = item as Property;

            if (property != null)
            {
                VisitProperty(property);
                return;
            }
            FeatureRef featureRef = item as FeatureRef;

            if (featureRef != null)
            {
                VisitFeatureRef(featureRef);
                return;
            }
            WebDirProperties webDirProperties = item as WebDirProperties;

            if (webDirProperties != null)
            {
                VisitWebDirProperties(webDirProperties);
                return;
            }
            ComplianceCheck complianceCheck = item as ComplianceCheck;

            if (complianceCheck != null)
            {
                VisitComplianceCheck(complianceCheck);
                return;
            }
            InstallExecuteSequence installExecuteSequence = item as InstallExecuteSequence;

            if (installExecuteSequence != null)
            {
                VisitInstallExecuteSequence(installExecuteSequence);
                return;
            }
            AdminExecuteSequence adminExecuteSequence = item as AdminExecuteSequence;

            if (adminExecuteSequence != null)
            {
                VisitAdminExecuteSequence(adminExecuteSequence);
                return;
            }
            Binary binary = item as Binary;

            if (binary != null)
            {
                VisitBinary(binary);
                return;
            }
            Group group = item as Group;

            if (group != null)
            {
                VisitGroup(group);
                return;
            }
            WebApplication webApplication = item as WebApplication;

            if (webApplication != null)
            {
                VisitWebApplication(webApplication);
                return;
            }
            ActionSequenceType actionSequenceType = item as ActionSequenceType;

            if (actionSequenceType != null)
            {
                VisitActionSequenceType(actionSequenceType);
                return;
            }
            ActionModuleSequenceType actionModuleSequenceType = item as ActionModuleSequenceType;

            if (actionModuleSequenceType != null)
            {
                VisitActionModuleSequenceType(actionModuleSequenceType);
                return;
            }
            BillboardAction billboardAction = item as BillboardAction;

            if (billboardAction != null)
            {
                VisitBillboardAction(billboardAction);
                return;
            }
            Error error = item as Error;

            if (error != null)
            {
                VisitError(error);
                return;
            }
            Dialog dialog = item as Dialog;

            if (dialog != null)
            {
                VisitDialog(dialog);
                return;
            }
            ProgressText progressText = item as ProgressText;

            if (progressText != null)
            {
                VisitProgressText(progressText);
                return;
            }
            TextStyle textStyle = item as TextStyle;

            if (textStyle != null)
            {
                VisitTextStyle(textStyle);
                return;
            }
            ListBox listBox = item as ListBox;

            if (listBox != null)
            {
                VisitListBox(listBox);
                return;
            }
            ListView listView = item as ListView;

            if (listView != null)
            {
                VisitListView(listView);
                return;
            }
            ComboBox comboBox = item as ComboBox;

            if (comboBox != null)
            {
                VisitComboBox(comboBox);
                return;
            }
            UIText uIText = item as UIText;

            if (uIText != null)
            {
                VisitUIText(uIText);
                return;
            }
            RadioGroup radioGroup = item as RadioGroup;

            if (radioGroup != null)
            {
                VisitRadioGroup(radioGroup);
                return;
            }
            IniFileSearch iniFileSearch = item as IniFileSearch;

            if (iniFileSearch != null)
            {
                VisitIniFileSearch(iniFileSearch);
                return;
            }
            RegistrySearch registrySearch = item as RegistrySearch;

            if (registrySearch != null)
            {
                VisitRegistrySearch(registrySearch);
                return;
            }
            ComponentSearch componentSearch = item as ComponentSearch;

            if (componentSearch != null)
            {
                VisitComponentSearch(componentSearch);
                return;
            }
            FileSearch fileSearch = item as FileSearch;

            if (fileSearch != null)
            {
                VisitFileSearch(fileSearch);
                return;
            }
            DirectorySearch directorySearch = item as DirectorySearch;

            if (directorySearch != null)
            {
                VisitDirectorySearch(directorySearch);
                return;
            }
            File file = item as File;

            if (file != null)
            {
                VisitFile(file);
                return;
            }
            Component component = item as Component;

            if (component != null)
            {
                VisitComponent(component);
                return;
            }
            Merge merge = item as Merge;

            if (merge != null)
            {
                VisitMerge(merge);
                return;
            }
            Custom custom = item as Custom;

            if (custom != null)
            {
                VisitCustom(custom);
                return;
            }
            WebError webError = item as WebError;

            if (webError != null)
            {
                VisitWebError(webError);
                return;
            }
            WebVirtualDir webVirtualDir = item as WebVirtualDir;

            if (webVirtualDir != null)
            {
                VisitWebVirtualDir(webVirtualDir);
                return;
            }
            WebDir webDir = item as WebDir;

            if (webDir != null)
            {
                VisitWebDir(webDir);
                return;
            }
            WebFilter webFilter = item as WebFilter;

            if (webFilter != null)
            {
                VisitWebFilter(webFilter);
                return;
            }
            MergeRef mergeRef = item as MergeRef;

            if (mergeRef != null)
            {
                VisitMergeRef(mergeRef);
                return;
            }
            Subscribe subscribe = item as Subscribe;

            if (subscribe != null)
            {
                VisitSubscribe(subscribe);
                return;
            }
            Publish publish = item as Publish;

            if (publish != null)
            {
                VisitPublish(publish);
                return;
            }
            TypeLib typeLib = item as TypeLib;

            if (typeLib != null)
            {
                VisitTypeLib(typeLib);
                return;
            }
            Shortcut shortcut = item as Shortcut;

            if (shortcut != null)
            {
                VisitShortcut(shortcut);
                return;
            }
            ODBCTranslator oDBCTranslator = item as ODBCTranslator;

            if (oDBCTranslator != null)
            {
                VisitODBCTranslator(oDBCTranslator);
                return;
            }
            Permission permission = item as Permission;

            if (permission != null)
            {
                VisitPermission(permission);
                return;
            }
            Class _class = item as Class;

            if (_class != null)
            {
                VisitClass(_class);
                return;
            }
            CopyFile copyFile = item as CopyFile;

            if (copyFile != null)
            {
                VisitCopyFile(copyFile);
                return;
            }
            Patch patch = item as Patch;

            if (patch != null)
            {
                VisitPatch(patch);
                return;
            }
            ODBCDriver oDBCDriver = item as ODBCDriver;

            if (oDBCDriver != null)
            {
                VisitODBCDriver(oDBCDriver);
                return;
            }
            PerfCounter perfCounter = item as PerfCounter;

            if (perfCounter != null)
            {
                VisitPerfCounter(perfCounter);
                return;
            }
            FileShare fileShare = item as FileShare;

            if (fileShare != null)
            {
                VisitFileShare(fileShare);
                return;
            }
            Certificate certificate = item as Certificate;

            if (certificate != null)
            {
                VisitCertificate(certificate);
                return;
            }
            Category category = item as Category;

            if (category != null)
            {
                VisitCategory(category);
                return;
            }
            WebAppPool webAppPool = item as WebAppPool;

            if (webAppPool != null)
            {
                VisitWebAppPool(webAppPool);
                return;
            }
            SqlString sqlString = item as SqlString;

            if (sqlString != null)
            {
                VisitSqlString(sqlString);
                return;
            }
            ServiceControl serviceControl = item as ServiceControl;

            if (serviceControl != null)
            {
                VisitServiceControl(serviceControl);
                return;
            }
            IsolateComponent isolateComponent = item as IsolateComponent;

            if (isolateComponent != null)
            {
                VisitIsolateComponent(isolateComponent);
                return;
            }
            ServiceConfig serviceConfig = item as ServiceConfig;

            if (serviceConfig != null)
            {
                VisitServiceConfig(serviceConfig);
                return;
            }
            WebProperty webProperty = item as WebProperty;

            if (webProperty != null)
            {
                VisitWebProperty(webProperty);
                return;
            }
            SqlScript sqlScript = item as SqlScript;

            if (sqlScript != null)
            {
                VisitSqlScript(sqlScript);
                return;
            }
            SqlDatabase sqlDatabase = item as SqlDatabase;

            if (sqlDatabase != null)
            {
                VisitSqlDatabase(sqlDatabase);
                return;
            }
            WebLockdown webLockdown = item as WebLockdown;

            if (webLockdown != null)
            {
                VisitWebLockdown(webLockdown);
                return;
            }
            Extension extension = item as Extension;

            if (extension != null)
            {
                VisitExtension(extension);
                return;
            }
            ReserveCost reserveCost = item as ReserveCost;

            if (reserveCost != null)
            {
                VisitReserveCost(reserveCost);
                return;
            }
            RemoveFile removeFile = item as RemoveFile;

            if (removeFile != null)
            {
                VisitRemoveFile(removeFile);
                return;
            }
            ProgId progId = item as ProgId;

            if (progId != null)
            {
                VisitProgId(progId);
                return;
            }
            Microsoft.Tools.WindowsInstallerXml.Serialize.Environment environment = item as
                                                                                    Microsoft.Tools.WindowsInstallerXml.Serialize.Environment;
            if (environment != null)
            {
                VisitEnvironment(environment);
                return;
            }
            ServiceInstall serviceInstall = item as ServiceInstall;

            if (serviceInstall != null)
            {
                VisitServiceInstall(serviceInstall);
                return;
            }
            IniFile iniFile = item as IniFile;

            if (iniFile != null)
            {
                VisitIniFile(iniFile);
                return;
            }
            Registry registry = item as Registry;

            if (registry != null)
            {
                VisitRegistry(registry);
                return;
            }
            CreateFolder createFolder = item as CreateFolder;

            if (createFolder != null)
            {
                VisitCreateFolder(createFolder);
                return;
            }
            MIME mIME = item as MIME;

            if (mIME != null)
            {
                VisitMIME(mIME);
                return;
            }
            Verb verb = item as Verb;

            if (verb != null)
            {
                VisitVerb(verb);
                return;
            }
        }
Beispiel #17
0
        public void SetDomainUsers()
        {
            DirectorySearch ds          = GetDirectorySearcher();
            List <string>   domainUsers = new List <string>();

            string[] ldapProperties = new string[] { "name", "adminCount", "sAMAccountName", "userAccountControl", "servicePrincipalName", "userPrincipalName" };
            string   ldapFilter     = "(&(objectClass=user)(objectCategory=person))";

            IEnumerable <SearchResultEntry> searchResultEntries = ds.QueryLdap(ldapFilter, ldapProperties, System.DirectoryServices.Protocols.SearchScope.Subtree);

            foreach (SearchResultEntry resEnt in searchResultEntries)
            {
                bool keepUser = false;
                try
                {
                    //busted account name
                    if (String.IsNullOrEmpty(resEnt.GetProperty("sAMAccountName")))
                    {
                        continue;
                    }

                    int  uacFlags;
                    bool success =
                        int.TryParse(resEnt.GetProperty("userAccountControl"),
                                     out uacFlags);
                    UserAccountControlFlags userAccFlags = (UserAccountControlFlags)uacFlags;

                    if (userAccFlags.HasFlag(UserAccountControlFlags.AccountDisabled))
                    {
                        continue;
                    }

                    string userName = resEnt.GetProperty("sAMAccountName");

                    if (userName.EndsWith("$"))
                    {
                        Mq.Trace("Skipping " + userName +
                                 " because it appears to be a computer or trust account.");
                        continue;
                    }

                    //skip mailboxy accounts - domains always have a billion of these.
                    if (userName.IndexOf("mailbox", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        Mq.Trace("Skipping " + userName +
                                 " because it appears to be a mailbox.");
                        continue;
                    }

                    if (userName.IndexOf("mbx", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        Mq.Trace("Skipping " + userName +
                                 " because it appears to be a mailbox.");
                        continue;
                    }

                    // if has an SPN, keep it
                    if (!keepUser && resEnt.GetProperty("servicePrincipalName") != null)
                    {
                        Mq.Trace("Adding " + userName +
                                 " to target list because it has an SPN");
                        keepUser = true;
                    }

                    // if it's got adminCount, keep it
                    if (!keepUser && resEnt.GetProperty("adminCount") == "1")
                    {
                        Mq.Trace("Adding " + userName +
                                 " to target list because it had adminCount=1.");
                        keepUser = true;
                    }

                    // if the password doesn't expire it's probably a service account
                    if (!keepUser && userAccFlags.HasFlag(UserAccountControlFlags.PasswordDoesNotExpire))
                    {
                        Mq.Trace("Adding " + userName +
                                 " to target list because password does not expire,  probably service account.");
                        keepUser = true;
                    }

                    if (!keepUser && userAccFlags.HasFlag(UserAccountControlFlags.DontRequirePreauth))
                    {
                        Mq.Trace("Adding " + userName +
                                 " to target list because it doesn't require Kerberos pre-auth.");
                        keepUser = true;
                    }

                    if (!keepUser && userAccFlags.HasFlag(UserAccountControlFlags.TrustedForDelegation))
                    {
                        Mq.Trace("Adding " + userName +
                                 " to target list because it is trusted for delegation.");
                        keepUser = true;
                    }

                    if (!keepUser && userAccFlags.HasFlag(UserAccountControlFlags
                                                          .TrustedToAuthenticateForDelegation))
                    {
                        Mq.Trace("Adding " + userName +
                                 " to target list because it is trusted for delegation.");
                        keepUser = true;
                    }

                    // Included patterns
                    if (!keepUser)
                    {
                        foreach (string str in MyOptions.DomainUserMatchStrings)
                        {
                            if (userName.ToLower().Contains(str.ToLower()))
                            {
                                Mq.Trace("Adding " + userName +
                                         " to target list because it contained " + str + ".");
                                keepUser = true;
                                break;
                            }
                        }
                    }


                    // Finished testing
                    if (!keepUser)
                    {
                        continue;
                    }

                    // Must have matched something
                    // For common/frequent names,  force fully-qualified strict formats
                    if (MyOptions.DomainUserStrictStrings.Contains(userName, StringComparer.OrdinalIgnoreCase))
                    {
                        Mq.Trace("Using strict formats for " + userName + ".");

                        domainUsers.Add(String.Format(@"{0}\{1}", _targetDomainNetBIOSName, userName));

                        if (!string.IsNullOrEmpty(resEnt.GetProperty("userPrincipalName")))
                        {
                            domainUsers.Add(resEnt.GetProperty("userPrincipalName"));
                        }

                        continue;
                    }

                    // Otherwise, go with the format preference from the config file
                    foreach (DomainUserNamesFormat dnuf in MyOptions.DomainUserNameFormats)
                    {
                        switch (dnuf)
                        {
                        case DomainUserNamesFormat.NetBIOS:
                            domainUsers.Add(String.Format(@"{0}\{1}", _targetDomainNetBIOSName, userName));
                            break;

                        case DomainUserNamesFormat.UPN:
                            if (!string.IsNullOrEmpty(resEnt.GetProperty("userPrincipalName")))
                            {
                                domainUsers.Add(resEnt.GetProperty("userPrincipalName"));
                            }
                            else
                            {
                                Mq.Trace("Adding " + userName + " with simple sAMAccountName because UPN is missing.");
                                domainUsers.Add(userName);
                            }
                            break;

                        case DomainUserNamesFormat.sAMAccountName:
                            domainUsers.Add(userName);
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Mq.Trace(e.ToString());
                    continue;
                }
            }

            this._domainUsers = domainUsers;
        }
Beispiel #18
0
        public void SetDomainComputers(string LdapFilter)
        {
            DirectorySearch ds = GetDirectorySearcher();

            List <string> domainComputers = new List <string>();

            try
            {
                if (!MyOptions.DfsOnly)
                {
                    // if we aren't limiting the scan to DFS shares then let's get some computer targets.

                    List <string> ldapPropertiesList = new List <string> {
                        "name", "dNSHostName", "lastLogonTimeStamp"
                    };
                    string ldapFilter = LdapFilter;

                    // extremely dirty hack to break a sig I once saw for Snaffler's LDAP queries. ;-)
                    int num = random.Next(1, 5);
                    while (num > 0)
                    {
                        Guid guid = Guid.NewGuid();
                        ldapPropertiesList.Add(guid.ToString());
                        --num;
                    }
                    string[] ldapProperties = ldapPropertiesList.ToArray();

                    IEnumerable <SearchResultEntry> searchResultEntries = ds.QueryLdap(ldapFilter, ldapProperties, System.DirectoryServices.Protocols.SearchScope.Subtree);

                    // set a window of "the last 4 months" - if a computer hasn't logged in to the domain in 4 months it's probably gone.
                    DateTime validLltsWindow = DateTime.Now.AddMonths(-4);
                    foreach (SearchResultEntry resEnt in searchResultEntries)
                    {
                        int  uacFlags;
                        bool success =
                            int.TryParse(resEnt.GetProperty("userAccountControl"),
                                         out uacFlags);

                        UserAccountControlFlags userAccFlags = (UserAccountControlFlags)uacFlags;

                        if (userAccFlags.HasFlag(UserAccountControlFlags.AccountDisabled))
                        {
                            continue;
                        }

                        try
                        {
                            // get the last logon timestamp value as a datetime
                            string lltsString = resEnt.GetProperty("lastlogontimestamp");
                            long   lltsLong;
                            long.TryParse(lltsString, out lltsLong);
                            DateTime lltsDateTime = DateTime.FromFileTime(lltsLong);
                            // compare it to our window, and if lltsDateTime is older, skip the computer acct.
                            if (lltsDateTime <= validLltsWindow)
                            {
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Mq.Error("Error calculating lastLogonTimeStamp for computer account " + resEnt.DistinguishedName);
                        }

                        if (!String.IsNullOrEmpty(resEnt.GetProperty("dNSHostName")))
                        {
                            string computerName = resEnt.GetProperty("dNSHostName");
                            domainComputers.Add(computerName);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Mq.Trace(e.ToString());
            }

            this._domainComputers = domainComputers;
        }
Beispiel #19
0
        private List <DFSShare> Get_DomainDFSShareV1(DirectorySearch _directorySearch)
        {
            var DFSShares = new List <DFSShare>();

            string[] properties = new string[] { "remoteservername", "pkt", "cn", "name" };
            string   filter     = @"(&(objectClass=fTDfs))";

            try
            {
                IEnumerable <SearchResultEntry> searchResultEntries = _directorySearch.QueryLdap(filter, properties, System.DirectoryServices.Protocols.SearchScope.Subtree);
                int count = searchResultEntries.Count();

                foreach (SearchResultEntry resEnt in searchResultEntries)
                {
                    string dfsnamespace = resEnt.DistinguishedName.Replace("CN=", "").Split(',')[0];

                    string[] RemoteNames = resEnt.GetPropertyAsArray(@"remoteservername");
                    byte[][] pkt         = resEnt.GetPropertyAsArrayOfBytes("pkt");

                    // Add the namespace-level shares
                    if (RemoteNames != null)
                    {
                        foreach (string name in RemoteNames)
                        {
                            try
                            {
                                if (name.Contains(@"\"))
                                {
                                    DFSShares.Add(new DFSShare
                                    {
                                        Name             = resEnt.GetProperty("name"),
                                        RemoteServerName = name.Split(new char[] { '\\' })[2],
                                        DFSNamespace     = dfsnamespace
                                    });
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Error parsing DFSv1 share : " + e);
                            }
                        }
                    }

                    // add the multi-level stuff
                    if (pkt != null && pkt[0] != null)
                    {
                        List <DFSShare> shares = Parse_Pkt(pkt[0] as byte[]);
                        if (shares != null)
                        {
                            foreach (var share in shares)
                            {
                                DFSShares.Add(share);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Get-DomainDFSShareV1 error : " + e);
            }

            return(DFSShares);
        }
Beispiel #20
0
        public List <DFSShare> FindDfsShares(DirectorySearch domainSearcher)
        {
            List <DFSShare> dfsShares = Get_DomainDFSShare(domainSearcher);

            return(dfsShares);
        }
 public void Setup()
 {
     directorySearch = new DirectorySearch();
     builder = new DirectorySearchOrderBuilder(directorySearch);
 }
Beispiel #22
0
        //FileSearchTest fileSearchTest;


        ////////////////////////////////////////////////////////////////
        ///////////////////생성자
        ////////////////////////////////////////////////////////////////

        public Form1()
        {
            InitializeComponent();
            directorySearch = new DirectorySearch(this);
            //fileSearchTest = new FileSearchTest(this);  //에러난 파일 테스트
        }
Beispiel #23
0
        public void SetDfsPaths()
        {
            DirectorySearch ds = GetDirectorySearcher();

            try
            {
                Mq.Degub("Starting DFS Enumeration.");

                DfsFinder       dfsFinder = new DfsFinder();
                List <DFSShare> dfsShares = dfsFinder.FindDfsShares(ds);

                _dfsSharesDict     = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                _dfsNamespacePaths = new List <string>();
                string realPath;

                foreach (DFSShare dfsShare in dfsShares)
                {
                    // Construct the UNC path to this DFS share and add it to the list.
                    // We use this structure as a to-do list in the ShareFinder code, skipping DFS shares that have already been processed
                    string        dfsShareNamespacePath = @"\\" + _targetDomain + @"\" + dfsShare.DFSNamespace;
                    List <string> hostnames             = new List <string>();

                    if (!_dfsNamespacePaths.Contains(dfsShareNamespacePath))
                    {
                        _dfsNamespacePaths.Add(dfsShareNamespacePath);
                    }

                    // Calculate a long and a short name version for each "real" share path in lowercase.  Admins can set either in AD and
                    //    we may get either for our scan (depending on how we got our computer list.
                    // This simplifies the cross-referencing of actual server shares back to DFS paths in the ShareFinder code.

                    hostnames.Add(dfsShare.RemoteServerName);

                    if (dfsShare.RemoteServerName.EndsWith(_targetDomain, StringComparison.OrdinalIgnoreCase))
                    {   // share path has FQDN so crack out the short hostname
                        hostnames.Add(dfsShare.RemoteServerName.Split('.')[0]);
                    }
                    else
                    {   // share path has short name so append domain for FQDN
                        hostnames.Add(String.Format("{0}.{1}", dfsShare.RemoteServerName, _targetDomain));
                    }

                    // Add these paths as keys in the dictionary
                    foreach (string h in hostnames)
                    {
                        realPath = String.Format(@"\\{0}\{1}", h, dfsShare.Name);

                        if (!_dfsSharesDict.ContainsKey(realPath))
                        {
                            _dfsSharesDict.Add(realPath, dfsShareNamespacePath);
                        }
                    }
                }

                Mq.Info("Found " + _dfsSharesDict.Count.ToString() + " DFS Shares in " + _dfsNamespacePaths.Count.ToString() + " namespaces.");

                Mq.Degub("Finished DFS Enumeration.");
            }
            catch (Exception e)
            {
                Mq.Trace(e.ToString());
            }
        }
Beispiel #24
0
        public static void ProcessSNAC(DataPacket dp)
        {
            switch ((SNACFamily)dp.SNAC.FamilyServiceID)
            {
            case SNACFamily.DirectoryUserSearch:
            {
                DirectorySearch sub = (DirectorySearch)dp.SNAC.FamilySubtypeID;
                switch (sub)
                {
                case DirectorySearch.ClientServerError:             // 0x0001
                    SNACFunctions.ProcessErrorNotification(dp);
                    break;

                case DirectorySearch.SearchUserResponse:             // 0x0003
                    SNAC0F.ProcessSearchResults(dp);
                    break;

                case DirectorySearch.InterestsListResponse:             // 0x0005
                    SNAC0F.ProcessInterestList(dp);
                    break;
                }
            }
            break;

            case SNACFamily.LocationService:
            {
                LocationServices sub = (LocationServices)dp.SNAC.FamilySubtypeID;
                switch (sub)
                {
                case LocationServices.ClientServerError:             // 0x0001
                    SNACFunctions.ProcessErrorNotification(dp);
                    break;

                case LocationServices.UpdateDirectoryInfoResponse:             // 0x000A
                    SNAC02.ProcessUpdateResult(dp);
                    break;

                case LocationServices.SNAC020BReply:
                    SNAC02.ProcessSelfLocationReply(dp);             // 0x000C
                    break;

                case LocationServices.UpdateInterestsResponse:             // 0x0010
                    SNAC02.ProcessUpdateResult(dp);
                    break;

                default:
                    break;
                }
            }
            break;

            case SNACFamily.PrivacyManagementService:
            {
                PrivacyManagementService sub = (PrivacyManagementService)dp.SNAC.FamilySubtypeID;
                switch (sub)
                {
                case PrivacyManagementService.ClientServerError:             // 0x0001
                    SNACFunctions.ProcessErrorNotification(dp);
                    break;

                case PrivacyManagementService.ServiceParametersRequest:             // 0x0002
                    SNAC09.ProcessParametersListRequest(dp);
                    break;

                case PrivacyManagementService.ServiceParametersResponse:             // 0x0003
                    SNAC09.ProcessParametersList(dp);
                    break;

                case PrivacyManagementService.ServiceError:
                    break;

                default:
                    break;
                }
            }
            break;

            case SNACFamily.SSIService:
            {
                SSIService sub = (SSIService)dp.SNAC.FamilySubtypeID;
                switch (sub)
                {
                case SSIService.ClientServerError:             // 0x0001
                    SNACFunctions.ProcessErrorNotification(dp);
                    break;

                case SSIService.ServiceParametersResponse:             // 0x0003
                    SNAC13.ProcessParametersList(dp);
                    break;

                case SSIService.ContactListResponse:             // 0x0006
                    SNAC13.ProcessBuddyList(dp);
                    break;

                case SSIService.SSIEditAddItems:             // 0x0008
                    SNAC13.ProcessItemsAdded(dp);
                    break;

                case SSIService.SSIEditUpdateGroupHeader:             // 0x0009
                    SNAC13.ProcessItemsModified(dp);
                    break;

                case SSIService.SSIEditRemoveItem:             // 0x000A
                    SNAC13.ProcessItemsRemoved(dp);
                    break;

                case SSIService.SSIEditAcknowledge:             // 0x000E
                    SNAC13.ProcessSSIUpdateResponse(dp);
                    break;

                case SSIService.LocalSSIUpToDate:             // 0x000F
                    SNAC13.ProcessSSIUpToDate(dp);
                    break;

                case SSIService.YouWereAddedMessage:             // 0x001C
                    SNAC13.ProcessAddedMessage(dp);
                    break;

                case SSIService.AuthorizationResponse:             // 0x001B
                    SNAC13.ProcessAuthorizationResponse(dp);
                    break;

                case SSIService.FutureAuthorizationGranted:             // 0x0015
                    SNAC13.ProcessFutureAuthorizationGrant(dp);
                    break;

                case SSIService.AuthorizationRequest:             //0x0019
                    SNAC13.ProcessAuthorizationRequest(dp);
                    break;

                default:
                    break;
                }
            }
            break;

            default:
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat(
                    System.Globalization.CultureInfo.CurrentCulture.NumberFormat,
                    "Unknown SNAC: ({0:x4},{1:x4}), flags = {2:x4}, requestID = {3:x8}",
                    dp.SNAC.FamilyServiceID,
                    dp.SNAC.FamilySubtypeID,
                    dp.SNAC.Flags,
                    dp.SNAC.RequestID);
                Logging.DumpFLAP(dp.Data.GetBytes(), sb.ToString());
                break;
            }
        }
Beispiel #25
0
 public virtual void VisitDirectorySearch(DirectorySearch node)
 {
     VisitItem(node.Item);
 }
 public void Setup()
 {
     directorySearch = new DirectorySearch();
     directory = new Mock<IDirectory>();
 }